Java - UNIT II
Java - UNIT II
UNIT – II
2.2.1 IF STATEMENT
The if statement is a powerful decision making statement and is used to control the flow of execution
of statements. It is a two way decision statement and is used in conjunction with an expression.
It allows the computer to evaluate the expression first and then depending on whether the values of
the expression is ‘true’ or ‘false’, it transfer the control to a particular statement.
Example:
i) if (a> 0)
The number is positive
ii) if (tamil >=40)
Result is pass
1
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
Simple If Statement
The general form of a simple if statement is
if (test expression)
{
Statement
block;
}
Statement-x;
The ‘statement block’ may be a single or group of statements. If the test expression is true then
statement block will be executed otherwise statement block will be skipped and execution will jump
to ‘statement x’.
Example:
if ( weight <10)
{
weight = weight +10;
}
weight = 0;
If … Else Statement
The if statement is Java’s conditional branch statement. It can be used to route program execution
through two different paths.
Syntax:
if (condition)
{
True-block statement 1;
}
else
{
False-block statement 2;
}
2
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
If the condition is true, then statement1 is executed. Otherwise statement2 is executed. Each
statement may be a single statement or a compound statement enclosed in curly braces. The
condition is any expression that returns a Boolean value. The else clause is optional.
Example:
If (( 8 % 2) = = 0)
{
System.out.println (“ The number is even “);
}
else
{
System.out.println (“ The number is odd “);
}
Output:
The number is even.
General form:
if test condition 1
{
if (test condition2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}
3
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
statement-x;
If the condition 1 is false, the statement-3 will be executed; otherwise it continues to perform the
second test. If the condition 2 is true, the statement 1 will be executed, otherwise the statement-2
will be evaluated and then the control is transferred to the statement-x.
Example: To find largest of 3 numbers
class biggest
{
public static void main (String args[ ])
{
int a=35, b=72, c=47;
if ( a > b)
{
if ( a >c)
{
System.out.println (“ The biggest number is “ + a );
}
else
{
System.out.println (“ The biggest number is “ + c );
}
}
else
{
if ( c >b)
{
System.out.println (“ The biggest number is “ + c );
}
else
{
System.out.println (“The biggest number is “ + b );
}
}
Output: The biggest number is 72
}
}
4
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
Else If Ladder
It is used when multipath decisions are involved use else if ladder statement. A multipath decision is
a chain of if’s in which the statement associated with each else is an if.
General form:
if (condition1)
statement-1;
else if(condition2)
statement-2;
……
else if(condition n)
statement-n;
else
default statement
statement-x;
The conditions are evaluated from top to towards. The true condition is found, the statement
associated with it is executed and the control is transferred to the statement-x. When all the n
conditions become false, then the final else containing the default statement will be executed.
Example:
Class lader
{
public static void main(String args[])
{
int rno[] = {1,2,3,4};
int m[] = {81,75,43,58};
for(int I = 0; i<rno.length; i++)
{
if(m[i] > 79)
System.out.println(rno[i]+”honours”);
else if (m[i] >59)
System.out.println(rno[i]+”I division”);
else if(m[i] >49)
System.out.println(rno[i] + “ II division”); Output: 1 honours
else 2 I division
3 fail
System.out.println(rno[i] + “fail”); 4 II division
}
5
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
}}
The expression is an integer expression or characters. Value1, value 2 ….. are constants or constants
expression and are known as case labels. Block1, block2 are statement lists and may contain zero or
more statement.
When the switch is executed, the value of the expression is successively compared against the values
value1, value2… If a case is found whose value matches with the value of the expression, then the
block of statements that follow the case are executed.
The break statement at the end of each block signals the end of a particular case and exit from the
switch statement, transferring the control to the statement x following the switch.
The default is an optional case. The selection process of switch statement is as follows:
6
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
Example:
class city
{
public static void main(String args[])
{
char choice;
System.out.println(“choice”);
System.out.println(“M Madras”);
System.out.println(“B Bombay”);
System.out.println(“C Calcutta”);
System.out.flush();
try{
switch(choice = (char)System.in.read()
{
case ‘M’
case ‘m’: System.out.println(“Madras”);
case ‘B’
case ‘b’: System.out.println(“Bombay”);
case ‘C’
case ‘c’: System.out.println(“Calcutta”);
default: System.out.println(“Invalid”)’
}
}
catch(Exception e)
{
System.out.println(“error in statement”);
7
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
}
}
}
Conditional
exp? exp1: exp2
- The conditional exp is evaluated first. If it is true, then the exp1 is evaluated and is returned as the
value of the conditional expression.
8
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
- Otherwise, exp2 is evaluated and its value is returned.
Example: Equivalent to
If (x<0)
flag = (x<0)? 0 : 1; flag = 0;
else
flag = 1;
condition
Body of loop
condition
Body of loop
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
False
False
True
True
(Entry control) (Exit control)
The while is an entry-controlled loop statement. The test condition is evaluated and if the condition
is true the body of the loop is executed. After execution of the body, the test condition is once again
evaluated and if it is true, the body is executed once again.
This process of repeated execution of the body continues until the condition finally becomes false,
and the control is transferred out of the loop.
The body of the loop may have one or more statements. The braces are needed only if the body
contains two or more statements.
Example:
class Whileex {
public static void main(String a[]) class Whileex1
{ {
int n = 5; public static void main(String a[])
while(n>0) {
{ int i= 100, j=200;
System.out.print(“\t”+n); while(++i < j++);// no body
n--; System.out.println(“Result is ”+i);
} }
10
}} }
Output Output
5 4 3 2 1 Result is 150
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
The body of the while loop can be empty. This is because a null statement is syntactically valid in
Java.
2.3.2 DO STATEMENT
It executes the body of the loop before the text is performed.
Syntax:
initialization
do
{
body of the loop;
} while (test
condition);
The program evaluates the body of the loop statement first. At the end of the loop, the test condition
in the while statement is evaluated. If the condition is true the program continues to evaluate the
body of the loop once again. This process continues as long as the condition is true.
When the condition becomes false, the loop will be terminated and the control goes to the statement
that appears immediately after the while statement.
The test condition is evaluated at the bottom of the loop. And therefore the body of the loop is
executed at least once.
Example:
int n = 10;
do {
System.out.println(“\t “ +n);
n --;
} while(n>0);
12
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
public static void main(String a[])
{
int num;
boolean isprime = true;
num=14;
for(int i =2; i< num/2; i++)
{
if(num % i) == 0)
{
isprime = false;
break;
}
}
if(isprime)
System.out.println(“prime”);
else
System.out.println(“Not prime”);
}
}
Example:
sum=0;
for (i=1, i<20 && sum <100; i++)
13
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
{
---
---
}
4) It is also permissible to use expression in the assignment statements of initialization and increment
section.
Example: for(x= (m+n) /2; x>0; x=x/2)
5) For loop is than one or more sections can be omitted. Example: for (; m! =50 ;)
6) Both the initialization and increment section are omitted in the for statement. The initialization has
been done before the for statement and the control variables is incremented inside the loop. The
body of the loop contains only one semicolon is known as empty statement.
Nested Loops
One for statement within another for statement is called nesting for loop. That is, one loop may
be inside another.
Syntax:
for ( i=1 ;i<10; ++i)
{
…….
…….
for( j=1 ;j!=5;++j)
{
………. Inner loop Outer loop
……….
}
………..
………..
} ……..
The outer loop controls the rows while the inner one controls the column.
Example: To generate a triangle
class Nesting
{
public static void main(string a[])
{
int i,j;
for(i = 0; i<5; i++) Output:
*****
****
14 ***
**
*
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
{
for(j=1; j<5; j++)
System.out.print(“*”);
System.out.println();
}
System.out.print(“\n”);
}
}
Jump statements are used to interrupt the normal flow of program. These statements transfer control
to another part of the program.
Java support the following jump statements:
1. break
2. continue
3. labelled loop
Using break:
The break statement has three uses.
1. It terminates a statement sequence in a switch statement.
2. It can be used to exit a loop.
3. It can be used as a “civilized” form of goto.
Ex:
class Breakloop
{
public static void main(String a[])
{
for(int i =0; i<100; i++)
Output
{ I=0 I=1 I=2 I=3 I=4
15 Loop complete
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
if(i == 5)
Break;
System.out.print(“\t I = “+i);
}
System.out.println(“\n Loop complete”);
}
}
Where, label is the name of a label that identifies a block of code. The control is transferred out
of the named block of code. A label is any valid Java identifier followed by a colon.
Example:
class Breakst
{
public static void main(String a[])
{
first: for(int i=0; i<3; i++)
{
System.out.print(“Pass “ + i + “: “);
for(int j=0; j<100; j++)
{
if(j == 10)
break first;
}
System.out.println(“This will not print”);
}
System.out.println(“Loop complete.”);
}
}
Using continue
16
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
It helps to skip a part of the body of the loop under certain conditions. The part of the program loop
that processes the application details is skipped and the execution continues with the next loop
operations.
Java supports another similar statement called the continue statement. The break statement called the
continue statement.
The break which causes the loop to be terminated, the continue as the name implies causes the loop
to be continued with the next iteration after skipping any statement in between.
Syntax: continue;
Example:
class Cont {
0 1
public static void main (String a[]) 2 3
{ 4 5
6 7
for(int i =0; i<10; i++) { 8 9
System.out.print(i+ “”);
If(i%2 == 0)
Continue;
System.out.println(“”);
}
}
}
Labelled Loops :
According to nested loop, if we put break statement in inner loop, compiler will jump out from
inner loop and continue the outer loop again.
If we need to jump out from the outer loop using break statement given inside inner loop,
define lable along with colon(:) sign before loop.
17
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
//WithoutLabelledLoop.java
class WithoutLabelledLoop
{
public static void main(String args[])
{
int i,j;
for(i=1;i<=10;i++)
{
System.out.println();
for(j=1;j<=10;j++)
{
System.out.print(j + " ");
if(j==5)
break; //Statement 1
18
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
}
}
}
}
Output :
12345
12345
12345
12345
12345
12345
12345
12345
12345
12345
In the above example, statement 1 will break the inner loop and jump outside from inner loop to
execute outer loop.
//WithLabelledLoop.java
class WithLabelledLoop
{
public static void main(String args[])
{
int i,j;
loop1: for(i=1;i<=10;i++)
{
System.out.println();
loop2: for(j=1;j<=10;j++)
{
System.out.print(j + " ");
19
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
if(j==5)
break loop1; //Statement 1
}
}
}
}
Output :
12345
In the above example, statement 1 will break the inner loop and jump outside the outer loop.
The data, or variables declared within a class are called as instance variables. Instance variables are
also known as member variables.
Collectively, the methods and variables defined within a class are called members of the class.
Everything inside the square brackets is optional.
Class name and super class name are any valid java identifiers.
The keyword extends indicates that the properties of the super class are extended to the class name
class. This concept is known as inheritance.
Fields Declaration:
Declare the instance variables exactly the same way as we define local variables.
class Box
{
int width, height, depth;
}
Methods Declaration:
Methods are declared inside the body of the class but immediately after the declaration of instance
variables. The general form of a method declaration is
type method-name (parameter-list)
{
Method-body;
}
There are four basic parts:
The name of the method (method name).
The type of the value the method returns (type).
A list of parameters (parameter list).
The body of the method.
The type specifies the type of values the method would return.
This could be a simple data type such as int as well as any class type. It could even be void type, if the
method does not return any values. The method name is valid identifiers.
The parameter list is always enclosed in parenthesis.
The variables in the list are separated by commas.
21
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
Methods that have a return type other than void return a value to the calling routine using the return
statement.
return value;
Adding a method to the Box class:
class Box
{
int height, width;
void getData(int x , int y)
{
height=x;
width=y;
}
}
The getData method is basically added to provide values to the instance variables. Instance variables
and methods in classes are accessible by all the methods in the class but a method cannot access the
variables declared in other methods.
2.4.2 OBJECTS
Creating objects:
An object is also referred to as instantiating an object. It is a block of memory that contains space to
store the entire instance variable.
An object in java is created using new operator. This operator is used to create an object of the
specified class and returns a reference to that object.
Ex: Box mybox; // declare reference to object
mybox = new Box( ); // allocate a Box object
The first statement declares a variable to hold the object reference and the second one actually
assigns the objects reference to the variables. The variable rect1 is now an object of the rectangle
class.
Statement Result
22
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
mybox = new Box(); mybox
mybox is a reference to
Box object
Box object
B1
Box object
B2
When we assign one object reference variable to another object reference variable, then we are not
creating a copy of the object, instead we are only making a copy of the reference.
objectname.variablename = value;
objectname.methodname(parameter-list);
Here objectname is the name of the object, variablename is the name of the instance variable inside
the object that we wish to access, methodname is the method that we wish to call, and parameter-list
is a comma separated list of “actual values” that must match in type and number with the parameter
list of the methodname declared in the calss.
Ex:
mybox.height = 20;
mybox.depth = 15;
2.4.4 CONSTRUCTOR
Java support a special type of method, called a Constructor that enable an object to initialize itself
when it is created.
23
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
Constructors have same name as the class itself, they do not specify a return type, not even void.
Example
c1ass Rectangle
{
int length, width;
Rectangle ( int x, int y) // Defining constructor
{
1ength = x;
width = y;
}
int rectArea()
{
return (length * width);
}
}
class RectangleArea
{
public static void main (string args [ ])
{
Rectangle rect1 = new Rectangle(15, 10); // Calling Constructor
intarea1 = rect1.rectArea( );
System.out.println(“Area = “ + area1);
}
}
Output: Area1 = 150
24
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
When Java encounters a call to an overloaded method, it simply executes the version of the method
whose parameters match the arguments used in the call.
Example:
Overloading Constructors
In addition to overloading normal methods, we can also overload constructor methods.
class Box {
double width;
double height;
double depth;
Box (double w, double h, double d) // constructor used when all dimensions specified
{
width = w;
height = h;
depth = d;
}
Box ( ) // constructor used when no dimensions specified
{
width = -1; // use -1 to indicate
height = -1; // an uninitialized
25
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
depth = -1; // box
}
Box(double len) // constructor used when cube is created
{
width = height = depth = len;
}
}
class OverloadCons
{
public static void main(String args[])
{
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}
Output
Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
Volume of mycube is 343.0
Example:
float x = Math.sqrt(25.0);
The method sqrt is a class method defined in Math class.
Example:
class Usestatic
{
static int a =3;
static int b;
static void meth (int x)
{
System.out.println(“x = “ + x);
System.out.println(“a = “ + a);
System.out.println(“b = “ + b);
}
static
Output
{ Static initialized
System.out.println(“Static initialized”); x = 42
a=3
b= a * 4; b = 12
}
public static void main(String args[])
{
Meth(42);
}
}
Restrictions for static methods:
Static methods are called using class names.
They can only call other static methods.
They can only access static data.
They cannot refer to this or super in any way.
27
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
2.4.7 NESTING OF METHODS
When a method in java calls another method in the same class, it is called Nesting of methods.
Example
import java.util.Scanner;
public class Nesting_Methods
{
int perimeter(int l, int b)
{
int pr = 12 * (l + b);
return pr;
}
int area(int l, int b)
{
int pr = perimeter(l, b);
System.out.println("Perimeter:"+pr);
int ar = 6 * l * b;
return ar;
}
int volume(int l, int b, int h)
{
int ar = area(l, b);
System.out.println("Area:"+ar);
int vol ;
vol = l * b * h;
return vol;
}
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print("Enter length of cuboid:");
int l = s.nextInt();
System.out.print("Enter breadth of cuboid:");
int b = s.nextInt();
System.out.print("Enter height of cuboid:");
int h = s.nextInt();
28
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
Nesting_Methods obj = new Nesting_Methods();
int vol = obj.volume(l, b, h);
System.out.println("Volume:"+vol);
}
}
Output:
$ javac Nesting_Methods.java
$ java Nesting_Methods
2.4.8 INHERITANCE
Inheritance is one of the cornerstones of object-oriented programming because it allows the creation
of hierarchical classifications.
In the terminology of Java, a class that is inherited is called a superclass. The class that does the
inheriting is called a subclass.
Therefore, a subclass is a specialized version of a superclass. It inherits all of the instance variables
and methods defined by the superclass and add its own, unique elements.
The mechanism of deriving a new class from an old one is called inheritance. The old class is known
as base class (or) super class (or) parent class and the new one is called the sub class (or) derived
class (or) child class.
Types of inheritance:
Single inheritance (only one super class)
Multiple inheritances (several base classes)
Hierarchical inheritance (one super class, many subclasses)
29
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
Multiple inheritances (derived from a derived class)
A A
A B A
B
B C D
B
C C
Defining a Subclass
To inherit a class, we simply incorporate the definition of one class into another by using the extends
keyword.
The keywords extends signifies that the properties of the superclass name are extended to the
subclass name.
Syntax: Example:
class subclass extends superclass class B extends A // A Superclass B Subclass
{ {
Variables declaration; -------
Methods declaration; -------
} }
30
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
MULTILEVEL INHERITANCE
Deriving a class from a super class allows us to build a chain of classes. We can build hierarchies
that contain as many layers of inheritance as we like.
For example, given three classes called A, B and C. C can be a subclass of B, which is a subclass of
A. In this case, C inherits all aspects of B and A.
A
Super class
B
Intermediate super class
C Sub class
The class A serves as a base class for the derived class B which in turn serves as a base class for the
derived class C. The chain ABC is known as inheritance path.
class A
{
---------
}
This process may be extended to any number of levels. The class C can inherit the members of both
A and B as:
B
CA
C contains B which contains A
31
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
HIERARCHICAL INHERITANCE
In hierarchical inheritance, the base class consists of many derived class.
Account
32
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
Output:
Super x = 100
Sub y = 200
33
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
2.4.11 FINAL CLASSES
A class that cannot be sub classed is called final class.
This is achieved in Java using the keyword final as follows:
final class Aclass {……….}
final class Bclass extends Somec1ass {………….}
Public Access:
34
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
Any variable or method is visible to the entire class by simply declaring it as public. To make it
visible to all the classes outside this class declare the variable or method as public.
Example:
public int x;
public void get( )
{
-----
-----
}
A variable or method declared as public has the widest possible visibility and accessible everywhere.
Friendly Access:
When no access modifier is specified, the member defaults to a limited version of public accessibility
known as “friendly” level of access.
Public modifier makes fields visible in all classes, regardless of their packages.
Friendly access makes fields visible only in the same package, but not in other packages. A package
is a group of related classes stored separately.
Protected Access:
It makes the fields visible not only to all classes and subclasses in the same package but also to
subclasses in other packages.
Private Access:
They are accessible only within their own class. A method declared as private behaves like a method
declared as final. It prevents the method from being sub-classed.
35
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
Access / Access modifiers Public Protected Friendly Private Private
locations (default) protected
Same class Yes Yes Yes Yes Yes
Subclass in same package Yes Yes Yes Yes No
Other classes in same packages Yes Yes Yes No No
Sub classes in other packages Yes Yes No No No
Non sub classes in other
Yes No No No No
packages
36