1
Introduction to Java
History of Java
Java is a general purpose object oriented programming
language.
Developed by Sun Microsystems. (James Gosling)
Initially called “Oak” but was renamed as “Java” in 1995.
Initial motivation is to develop a platform independent
language to create software to be embedded in various
consumer electronics devices (like set top boxes).
Became the language of Internet (portability and security).
2
Java Applications
Desktop applications such as acrobat reader, media player,
anti-virus etc..
Web applications such as irctc.co.in
Enterprise applications such as Banking applications
Mobile applications
Embedded systems
Smart cards
Robotics
Games etc…
Features of Java (java buzzwords)
1. Simple, Small and Familiar
2. Compiled and Interpreted
3. Object Oriented
4. Platform Independent and portable
5. Robust
6. Secure
7. Distributed / Network Oriented
8. Multi-threaded and Interactive
9. High Performance
10. Dynamic
4
Simple, Small and Familiar
Similar to C/C++ in syntax
But eliminates several complexities of
No operator overloading
No direct pointer manipulation or pointer arithmetic
No multiple inheritance
No malloc() and free() – handles memory automatically
5
05/07/2008 Mosarratj Jahan, Dept. of CSE, DU
Compiled and Interpreted
Java works in two stages
Java compiler translate the source code into byte code.
Java interpreter converts the byte code into machine level
representation.
Byte Code:
-A highly optimized set of instructions to be executed by the
java runtime system, known as java virtual machine (JVM).
-Not executable code.
Java Virtual Machine (JVM):
- Need to be implemented for each platform.
- Although the details vary from machine to machine, all JVM
understand the same byte code.
6
05/07/2008 E, DU
Java Virtual Machine
Java compiler produces an intermediate code known as byte
code for a machine, known as JVM.
It exists only inside the computer memory.
Machine code is generated by the java interpreter by acting
as an intermediary between the virtual machine and real
machine.
Java Program Java Compiler Byte code
Byte code Java Interpreter Machine Code
7
05/07/2008 Mosarratj Jahan, Dept. of CSE, DU
Object Oriented
Fundamentally based on OOP
Classes and Objects
Encapsulation
Abstraction
Inheritance
Polymorphism
8
05/07/2008 Mosarratj Jahan, Dept. of CSE, DU
Platform Independent and Portable
“Write-Once Run-Anywhere”
Changes in system platform will not force any change in the
program.
The Java Virtual Machine (JVM) of a particular platform takes
care of it.
Converts byte code into machine level representation.
9
05/07/2008 Mosarratj Jahan, Dept. of CSE, DU
Robust and Secure
Designed with the intention of being secure
No pointer arithmetic or memory management!
Strict compile time and run time checking of data type.
Exception handling
It verifies all memory access
Ensure that no viruses are communicated with an applet.
10
05/07/2008 Mosarratj Jahan, Dept. of CSE, DU
Distributed and Network Oriented
 Java grew up in the days of the Internet
 Inherently network friendly
 Original release of Java came with Networking libraries
 Newer releases contain even more for handling distributed
applications
11
05/07/2008 Mosarratj Jahan, Dept. of CSE, DU
Multi-threaded and Interactive
Handles multiple tasks simultaneously.
Java runtime system contains tools to support multiprocess
synchronization and construct smoothly running interactive
systems.
12
05/07/2008 Mosarratj Jahan, Dept. of CSE, DU
High Performance
Java performance is slower than C
Provisions are added to reduce overhead at runtime.
Incorporation of multi-threading enhance the overall
execution speed.
Just-in-Time (JIT) can compile the byte code into machine
code.
13
05/07/2008 Mosarratj Jahan, Dept. of CSE, DU
Dynamic
Capable of dynamically linking new class libraries,
methods and objects.
Java can use efficient functions available in C/C++.
Installing new version of library automatically updates all
programs
14
05/07/2008 Mosarratj Jahan, Dept. of CSE, DU
Language of Internet Programming
Java Applets
Security
Portability
1. Applets:
Special java program that can be transmitted over the network
and automatically executed by a java-compatible web
browser.
2. Security:
Java compatible web browser can download java applets
without fear of viral infection and malicious agent.
3. Portable:
Java applets can be dynamically downloaded to all the
various types of platforms connected to the internet 15
05/07/2008 Mosarratj Jahan, Dept. of CSE, DU
Why portable and Secure?
. The output of java compiler is not executable code.
Once JVM exists for a platform, any java program can run
on it.
The execution of byte code by the JVM makes java
programs portable.
16
05/07/2008 Mosarratj Jahan, Dept. of CSE, DU
Basics of Java Environments
Java programs normally undergo five phases
Edit
Programmer writes program (and stores program on disk)
Compile
Compiler creates bytecodes from program
Load
Class loader stores bytecodes in memory
Verify
Verifier ensures bytecodes do not violate security requirements
Execute
Interpreter translates bytecodes into machine language
17
Primary
Memory
.
.
.
.
.
.
Disk
Disk
Disk
Editor
Compiler
Class Loader
Program is created in an
editor and stored on
disk in a file ending with
.java.
Compiler creates
bytecodes and stores
them on disk in a file
ending with .class.
Class loader reads
.class files
containing
bytecodes from
disk and puts those
bytecodes in
memory.
Phase 1
Phase 2
Phase 3
Primary
Memory
.
.
.
.
.
.
Bytecode Verifier Bytecode verifier
confirms that all
bytecodes are
valid and do not
violate Java’s
security
restrictions.
Phase 4
Primary
Memory
.
.
.
.
.
.
Interpreter
Interpreter reads
bytecodes and
translates them into a
language that the
computer can
understand, possibly
storing data values as
the program
executes.
Phase 5
18
05/07/2008 Mosarratj Jahan, Dept. of CSE, DU
JRE and JDK
JRE: J2SE Runtime Environment
Provides
 libraries,
 Java virtual machine,
 other components necessary for you to run applets and
applications
JDK: J2SE Development Kit
Includes
 JRE
 command-line development tools such as compilers and
debuggers
Versions of Java
Three versions of the Java 2 Platform, targeted at different uses
Java 2 Micro Edition (J2ME)
Very small Java environment for smart cards, phones, and
set-top boxes
Subset of the standard Java libraries aimed at limited size
and processing power
Java 2 Standard Edition (J2SE)
The basic platform
J2SE can be used to develop client-side standalone
applications or applets.
Java 2 Enterprise Edition (J2EE)
For business applications, web services.
20
Procedure Oriented Programming
Large problem is divided into smaller programs known as modular
programming.
Main program
Function-1 Function-2 Function-3
Function-4 Function-5
Procedure Oriented Programming
Data move openly around from function to function.
Global Data Global Data
Function-1 Function-2 Function-3
Local Data Local Data Local Data
Object –Oriented Programming
Programs are divided into objects.
Objects can communicate with each other through methods
(functions).
Data
Functions
Data
Functions
Functions
Data
Object A Object B
Object C
Differences between C and Java
Java does not include sizeof, typedef key words.
No struct, union data types.
No type modifiers as auto, extern, register, signed,
unsigned.
Does not support explicit pointer type.
No pre-processor so, we can not use #define, #include,
#ifdef etc..
Java adds new operators such as instanceof and >>>.
Contains labelled break and continue statements.
 Java includes lot of object oriented features.
Differences between C++ and Java
Java does not support operator overloading.
Does not have template classes as in C++.
Does not support multiple inheritance. (But can be done
indirectly with interfaces).
No global variables.
No destructors but use finalize() for that purpose.
No header files, pointers etc..
Note: C++ is superset of C but Java is neither superset nor
subset of C or C++.
Java Program
Java Source
Code
Java Compiler
Java Enabled
Browser Java Interpreter
Application Type
Applet Type
Output
Output
First Java Program-Example 1
/*This is a simple java program*/
class Example
{
public static void main (String args[])
{
System.out.println (“Welcome to Java”);
}
}
Simple Java Program-Some points
public: Access specifier. main() must be made public, since it must
be visible to code defined outside it’s class.
Static: It is required because main() is called without creating an
object of it’s class
String args[]: An array of objects of type String class. Each object
of type string contains a character string. It is used to manipulate
command line arguments.
Java is case sensitive.
System predefined class that refers to system.
out It is static data member of System class
println() It is a method of out object
Implementing a Java Program
1. Creating a java program
2. Compiling a java program
3. Running the program
Creating a Java Program:
1. All java source files have an extension .java.
2. If a program contains multiple classes, the file name must be
the class name of the class containing the main method. This
class must be the only public class.
[Rule: File name should match the name of the public class of a
source code.]
Implementing a Java Program
Compiling a Java Program:
To compile a java program, execute the java compiler javac,
specifying the name of the source file on the command line. C:>
javac Example.java
When java source code is compiled, each individual class is put
into it’s own output file named after the class and using the .class
extension.
Each file with .class extension contains the bytecode
corresponding to that class
Implementing a Java Program
To run the program, interpreter java uses the name of the class
that contains the main function.
c:> java Example
Actually it searches for Example. class file.
Second Java Program
class AddNum
{
public int add(int x,int y)
{
return (x+y);
}
}
public class Test
{
public static void main(String args[])
{
int a, b;
a=100;
b=23;
AddNum ob = new AddNum();
System.out.println(“The addition: “+
ob.add(a,b));
}
}
Points to be Noted
Java source code can contain multiple classes, the name of the
source code must be the name of the only public class of the
code.
Usually one class contains the main() method, that is the
starting point of program execution.
Object of a class is created using new operator.
Method of a class is accessed through an object of that class.
+ in System.out.println() method concatenates two strings.
Java is a Strongly typed Language
Every variable and expression has a strongly defined type.
All assignments are checked for type compatibility.
Java compiler checks all expressions and parameters to ensure that
the types are compatible.
The Primitive Data Types
There are exactly eight primitive data types in Java
byte, short, int, long
float, double
char
boolean
Numeric Data Types
The difference between the various numeric primitive types is their
size, and therefore the values they can store:
Type
byte
short
int
long
float
double
Storage
8 bits
16 bits
32 bits
64 bits
32 bits
64 bits
Min Value
-128
-32,768
-2,147,483,648
-9 x 1018
+/- 3.4 x 1038 with 7 significant digits
+/- 1.7 x 10308 with 15 significant digits
Max Value
127
32,767
2,147,483,647
9 x 1018
Character Type
It uses unicode to represent character.
The char type is unsigned 16 bit value ranging from 0 to
65535. ASCII still ranges from 0 to 127.
Example:
class Test
{public static void main (String args[])
{
char ch1, ch2;
ch1=88;
ch2=‘Y’;
System.out.println (“ch1 and ch2: “ + ch1+” “+ch2);
}
} Output: ch1 and ch2: X Y
Character Type
class test
{
public static void main (String args[])
{
char ch;
ch= ‘X’;
Sytem.out.println (“ch contains “+ch);
ch++;
System.out.println (“ch is now “ + ch);
}
}
Output:
ch contains X
ch is now Y
Booleans
 Size is 1 bit – two values: true and false.
 This type is returned by all relational operators.
 Example:
boolean b;
b= true;
1. System.out.println(“b is “+b);
2. System.out.println(“10<9 is “ +(10<9));
Output:
b is true
10<9 is false
Literals
Integer Literals
1. base 10 – 1,2,43 etc.
2. base 8 – octal values are denoted in java by a leading 0.
3. base 16 – hexadecimal values are denoted by leading 0x
or 0X.
 Any whole number is by default integer (32 bits).
 To specify a long literal, the number should be appended
with an upper or lowercase L.
Literals
Floating point Literals
1. Standard Notation : 3.14159, 0.6667, 2.0 etc.
2. Scientific Notation : 6.022E23, 2e+100.
 Floating point literals are by default of type double.
 To specify a float literal, we must append an F or f to the
constant.
Boolean Literals
 Two values : true and false.
 True is not equal to 1 and false is not equal to 0.
 They can be assigned to variable declared as boolean.
Literals
Character Literals:
 A literal character is represented inside a pair of single
quotes.
String Literals:
A sequence of characters between a pair of double quotes.
In java string must begin and end on the same line.
Variables
Variable is a name for a location in memory.
Declaring a variable:
type identifier [=value][,identifier [=value]….];
The initialization expression must result in a value of the
same or compatible type as that specified for the variable.
Scope and Lifetime of a variable
A block begins with an opening curly brace and ends by a
closing curly brace.
A block determines scope, that defines which objects are visible
to other parts of your program.
Variables declared within a block localize themselves.
In case of nested block, the outer block encloses the inner
block. The variables declared in the outer block is visible to the
inner block but the reverse is not true.
A variable will not hold it’s value once it has gone out of it’s
scope.
In an inner block, it is not possible to declare a variable of the
same name as in outer block.
Scope and Lifetime of a variable
Example
public static void main( String args[])
{
int x =10;
if ( x == 10)
{
int y =20;
System.out.println(“x and y: “ +x +” “+y);
x= y * 2;
}
y= 100; //Error
System.out.println (“x is “+x);
}
Automatic Type Conversion
When one type of data is assigned to another type of variable,
an automatic type conversion will take place if:
1. Two types are compatible.
2. The destination type is larger than the source type.
It is known as widening conversion.
The numeric types, including integer and floating point types
are compatible.
Numeric types are not compatible with char or boolean.
Char and boolean are not compatible with each other.
Casting Type
Problem: assigning int value to a byte type variable.
This type of conversion is known as narrowing conversion.
A cast is simply an explicit type conversion : (target_type) value
Example:
int a;
byte b;
….
b = (byte) a;
Contains the remainder of an integer division by byte’s range.
Casting Type
class test
{
public static void main(String args[])
{
byte b;
int i = 257;
double d = 323.142;
b=(byte)i;
System.out.println (“Conversion of int to byte: ” + i +” “+ b);
i=(int)d;
System.out.println(“Conversion of double to int: “ +d+” “+i);
b=(byte)d;
System.out.println(“Conversion of double to byte: “ +d+” “+b);
}
}
Casting Type
Output:
Conversion of int to byte: 257 1
Conversion of double to int: 323.142 323
Conversion of double to byte: 323.142 67
Note:
When assigning a fractional number’s to a whole number’s
variable, fractional part is truncated.
If the value of the whole number part is too large to fit into the
target integer type, then that value will be reduced modulo the
target type’s range.
Automatic Type Promotion in Expression
Takes place in expression.
Rules:
1. All byte and short values are promoted to int.
2. If one operand is long, the whole expression is promoted to
long.
3.If one operand is float, the entire expression is promoted to
float.
4. If one operand is double, the entire expression is promoted
to double.
Automatic Type Promotion-Example
byte b =42;
char c=‘a’;
short s=1024;
int i=50000;
float f=5.67f;
double d=.1234;
double result = (f * b) + (i / c) – (d * s);
1. (f * b) is promoted to float.
2. (i / c) is promoted to int.
3. (d *s ) is promoted to double.
4. float + int – double = float – double = double
Automatic Type Conversion-Example
1. byte a =40, b= 50, c =100;
int d = a * b /c;
2. byte b =50;
b = b * 2; //Error
Operators in Java
Classified into four groups:
1. Arithmetic Operator
2. Bitwise Operator
3. Relational Operator
4. Logical Operator
Arithmetic Operators
Addition +
Subtraction -
Multiplication *
Division /
Remainder %
Increment ++
Addition Assignment +=
Subtraction Assignment -=
Multiplication Assignment *=
Division Assignment /=
Modulus Assignment %=
Decrement --
Arithmetic Operators
If either or both operands associated with an arithmetic operator are
floating point, the result is a floating point.
% operator applies both to floating-point type and integer types.
class modulus
{
public static void main (String args [])
{
int x = 42;
double y = 42.3;
System.out.println(“x mod 10 =“ + x%10);
System.out.println(“y mod 10 = “ + y%10);
}
}
Output:
x mod 10 =2
y mod 10 = 2.3
Bitwise Operator
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
>> Shift Right
>>> Shift Right zero fill
<< Shift left
Applied to integer type – long, int, short, byte and char.
The Left Shift
byte a=8, b=24;
int c;
c=a<<2; 00001000 << 2 = 00100000=32
Java’s automatic type conversion produces unexpected result when
shifting byte and short values.
Example:
byte a = 64, b;
int i;
i = a<<2;
b= (byte) (a<<2);
i 00000000 00000000 00000001 00000000 = 256
b 00000000 = 0
Each left shift double the value which is equivalent to multiplying
by 2.
The Right Shift
byte a=8, b=24;
int c ;
c=a>>2; 00001000 >> 2= 00000010=2
Use sign extension.
Each time we shift a value to the right, it divides that value by two
and discards any remainder.
The Unsigned Right Shift
byte a=8, b=24;
int c;
c=a>>>1 00001000 >>> 1= 00000100=4
Relational operators
> greater than
>= greater than or equal to
< less than
<= less than or equal to
= = equal to
!= not equal to
The outcome of these operations is a boolean value.
= = , != can be applied to any type in java.
Only numeric types are compared using ordering operator.
Relational Operators
int done;
……
if(!done) …. // Valid in C /C++ but not in java
if(done)….
if (done == 0)….
if(done!=0) …….. //Valid in Java
istanceof Operator
 Student s= new Student();
 Person p= new Person();
 boolean b;
 b= s instanceof Student; // Here b =true
 b= s instanceof Person; // Here b =false
Operator Precedence
Highest
1. ( ) [] .
2. ++ -- ~ !
3. * / %
4. + -
5. >> >>> <<
6. > >= < <=
7. = = !=
8. &
9. ^
10. |
11. &&
12. ||
13. ?:
14. = op=
Lowest
Decision Making and Branching
When a program breaks the sequential flow and jumps to another
part of the code, it is known as branching. When branching is
done on a condition it is known as conditional branching.
Three decision making statements:
1. if statement
2. switch statement
3. conditional operator statement
The Conditional Operator
 Java has a conditional operator that evaluates a boolean condition that
determines which of two other expressions is evaluated
 The result of the chosen expression is the result of the entire conditional
operator
 Its syntax is:
 condition ? expression1 : expression2
 If the condition is true, expression1 is evaluated; if it is false, expression2 is
evaluated
The Conditional Operator
 The conditional operator is similar to an if-else statement, except that it forms an
expression that returns a value
 For example:
 larger = ((num1 > num2) ? num1 : num2);
 if (num1 > num2)
larger = num1;
else
larger = num2;
 The conditional operator is ternary because it requires three operands
Repetition Statements
Repetition statements allow us to execute a statement
multiple times
They are referred to as loops
Like conditional statements, they are controlled by boolean
expressions
Java has three kinds of repetition statements:
the while loop
the do loop
the for loop
The programmer should choose the right kind of loop for
the situation
Choosing a Loop Structure
When you can’t determine how many times you want to execute
the loop body, use a while statement or a do statement
If it might be zero or more times, use a while statement
If it will be at least once, use a do statement
If you can determine how many times you want to execute the
loop body, use a for statement
For each loop (Enhanced for loop)
Labeled break and continue
The General Form of a Class
 A class is defined by specifying the data and the code that operates on the data.
 The general form:
class classname
{
type instance-variable1;
type instance-variable2;
…………
type methodname1( parameter-list)
{
// body of the method
}
type methodname2( parameter-list)
{
//body of the method
}
……………………
}
Class and Object
A class defines a new data type. This new data type is used to
create objects of that type.
A class is a template for an object and an object is an instance of a
class.
To allocate a physical memory new() is used. It dynamically
allocates memory for an object and returns a reference to it.
In Java, all class objects must be dynamically allocated.
A Simple Example
class Box
{
double width;
double height;
double depth;
}
class BoxDemo
{
public static void main( String args[])
{
Box mybox, mybox1;
mybox = new Box();
mybox1 = new Box();
mybox.width=10;
mybox.height = 20;
mybox. depth = 15;
mybox1.width = 10;
mybox1.height = 25;
mybox1.depth=5;
}
}
A Closer Look at New
Box mybox;
mybox = new Box();
Box b1 = new Box();
Box b2 = b1;
null mybox
mybox
Width
Height
Depth
Call to the default constructor defined
by the compiler. It initializes the
instance variables to 0.
Width
Height
Depth
b1
b2
Instance variables
Default initialization
If the variable is within a method, Java does NOT initialize
it.
If the variable is within a class, Java initializes it as follows:
 Numeric instance variables initialized to 0
 Logical instance variables initialized to false
 Object instance variables initialized to null
Import Statement
A java package is a collection of related classes.
In order to access the available classes in the package,
the program must specify the complete dot seperated
package path.
The general format:
import package-level1.[package-level2.]classname|*
Example:
import java.util.Scanner;
import java.util.*;
Example
import java.util.Random;
class random
{
public static void main(String args[])
{
Random r = new Random();
int i;
float v;
for(i=0;i<5;i++)
{
v=r.nextFloat();
System.out.println(v);
}
}
}
Output:
java.lang is automatically imported with every java program.
System.out.println() belongs to java.lang.
Predefined Stream
Stream:
-A stream is an abstraction that either produces or consumes
information.
-It is linked to a physical device by a java I/O system.
-It hides the details of the physical device to which they are
connected.
System:
-System is a predefined class included in the package java.lang.
(Imported automatically by all java programs).
-It includes three predefined stream variables:
1. in 2. out. 3. err
The Predefined Streams
1. System.out: refers to the standard output stream. It is an
object of type PrintStream.
2. System.in: refers to the standard input stream. It is an object
of type InputStream.
3. System.err: refers to the standard error stream. It is an object
of type PrintStream.
Note: they are defined as public and static.
InputStream:
- This class is included in the package java.io.
- It has some subclasses the handle the differences between
various devices.
- Includes some methods that the subclasses will implement.
Taking Input from the Keyboard
First, Scanner class is connected to System.in which is
an object of type InputStream.
Then, it uses it’s internal functions to read from
System.in
Example:
Scanner test = new Scanner(System.in);
Take an input from the keyboard
import java.util.*;
public static void main(String[] args) {
int value;
System.out.print(“Enter an Integer number:");
Scanner tmp = new Scanner(System.in);
if(tmp.hasNextInt())
{
value=tmp.nextInt();
System.out.println(“You have entered: ”+value);
}
else
System.out.println(“Not an Integer”);
}
One-Dimensional Array
Creating an array is a two steps process:
1. type var_name[];
2. var_name = new type [size];
Example: int month_days [];
month_days = new int [12];
- first line declares month_days as an array variable, no array
actually exists.
- Actual, physical array of integers, is allocated using new
and assign it to month_days.
-The elements of array are automatically initialized to 0.
int month_days [] = new int[12];
One-Dimensional Array
Once array is created, a specific element in the array can be
accessed by specifying it’s index within square brackets.
Example: month_days[0]=31;
month_days[1]=28;
Arrays can be initialized when they are declared.
Example:
int month_days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31,
30, 31};
Features of Java to Manipulate Array
All arrays are dynamically allocated.
Size of the array can be specified at the run time.
Index type is integer and the index range must be 0 to n-1,
where n is the number of elements.
Java run time system will check to be sure that all array indices
are in the correct range. Incorrect reference will generate
ArrayIndexOutofBoundsException.
Example
import java.util.Scanner;
class array_avg
{
public static void main(String args[])
{
int i,sum=0;
float avg;
int a[] = new int[5];
Scanner test=new Scanner(System.in);
System.out.println("Enter the input:");
for(i=0;i<5;i++)
{
a[i]=test.nextInt();
sum=sum+a[i];
}
avg=sum/5;
System.out.println("The average value is: " + avg);
}
}
Array in Java
int a[];
int b[] = null;
int c[] = new int[5];
int d[] = { 1, 2, 3, 4, 5 };
a = c;
d = c;
1 2 3 4 5
0 0 0 0 0
null
a
-
b null
c
d
Multi-Dimensional Arrays
A two-dimensional array can be declared as
int twoD [ ] [ ] = new int[4][5];
[0][0] [0][1
] [0][2] [0][3] [0][4]
Represents row
Represents column
Example
int tmp[][] = new int[3][3];
int i,j;
Scanner test=new Scanner(System.in);
for(i=0;i<3;i++)
for(j=0;j<3;j++)
{
System.out.print("Enter Input:");
tmp[i][j]=test.nextInt();
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
System.out.print(tmp[i][j] + " ");
System.out.println();
}
Multi-dimensional Array
int twoD [][] = new int[4][];
twoD[0] = new int[5];
twoD[1] = new int[4];
twoD[2] = new int[3];
int m [][]={{1,2},{2,3}};
Example – jagged array
int a[][]=new int[3][];
a[0]=new int[1];
a[1]=new int[2];
a[2]=new int[3];
int i,j,k=0;
for(i=0;i<3;i++)
for(j=0;j<i+1;j++)
{
a[i][j]=k;
k++;
}
for(i=0;i<3;i++)
{
for(j=0;j<a[i].length;j++)
System.out.print(a[i][j]+” “);
System.out.println();
}
Output:
0
1 2
3 4 5
Alternative Array Declaration Syntax
Type [] var_name;
Example: int [] a = new int[3];
int [] num1, num2, num3;
same as
int num1[], num2[], num3[];
Array as an Object
An array is implemented as an object.
It has a special attribute: length instance variable.
Example:
int a1[] = new int[10];
int a2[] = {3, 5, 7, 9, 11, 13, 15, 17};
int a3[] = {4, 3, 2, 1};
System.out.println(“length of a1 is: ”+a1.length);
System.out.println(“length of a2 is: ”+a2.length);
System.out.println(“length of a3 is: ”+a3.length);
Class-Methods
class Box
{
double length;
double breadth;
double height;
}
 Write Java programs by including volume( ) method to calculate
volume of a box with and with out passing parameters in different
ways.
Also, add a method setDim( ) to set the dimensions of a box then
use them to calculate volume.
Class- Constructors
Constructor name must be same as class name
A constructor must have no explicit return type.
A constructor in Java can not be abstract, static,final and
synchronized.
We can use access modifiers while declaring a constructor. It
controls object creation.
Constructors may be default or parameterized.
Write Java programs by including volume( ) method to calculate
volume of a box by initializing instance variables in a constructor.
Also write program with parameterized constructors.
The key word- this
this is a key word with which we can refer to the current object.
this can be used to invoke the current class instance variable.
this can be used to invoke the current class method.
this can be used to invoke the current class constructor.
this can be passed as an argument in the method call or
constructor call.
Method overloading, Constructor overloading programs.
abs(), labs(), fabs()
Java- finalize() method:
Memory de-allocation is done automatically in Java.
The finalize() method is called just before an object is
destroyed (de-allocated).
 Inside the finalize( ) we will specify those actions that
must be performed before an object is destroyed.
The finalize( ) method has this general form:
protected void finalize( )
{ // finalization code here
}
Object as parameter
class Test
{
int a, b;
Test(int i, int j)
{ a = i; b = j;
}
boolean equals(Test o)
{ if(o.a == a && o.b == b) return true; else return false;
}
}
class PassOb
{
public static void main(String args[])
{
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
System.out.println("ob1 == ob2: " + ob1.equals(ob2));
System.out.println("ob1 == ob3: " + ob1.equals(ob3));
}
}
Pass By Value
class Test
{
void meth(int i, int j)
{
i *= 2; j /= 2;
}
}
class CallByValue
{
public static void main(String args[])
{
Test ob = new Test();
int a = 15, b = 20;
System.out.println("a and b before call: " + a + " " + b);
ob.meth(a, b);
System.out.println("a and b after call: " + a + " " + b);
}
}
Pass By Reference
class Test
{
int a, b;
Test(int i, int j)
{ a = i; b = j;
}
void meth(Test o)
{
o.a *= 2; o.b /= 2;
}
}
class CallByRef
{
public static void main(String args[])
{
Test ob = new Test(15, 20);
System.out.println("ob.a and ob.b before call:"+ob.a+" "+ob.b);
ob.meth(ob);
System.out.println("ob.a and ob.b after call:"+ob.a+" "+ob.b);
}
}
Returning Objects
class Test
{
int a;
Test(int i)
{ a = i; }
Test incrByTen()
{ Test temp = new Test(a+10);
return temp; }
}
class RetOb
{
public static void main(String args[])
{
Test ob1 = new Test(10);
Test ob2;
ob2 = ob1.incrByTen();
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);
ob2 = ob2.incrByTen();
System.out.println("ob2.a after second increase: "+ ob2.a);
}
Static keyword in Java
The static keyword in Java is used for memory management
mainly.
We can apply java static keyword with variables, methods and
blocks.
The static variable can be used to refer to the common property
of all objects (which is not unique for each object).
The static variable gets memory only once in the class area at
the time of class loading.
Counter() ---program
Static keyword in Java
 If we apply static keyword with any method, it is known as static
method.
 A static method belongs to the class rather than the object of a
class.
 A static method can be invoked without the need for creating an
instance of a class.
 A static method can access static data member and can change
the value of it.
There are two main restrictions for the static method. They are:
(1)The static method can not use non static data member or call
non-static method directly. (2) this and super cannot be used in
static context.
Static keyword in Java
 Java static block used to initialize the static data members .
 It is executed before the main method at the time of
classloading.
class StaticTest
{ static
{ System.out.println("static block is invoked"); }
public static void main(String args[])
{ System.out.println("Hello main"); }
}
Wrapper Class
 wrapper classes provide a way to use primitive data
types (int, char, short, byte, etc) as objects.
These wrapper classes come under java.util package.
• Autoboxing in Wrapper Class
Autoboxing is used to convert primitive data types into
corresponding objects.
• Unboxing in Wrapper Class
Unboxing is used to convert the Wrapper class object into
corresponding primitive data types.
• Autoboxing
Class Autoboxing
{
public static void main(String args[])
{
int a=50;
Integer obj1=new Integer(a);
Integer obj2=Integer.valueOf(a);
Integer obj3=a;
System.out.println(obj1 +” “+obj2+” “+obj3);
}}
• Unboxing
Class Unboxing
{
public static void main(String args[])
{
int a=50;
Integer obj=new Integer(a);
Int x=obj.intValue();
Int y=obj;
System.out.println(a +” “+x+” “+” “+y+” “+obj);
}}
• Wrapper Class Uses
Serialization: We need to convert the objects into streams to
perform the serialization. If we have a primitive value, we can
convert it in objects through the wrapper classes.
Synchronization: Java synchronization works with objects in
Multithreading.
java.util package: The java.util package provides the utility
classes to deal with objects.
Collection Framework: Java collection framework works with
objects only. All classes of the collection framework (ArrayList,
LinkedList, Vector, HashSet, LinkedHashSet, TreeSet,
PriorityQueue, ArrayDeque, etc.) deal with objects only.
Access Control in Java
Java’s access specifiers are public, private, and protected.
Java also defines a default access level.
protected applies only when inheritance is involved.
When a member of a class is modified by the public specifier,
then that member can by accessed by any other code.
When a member of a class is specified as private, then that
member can only be accessed by other members of its class.
 main( ) has always been preceded by the public specifier. It is
called by code that is outside the program—that is, by the Java
run-time system.
When no access specifier is used, then by default the member
of a class is public within its own package, but cannot be
accessed outside of its package.
Access Control in Java
Write a Stack program by taking top as private and perform push(),pop()
operations
Final keyword in Java
The final keyword in java is used to restrict the user.
The java final keyword can be used in many context.
Final can be applied on variable, method or class.
Final variable can not be changed.
Final method can not be overriden.
Final class can not be extended.

Java-Unit-I.ppt

  • 1.
  • 2.
    History of Java Javais a general purpose object oriented programming language. Developed by Sun Microsystems. (James Gosling) Initially called “Oak” but was renamed as “Java” in 1995. Initial motivation is to develop a platform independent language to create software to be embedded in various consumer electronics devices (like set top boxes). Became the language of Internet (portability and security). 2
  • 3.
    Java Applications Desktop applicationssuch as acrobat reader, media player, anti-virus etc.. Web applications such as irctc.co.in Enterprise applications such as Banking applications Mobile applications Embedded systems Smart cards Robotics Games etc…
  • 4.
    Features of Java(java buzzwords) 1. Simple, Small and Familiar 2. Compiled and Interpreted 3. Object Oriented 4. Platform Independent and portable 5. Robust 6. Secure 7. Distributed / Network Oriented 8. Multi-threaded and Interactive 9. High Performance 10. Dynamic 4
  • 5.
    Simple, Small andFamiliar Similar to C/C++ in syntax But eliminates several complexities of No operator overloading No direct pointer manipulation or pointer arithmetic No multiple inheritance No malloc() and free() – handles memory automatically 5 05/07/2008 Mosarratj Jahan, Dept. of CSE, DU
  • 6.
    Compiled and Interpreted Javaworks in two stages Java compiler translate the source code into byte code. Java interpreter converts the byte code into machine level representation. Byte Code: -A highly optimized set of instructions to be executed by the java runtime system, known as java virtual machine (JVM). -Not executable code. Java Virtual Machine (JVM): - Need to be implemented for each platform. - Although the details vary from machine to machine, all JVM understand the same byte code. 6 05/07/2008 E, DU
  • 7.
    Java Virtual Machine Javacompiler produces an intermediate code known as byte code for a machine, known as JVM. It exists only inside the computer memory. Machine code is generated by the java interpreter by acting as an intermediary between the virtual machine and real machine. Java Program Java Compiler Byte code Byte code Java Interpreter Machine Code 7 05/07/2008 Mosarratj Jahan, Dept. of CSE, DU
  • 8.
    Object Oriented Fundamentally basedon OOP Classes and Objects Encapsulation Abstraction Inheritance Polymorphism 8 05/07/2008 Mosarratj Jahan, Dept. of CSE, DU
  • 9.
    Platform Independent andPortable “Write-Once Run-Anywhere” Changes in system platform will not force any change in the program. The Java Virtual Machine (JVM) of a particular platform takes care of it. Converts byte code into machine level representation. 9 05/07/2008 Mosarratj Jahan, Dept. of CSE, DU
  • 10.
    Robust and Secure Designedwith the intention of being secure No pointer arithmetic or memory management! Strict compile time and run time checking of data type. Exception handling It verifies all memory access Ensure that no viruses are communicated with an applet. 10 05/07/2008 Mosarratj Jahan, Dept. of CSE, DU
  • 11.
    Distributed and NetworkOriented  Java grew up in the days of the Internet  Inherently network friendly  Original release of Java came with Networking libraries  Newer releases contain even more for handling distributed applications 11 05/07/2008 Mosarratj Jahan, Dept. of CSE, DU
  • 12.
    Multi-threaded and Interactive Handlesmultiple tasks simultaneously. Java runtime system contains tools to support multiprocess synchronization and construct smoothly running interactive systems. 12 05/07/2008 Mosarratj Jahan, Dept. of CSE, DU
  • 13.
    High Performance Java performanceis slower than C Provisions are added to reduce overhead at runtime. Incorporation of multi-threading enhance the overall execution speed. Just-in-Time (JIT) can compile the byte code into machine code. 13 05/07/2008 Mosarratj Jahan, Dept. of CSE, DU
  • 14.
    Dynamic Capable of dynamicallylinking new class libraries, methods and objects. Java can use efficient functions available in C/C++. Installing new version of library automatically updates all programs 14 05/07/2008 Mosarratj Jahan, Dept. of CSE, DU
  • 15.
    Language of InternetProgramming Java Applets Security Portability 1. Applets: Special java program that can be transmitted over the network and automatically executed by a java-compatible web browser. 2. Security: Java compatible web browser can download java applets without fear of viral infection and malicious agent. 3. Portable: Java applets can be dynamically downloaded to all the various types of platforms connected to the internet 15 05/07/2008 Mosarratj Jahan, Dept. of CSE, DU
  • 16.
    Why portable andSecure? . The output of java compiler is not executable code. Once JVM exists for a platform, any java program can run on it. The execution of byte code by the JVM makes java programs portable. 16 05/07/2008 Mosarratj Jahan, Dept. of CSE, DU
  • 17.
    Basics of JavaEnvironments Java programs normally undergo five phases Edit Programmer writes program (and stores program on disk) Compile Compiler creates bytecodes from program Load Class loader stores bytecodes in memory Verify Verifier ensures bytecodes do not violate security requirements Execute Interpreter translates bytecodes into machine language 17
  • 18.
    Primary Memory . . . . . . Disk Disk Disk Editor Compiler Class Loader Program iscreated in an editor and stored on disk in a file ending with .java. Compiler creates bytecodes and stores them on disk in a file ending with .class. Class loader reads .class files containing bytecodes from disk and puts those bytecodes in memory. Phase 1 Phase 2 Phase 3 Primary Memory . . . . . . Bytecode Verifier Bytecode verifier confirms that all bytecodes are valid and do not violate Java’s security restrictions. Phase 4 Primary Memory . . . . . . Interpreter Interpreter reads bytecodes and translates them into a language that the computer can understand, possibly storing data values as the program executes. Phase 5 18 05/07/2008 Mosarratj Jahan, Dept. of CSE, DU
  • 19.
    JRE and JDK JRE:J2SE Runtime Environment Provides  libraries,  Java virtual machine,  other components necessary for you to run applets and applications JDK: J2SE Development Kit Includes  JRE  command-line development tools such as compilers and debuggers
  • 20.
    Versions of Java Threeversions of the Java 2 Platform, targeted at different uses Java 2 Micro Edition (J2ME) Very small Java environment for smart cards, phones, and set-top boxes Subset of the standard Java libraries aimed at limited size and processing power Java 2 Standard Edition (J2SE) The basic platform J2SE can be used to develop client-side standalone applications or applets. Java 2 Enterprise Edition (J2EE) For business applications, web services. 20
  • 21.
    Procedure Oriented Programming Largeproblem is divided into smaller programs known as modular programming. Main program Function-1 Function-2 Function-3 Function-4 Function-5
  • 22.
    Procedure Oriented Programming Datamove openly around from function to function. Global Data Global Data Function-1 Function-2 Function-3 Local Data Local Data Local Data
  • 23.
    Object –Oriented Programming Programsare divided into objects. Objects can communicate with each other through methods (functions). Data Functions Data Functions Functions Data Object A Object B Object C
  • 24.
    Differences between Cand Java Java does not include sizeof, typedef key words. No struct, union data types. No type modifiers as auto, extern, register, signed, unsigned. Does not support explicit pointer type. No pre-processor so, we can not use #define, #include, #ifdef etc.. Java adds new operators such as instanceof and >>>. Contains labelled break and continue statements.  Java includes lot of object oriented features.
  • 25.
    Differences between C++and Java Java does not support operator overloading. Does not have template classes as in C++. Does not support multiple inheritance. (But can be done indirectly with interfaces). No global variables. No destructors but use finalize() for that purpose. No header files, pointers etc.. Note: C++ is superset of C but Java is neither superset nor subset of C or C++.
  • 26.
    Java Program Java Source Code JavaCompiler Java Enabled Browser Java Interpreter Application Type Applet Type Output Output
  • 27.
    First Java Program-Example1 /*This is a simple java program*/ class Example { public static void main (String args[]) { System.out.println (“Welcome to Java”); } }
  • 28.
    Simple Java Program-Somepoints public: Access specifier. main() must be made public, since it must be visible to code defined outside it’s class. Static: It is required because main() is called without creating an object of it’s class String args[]: An array of objects of type String class. Each object of type string contains a character string. It is used to manipulate command line arguments. Java is case sensitive. System predefined class that refers to system. out It is static data member of System class println() It is a method of out object
  • 29.
    Implementing a JavaProgram 1. Creating a java program 2. Compiling a java program 3. Running the program Creating a Java Program: 1. All java source files have an extension .java. 2. If a program contains multiple classes, the file name must be the class name of the class containing the main method. This class must be the only public class. [Rule: File name should match the name of the public class of a source code.]
  • 30.
    Implementing a JavaProgram Compiling a Java Program: To compile a java program, execute the java compiler javac, specifying the name of the source file on the command line. C:> javac Example.java When java source code is compiled, each individual class is put into it’s own output file named after the class and using the .class extension. Each file with .class extension contains the bytecode corresponding to that class
  • 31.
    Implementing a JavaProgram To run the program, interpreter java uses the name of the class that contains the main function. c:> java Example Actually it searches for Example. class file.
  • 32.
    Second Java Program classAddNum { public int add(int x,int y) { return (x+y); } } public class Test { public static void main(String args[]) { int a, b; a=100; b=23; AddNum ob = new AddNum(); System.out.println(“The addition: “+ ob.add(a,b)); } }
  • 33.
    Points to beNoted Java source code can contain multiple classes, the name of the source code must be the name of the only public class of the code. Usually one class contains the main() method, that is the starting point of program execution. Object of a class is created using new operator. Method of a class is accessed through an object of that class. + in System.out.println() method concatenates two strings.
  • 34.
    Java is aStrongly typed Language Every variable and expression has a strongly defined type. All assignments are checked for type compatibility. Java compiler checks all expressions and parameters to ensure that the types are compatible.
  • 35.
    The Primitive DataTypes There are exactly eight primitive data types in Java byte, short, int, long float, double char boolean
  • 36.
    Numeric Data Types Thedifference between the various numeric primitive types is their size, and therefore the values they can store: Type byte short int long float double Storage 8 bits 16 bits 32 bits 64 bits 32 bits 64 bits Min Value -128 -32,768 -2,147,483,648 -9 x 1018 +/- 3.4 x 1038 with 7 significant digits +/- 1.7 x 10308 with 15 significant digits Max Value 127 32,767 2,147,483,647 9 x 1018
  • 37.
    Character Type It usesunicode to represent character. The char type is unsigned 16 bit value ranging from 0 to 65535. ASCII still ranges from 0 to 127. Example: class Test {public static void main (String args[]) { char ch1, ch2; ch1=88; ch2=‘Y’; System.out.println (“ch1 and ch2: “ + ch1+” “+ch2); } } Output: ch1 and ch2: X Y
  • 38.
    Character Type class test { publicstatic void main (String args[]) { char ch; ch= ‘X’; Sytem.out.println (“ch contains “+ch); ch++; System.out.println (“ch is now “ + ch); } } Output: ch contains X ch is now Y
  • 39.
    Booleans  Size is1 bit – two values: true and false.  This type is returned by all relational operators.  Example: boolean b; b= true; 1. System.out.println(“b is “+b); 2. System.out.println(“10<9 is “ +(10<9)); Output: b is true 10<9 is false
  • 40.
    Literals Integer Literals 1. base10 – 1,2,43 etc. 2. base 8 – octal values are denoted in java by a leading 0. 3. base 16 – hexadecimal values are denoted by leading 0x or 0X.  Any whole number is by default integer (32 bits).  To specify a long literal, the number should be appended with an upper or lowercase L.
  • 41.
    Literals Floating point Literals 1.Standard Notation : 3.14159, 0.6667, 2.0 etc. 2. Scientific Notation : 6.022E23, 2e+100.  Floating point literals are by default of type double.  To specify a float literal, we must append an F or f to the constant. Boolean Literals  Two values : true and false.  True is not equal to 1 and false is not equal to 0.  They can be assigned to variable declared as boolean.
  • 42.
    Literals Character Literals:  Aliteral character is represented inside a pair of single quotes. String Literals: A sequence of characters between a pair of double quotes. In java string must begin and end on the same line.
  • 43.
    Variables Variable is aname for a location in memory. Declaring a variable: type identifier [=value][,identifier [=value]….]; The initialization expression must result in a value of the same or compatible type as that specified for the variable.
  • 44.
    Scope and Lifetimeof a variable A block begins with an opening curly brace and ends by a closing curly brace. A block determines scope, that defines which objects are visible to other parts of your program. Variables declared within a block localize themselves. In case of nested block, the outer block encloses the inner block. The variables declared in the outer block is visible to the inner block but the reverse is not true. A variable will not hold it’s value once it has gone out of it’s scope. In an inner block, it is not possible to declare a variable of the same name as in outer block.
  • 45.
    Scope and Lifetimeof a variable Example public static void main( String args[]) { int x =10; if ( x == 10) { int y =20; System.out.println(“x and y: “ +x +” “+y); x= y * 2; } y= 100; //Error System.out.println (“x is “+x); }
  • 46.
    Automatic Type Conversion Whenone type of data is assigned to another type of variable, an automatic type conversion will take place if: 1. Two types are compatible. 2. The destination type is larger than the source type. It is known as widening conversion. The numeric types, including integer and floating point types are compatible. Numeric types are not compatible with char or boolean. Char and boolean are not compatible with each other.
  • 47.
    Casting Type Problem: assigningint value to a byte type variable. This type of conversion is known as narrowing conversion. A cast is simply an explicit type conversion : (target_type) value Example: int a; byte b; …. b = (byte) a; Contains the remainder of an integer division by byte’s range.
  • 48.
    Casting Type class test { publicstatic void main(String args[]) { byte b; int i = 257; double d = 323.142; b=(byte)i; System.out.println (“Conversion of int to byte: ” + i +” “+ b); i=(int)d; System.out.println(“Conversion of double to int: “ +d+” “+i); b=(byte)d; System.out.println(“Conversion of double to byte: “ +d+” “+b); } }
  • 49.
    Casting Type Output: Conversion ofint to byte: 257 1 Conversion of double to int: 323.142 323 Conversion of double to byte: 323.142 67 Note: When assigning a fractional number’s to a whole number’s variable, fractional part is truncated. If the value of the whole number part is too large to fit into the target integer type, then that value will be reduced modulo the target type’s range.
  • 50.
    Automatic Type Promotionin Expression Takes place in expression. Rules: 1. All byte and short values are promoted to int. 2. If one operand is long, the whole expression is promoted to long. 3.If one operand is float, the entire expression is promoted to float. 4. If one operand is double, the entire expression is promoted to double.
  • 51.
    Automatic Type Promotion-Example byteb =42; char c=‘a’; short s=1024; int i=50000; float f=5.67f; double d=.1234; double result = (f * b) + (i / c) – (d * s); 1. (f * b) is promoted to float. 2. (i / c) is promoted to int. 3. (d *s ) is promoted to double. 4. float + int – double = float – double = double
  • 52.
    Automatic Type Conversion-Example 1.byte a =40, b= 50, c =100; int d = a * b /c; 2. byte b =50; b = b * 2; //Error
  • 53.
    Operators in Java Classifiedinto four groups: 1. Arithmetic Operator 2. Bitwise Operator 3. Relational Operator 4. Logical Operator
  • 54.
    Arithmetic Operators Addition + Subtraction- Multiplication * Division / Remainder % Increment ++ Addition Assignment += Subtraction Assignment -= Multiplication Assignment *= Division Assignment /= Modulus Assignment %= Decrement --
  • 55.
    Arithmetic Operators If eitheror both operands associated with an arithmetic operator are floating point, the result is a floating point. % operator applies both to floating-point type and integer types. class modulus { public static void main (String args []) { int x = 42; double y = 42.3; System.out.println(“x mod 10 =“ + x%10); System.out.println(“y mod 10 = “ + y%10); } } Output: x mod 10 =2 y mod 10 = 2.3
  • 56.
    Bitwise Operator ~ Bitwiseunary NOT & Bitwise AND | Bitwise OR ^ Bitwise XOR >> Shift Right >>> Shift Right zero fill << Shift left Applied to integer type – long, int, short, byte and char.
  • 57.
    The Left Shift bytea=8, b=24; int c; c=a<<2; 00001000 << 2 = 00100000=32 Java’s automatic type conversion produces unexpected result when shifting byte and short values. Example: byte a = 64, b; int i; i = a<<2; b= (byte) (a<<2); i 00000000 00000000 00000001 00000000 = 256 b 00000000 = 0 Each left shift double the value which is equivalent to multiplying by 2.
  • 58.
    The Right Shift bytea=8, b=24; int c ; c=a>>2; 00001000 >> 2= 00000010=2 Use sign extension. Each time we shift a value to the right, it divides that value by two and discards any remainder. The Unsigned Right Shift byte a=8, b=24; int c; c=a>>>1 00001000 >>> 1= 00000100=4
  • 59.
    Relational operators > greaterthan >= greater than or equal to < less than <= less than or equal to = = equal to != not equal to The outcome of these operations is a boolean value. = = , != can be applied to any type in java. Only numeric types are compared using ordering operator.
  • 60.
    Relational Operators int done; …… if(!done)…. // Valid in C /C++ but not in java if(done)…. if (done == 0)…. if(done!=0) …….. //Valid in Java
  • 61.
    istanceof Operator  Students= new Student();  Person p= new Person();  boolean b;  b= s instanceof Student; // Here b =true  b= s instanceof Person; // Here b =false
  • 62.
    Operator Precedence Highest 1. () [] . 2. ++ -- ~ ! 3. * / % 4. + - 5. >> >>> << 6. > >= < <= 7. = = != 8. & 9. ^ 10. | 11. && 12. || 13. ?: 14. = op= Lowest
  • 63.
    Decision Making andBranching When a program breaks the sequential flow and jumps to another part of the code, it is known as branching. When branching is done on a condition it is known as conditional branching. Three decision making statements: 1. if statement 2. switch statement 3. conditional operator statement
  • 64.
    The Conditional Operator Java has a conditional operator that evaluates a boolean condition that determines which of two other expressions is evaluated  The result of the chosen expression is the result of the entire conditional operator  Its syntax is:  condition ? expression1 : expression2  If the condition is true, expression1 is evaluated; if it is false, expression2 is evaluated
  • 65.
    The Conditional Operator The conditional operator is similar to an if-else statement, except that it forms an expression that returns a value  For example:  larger = ((num1 > num2) ? num1 : num2);  if (num1 > num2) larger = num1; else larger = num2;  The conditional operator is ternary because it requires three operands
  • 66.
    Repetition Statements Repetition statementsallow us to execute a statement multiple times They are referred to as loops Like conditional statements, they are controlled by boolean expressions Java has three kinds of repetition statements: the while loop the do loop the for loop The programmer should choose the right kind of loop for the situation
  • 67.
    Choosing a LoopStructure When you can’t determine how many times you want to execute the loop body, use a while statement or a do statement If it might be zero or more times, use a while statement If it will be at least once, use a do statement If you can determine how many times you want to execute the loop body, use a for statement For each loop (Enhanced for loop) Labeled break and continue
  • 68.
    The General Formof a Class  A class is defined by specifying the data and the code that operates on the data.  The general form: class classname { type instance-variable1; type instance-variable2; ………… type methodname1( parameter-list) { // body of the method } type methodname2( parameter-list) { //body of the method } …………………… }
  • 69.
    Class and Object Aclass defines a new data type. This new data type is used to create objects of that type. A class is a template for an object and an object is an instance of a class. To allocate a physical memory new() is used. It dynamically allocates memory for an object and returns a reference to it. In Java, all class objects must be dynamically allocated.
  • 70.
    A Simple Example classBox { double width; double height; double depth; } class BoxDemo { public static void main( String args[]) { Box mybox, mybox1; mybox = new Box(); mybox1 = new Box(); mybox.width=10; mybox.height = 20; mybox. depth = 15; mybox1.width = 10; mybox1.height = 25; mybox1.depth=5; } }
  • 71.
    A Closer Lookat New Box mybox; mybox = new Box(); Box b1 = new Box(); Box b2 = b1; null mybox mybox Width Height Depth Call to the default constructor defined by the compiler. It initializes the instance variables to 0. Width Height Depth b1 b2
  • 72.
    Instance variables Default initialization Ifthe variable is within a method, Java does NOT initialize it. If the variable is within a class, Java initializes it as follows:  Numeric instance variables initialized to 0  Logical instance variables initialized to false  Object instance variables initialized to null
  • 73.
    Import Statement A javapackage is a collection of related classes. In order to access the available classes in the package, the program must specify the complete dot seperated package path. The general format: import package-level1.[package-level2.]classname|* Example: import java.util.Scanner; import java.util.*;
  • 74.
    Example import java.util.Random; class random { publicstatic void main(String args[]) { Random r = new Random(); int i; float v; for(i=0;i<5;i++) { v=r.nextFloat(); System.out.println(v); } } } Output: java.lang is automatically imported with every java program. System.out.println() belongs to java.lang.
  • 75.
    Predefined Stream Stream: -A streamis an abstraction that either produces or consumes information. -It is linked to a physical device by a java I/O system. -It hides the details of the physical device to which they are connected. System: -System is a predefined class included in the package java.lang. (Imported automatically by all java programs). -It includes three predefined stream variables: 1. in 2. out. 3. err
  • 76.
    The Predefined Streams 1.System.out: refers to the standard output stream. It is an object of type PrintStream. 2. System.in: refers to the standard input stream. It is an object of type InputStream. 3. System.err: refers to the standard error stream. It is an object of type PrintStream. Note: they are defined as public and static. InputStream: - This class is included in the package java.io. - It has some subclasses the handle the differences between various devices. - Includes some methods that the subclasses will implement.
  • 77.
    Taking Input fromthe Keyboard First, Scanner class is connected to System.in which is an object of type InputStream. Then, it uses it’s internal functions to read from System.in Example: Scanner test = new Scanner(System.in);
  • 78.
    Take an inputfrom the keyboard import java.util.*; public static void main(String[] args) { int value; System.out.print(“Enter an Integer number:"); Scanner tmp = new Scanner(System.in); if(tmp.hasNextInt()) { value=tmp.nextInt(); System.out.println(“You have entered: ”+value); } else System.out.println(“Not an Integer”); }
  • 79.
    One-Dimensional Array Creating anarray is a two steps process: 1. type var_name[]; 2. var_name = new type [size]; Example: int month_days []; month_days = new int [12]; - first line declares month_days as an array variable, no array actually exists. - Actual, physical array of integers, is allocated using new and assign it to month_days. -The elements of array are automatically initialized to 0. int month_days [] = new int[12];
  • 80.
    One-Dimensional Array Once arrayis created, a specific element in the array can be accessed by specifying it’s index within square brackets. Example: month_days[0]=31; month_days[1]=28; Arrays can be initialized when they are declared. Example: int month_days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  • 81.
    Features of Javato Manipulate Array All arrays are dynamically allocated. Size of the array can be specified at the run time. Index type is integer and the index range must be 0 to n-1, where n is the number of elements. Java run time system will check to be sure that all array indices are in the correct range. Incorrect reference will generate ArrayIndexOutofBoundsException.
  • 82.
    Example import java.util.Scanner; class array_avg { publicstatic void main(String args[]) { int i,sum=0; float avg; int a[] = new int[5]; Scanner test=new Scanner(System.in); System.out.println("Enter the input:"); for(i=0;i<5;i++) { a[i]=test.nextInt(); sum=sum+a[i]; } avg=sum/5; System.out.println("The average value is: " + avg); } }
  • 83.
    Array in Java inta[]; int b[] = null; int c[] = new int[5]; int d[] = { 1, 2, 3, 4, 5 }; a = c; d = c; 1 2 3 4 5 0 0 0 0 0 null a - b null c d
  • 84.
    Multi-Dimensional Arrays A two-dimensionalarray can be declared as int twoD [ ] [ ] = new int[4][5]; [0][0] [0][1 ] [0][2] [0][3] [0][4] Represents row Represents column
  • 85.
    Example int tmp[][] =new int[3][3]; int i,j; Scanner test=new Scanner(System.in); for(i=0;i<3;i++) for(j=0;j<3;j++) { System.out.print("Enter Input:"); tmp[i][j]=test.nextInt(); } for(i=0;i<3;i++) { for(j=0;j<3;j++) System.out.print(tmp[i][j] + " "); System.out.println(); }
  • 86.
    Multi-dimensional Array int twoD[][] = new int[4][]; twoD[0] = new int[5]; twoD[1] = new int[4]; twoD[2] = new int[3]; int m [][]={{1,2},{2,3}};
  • 87.
    Example – jaggedarray int a[][]=new int[3][]; a[0]=new int[1]; a[1]=new int[2]; a[2]=new int[3]; int i,j,k=0; for(i=0;i<3;i++) for(j=0;j<i+1;j++) { a[i][j]=k; k++; } for(i=0;i<3;i++) { for(j=0;j<a[i].length;j++) System.out.print(a[i][j]+” “); System.out.println(); } Output: 0 1 2 3 4 5
  • 88.
    Alternative Array DeclarationSyntax Type [] var_name; Example: int [] a = new int[3]; int [] num1, num2, num3; same as int num1[], num2[], num3[];
  • 89.
    Array as anObject An array is implemented as an object. It has a special attribute: length instance variable. Example: int a1[] = new int[10]; int a2[] = {3, 5, 7, 9, 11, 13, 15, 17}; int a3[] = {4, 3, 2, 1}; System.out.println(“length of a1 is: ”+a1.length); System.out.println(“length of a2 is: ”+a2.length); System.out.println(“length of a3 is: ”+a3.length);
  • 90.
    Class-Methods class Box { double length; doublebreadth; double height; }  Write Java programs by including volume( ) method to calculate volume of a box with and with out passing parameters in different ways. Also, add a method setDim( ) to set the dimensions of a box then use them to calculate volume.
  • 91.
    Class- Constructors Constructor namemust be same as class name A constructor must have no explicit return type. A constructor in Java can not be abstract, static,final and synchronized. We can use access modifiers while declaring a constructor. It controls object creation. Constructors may be default or parameterized. Write Java programs by including volume( ) method to calculate volume of a box by initializing instance variables in a constructor. Also write program with parameterized constructors.
  • 92.
    The key word-this this is a key word with which we can refer to the current object. this can be used to invoke the current class instance variable. this can be used to invoke the current class method. this can be used to invoke the current class constructor. this can be passed as an argument in the method call or constructor call. Method overloading, Constructor overloading programs. abs(), labs(), fabs()
  • 93.
    Java- finalize() method: Memoryde-allocation is done automatically in Java. The finalize() method is called just before an object is destroyed (de-allocated).  Inside the finalize( ) we will specify those actions that must be performed before an object is destroyed. The finalize( ) method has this general form: protected void finalize( ) { // finalization code here }
  • 94.
    Object as parameter classTest { int a, b; Test(int i, int j) { a = i; b = j; } boolean equals(Test o) { if(o.a == a && o.b == b) return true; else return false; } } class PassOb { public static void main(String args[]) { Test ob1 = new Test(100, 22); Test ob2 = new Test(100, 22); Test ob3 = new Test(-1, -1); System.out.println("ob1 == ob2: " + ob1.equals(ob2)); System.out.println("ob1 == ob3: " + ob1.equals(ob3)); } }
  • 95.
    Pass By Value classTest { void meth(int i, int j) { i *= 2; j /= 2; } } class CallByValue { public static void main(String args[]) { Test ob = new Test(); int a = 15, b = 20; System.out.println("a and b before call: " + a + " " + b); ob.meth(a, b); System.out.println("a and b after call: " + a + " " + b); } }
  • 96.
    Pass By Reference classTest { int a, b; Test(int i, int j) { a = i; b = j; } void meth(Test o) { o.a *= 2; o.b /= 2; } } class CallByRef { public static void main(String args[]) { Test ob = new Test(15, 20); System.out.println("ob.a and ob.b before call:"+ob.a+" "+ob.b); ob.meth(ob); System.out.println("ob.a and ob.b after call:"+ob.a+" "+ob.b); } }
  • 97.
    Returning Objects class Test { inta; Test(int i) { a = i; } Test incrByTen() { Test temp = new Test(a+10); return temp; } } class RetOb { public static void main(String args[]) { Test ob1 = new Test(10); Test ob2; ob2 = ob1.incrByTen(); System.out.println("ob1.a: " + ob1.a); System.out.println("ob2.a: " + ob2.a); ob2 = ob2.incrByTen(); System.out.println("ob2.a after second increase: "+ ob2.a); }
  • 98.
    Static keyword inJava The static keyword in Java is used for memory management mainly. We can apply java static keyword with variables, methods and blocks. The static variable can be used to refer to the common property of all objects (which is not unique for each object). The static variable gets memory only once in the class area at the time of class loading. Counter() ---program
  • 99.
    Static keyword inJava  If we apply static keyword with any method, it is known as static method.  A static method belongs to the class rather than the object of a class.  A static method can be invoked without the need for creating an instance of a class.  A static method can access static data member and can change the value of it. There are two main restrictions for the static method. They are: (1)The static method can not use non static data member or call non-static method directly. (2) this and super cannot be used in static context.
  • 100.
    Static keyword inJava  Java static block used to initialize the static data members .  It is executed before the main method at the time of classloading. class StaticTest { static { System.out.println("static block is invoked"); } public static void main(String args[]) { System.out.println("Hello main"); } }
  • 101.
    Wrapper Class  wrapperclasses provide a way to use primitive data types (int, char, short, byte, etc) as objects. These wrapper classes come under java.util package. • Autoboxing in Wrapper Class Autoboxing is used to convert primitive data types into corresponding objects. • Unboxing in Wrapper Class Unboxing is used to convert the Wrapper class object into corresponding primitive data types.
  • 102.
    • Autoboxing Class Autoboxing { publicstatic void main(String args[]) { int a=50; Integer obj1=new Integer(a); Integer obj2=Integer.valueOf(a); Integer obj3=a; System.out.println(obj1 +” “+obj2+” “+obj3); }}
  • 103.
    • Unboxing Class Unboxing { publicstatic void main(String args[]) { int a=50; Integer obj=new Integer(a); Int x=obj.intValue(); Int y=obj; System.out.println(a +” “+x+” “+” “+y+” “+obj); }}
  • 104.
    • Wrapper ClassUses Serialization: We need to convert the objects into streams to perform the serialization. If we have a primitive value, we can convert it in objects through the wrapper classes. Synchronization: Java synchronization works with objects in Multithreading. java.util package: The java.util package provides the utility classes to deal with objects. Collection Framework: Java collection framework works with objects only. All classes of the collection framework (ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque, etc.) deal with objects only.
  • 105.
    Access Control inJava Java’s access specifiers are public, private, and protected. Java also defines a default access level. protected applies only when inheritance is involved. When a member of a class is modified by the public specifier, then that member can by accessed by any other code. When a member of a class is specified as private, then that member can only be accessed by other members of its class.  main( ) has always been preceded by the public specifier. It is called by code that is outside the program—that is, by the Java run-time system. When no access specifier is used, then by default the member of a class is public within its own package, but cannot be accessed outside of its package.
  • 106.
    Access Control inJava Write a Stack program by taking top as private and perform push(),pop() operations
  • 107.
    Final keyword inJava The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be applied on variable, method or class. Final variable can not be changed. Final method can not be overriden. Final class can not be extended.