0% found this document useful (0 votes)
3 views36 pages

Java - UNIT II

This document provides an overview of decision-making and branching in Java programming, detailing control statements such as selection, iteration, and jump statements. It explains the use of if statements, switch statements, and the ternary operator for decision-making, as well as while, do, and for loops for iteration. The document includes syntax examples and explanations of how these constructs control the flow of program execution based on conditions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views36 pages

Java - UNIT II

This document provides an overview of decision-making and branching in Java programming, detailing control statements such as selection, iteration, and jump statements. It explains the use of if statements, switch statements, and the ternary operator for decision-making, as well as while, do, and for loops for iteration. The document includes syntax examples and explanations of how these constructs control the flow of program execution based on conditions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

III B.

Sc CS Java Programming Siri PSG Arts & Science College for


Women

UNIT – II

DECISION MAKING AND BRANCHING


2.1 INTRODUCTION
 A programming language uses control statements to cause the flow of execution to advance and
branch based on changes to the state of a program.
 When a program breaks the sequential flow and jumps to another part of the code, it is called
branching.
 When the branching is based on a particular condition, it is known as conditional branching. It
branching takes place without any decision it is known as unconditional branching.
 Java’s program control statements can be put into the following categories: selection, iteration and
jump.
 Selection statements allow our programs to choose different paths of execution based upon the
outcome of an expression or the state of a variable.
 Iteration statements enable program execution to repeat one or more statements.
 Jump statements allow our program to execute in a nonlinear fashion.

2.2 DECISION MAKING WITH IF STATEMENT / JAVA’S SELECTION STATEMENTS


 Java supports two selection statements: if and switch. These statements allow us to control the flow
of our program’s execution based upon conditions known only during run time.

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.

Syntax: if (test 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

 The if statement in different forms


 Simple if statement
 If…else statement
 Nested if…else statement
 Else if ladder

 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.

 Nesting of If...Else Statements


 When a series of decision are involved, use more than one if… else statement in nested form.

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
}}

2.2.2 SWITCH STATEMENT


 Java has a built-in multi-way decision statement known as a switch. The switch statement tests the
value of a given variable against a list of case values and when a match is found, a block of
statements associated with the case is executed.
General form:

 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
}
}
}

 Nested Switch Statements


 A switch is part of the statement sequence of an outer switch. This is called a nested switch.
switch (count)
{
case 1:
switch(target)
{
case 0:
System.out.println (“target is zero”);
break;
case 1:
System.out.println (“target is one”);
break;
}
break;
case 2: ….
 There are three important features of the switch statement:
1. The switch differs from the if in that switch can only test for equality, whereas if can evaluate
any type of Boolean expression.
2. No two case constants in the same switch can have identical values. A switch statement enclosed
by an outer switch can have case constants.
3. A switch statement is usually more efficient than a set of nested ifs.

2.2.3 THE ?: OPERATOR


 Java ternary operator is the only conditional operator that takes three operands. Java ternary operator
is a one liner replacement for if-then-else statement and used a lot in java programming.
Syntax:

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;

2.3 DECISION MAKING AND LOOPING / JAVA’S ITERATION STATEMENTS:


 Java iteration statements create loops. The process of repeatedly executing a block of statements is
known as looping. The statements in the block may be executed any number of times from zero to
infinite number. If a loop continues forever, it is called as infinite loop.
 A program loop consists of two segments
1. Body of the loop 2. Control statement
 The control statement tests certain conditions and then directs the repeated execution of the
statements contained in the body of the loop. It classified into 2 types.
Entry-Controlled loop
Exit-Controlled loop
Entry-Controlled loop The control conditions are tested before the start of the loop execution. If
the conditions are not satisfied then the body of the loop will not be executed.
Exit-Controlled loop  The test is performed at the end of the body of the loop and therefore the
body is executed unconditionally for the first time.
The looping process involving four steps:
 Setting and initialization of a counter.
 Execution of the statements in the loop.
 Test for a specified condition for execution of the loop.
 Incrementing the counter.

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 java language provides three constructs. They are:


 While statement
 Do statement
 For statement

2.3.1 WHILE STATEMENT


 It repeats a statement or block while its controlling expression is true.
Syntax:
initialization
While (test condition)
{
body of the loop;
}

 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);

2.3.3 FOR STATEMENT


 The for loop is a entry-controlled loop that provides a more concise loop control structure.
Syntax:
11
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women

for (initialization; test condition;


increment)
{
body of the loop;
}

 The execution of the ‘for’ statement is as follows:


 Initialization of the control variables is done first using assignment statements. i = 0, count = 0.
The variables i and count are known as loop control variables.
 The value of the control variable is tested using test condition. If the condition is true the body of
the loop is executed, otherwise the loop is terminated and the execution continues with the
statement that immediately follows the loop.
 When the body of the loop is executed the control is transferred back to the ‘for’ statement after
evaluating the last statement in the loop.
Example:
class Forex
{
public static void main(String a[])
{
int n;
for(n=10; n>0; n--)
System.out.println(n);
}
}

Declaring Loop control variables inside the for loop:


 It is possible to declare the variable inside the initialization portion of the for.
for (int n=10; n>0; n--)
System.out.println(n);
 When we declare a variable inside a for loop, there is one important point to remember: the scope of
that variable is limited to the for loop.
 Outside the for loop, the variable will cease to exist. If we need to use the loop control variable
elsewhere in our program, we will not be able to declare it inside the for loop.
Example:
class forst
{

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”);
}
}

Additional features of for loop:


1) More that one variable can be initialized at a time in the for statement.
Example : for (i=0, j=0; i<10; i++) // Initialization section has separated by comma.
2) The increment section has more than one part.
Example:
for (n=1, m=50; n<=m; n=n+1, m=m-1)
{
---
---
}
3) The test condition may have any compound relation and the testing need not be limited only to the
loop control variable.

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”);
}
}

2.3.4 JUMPS IN LOOPS

 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.

Using break to Exit a loop:


We can force immediate termination of a loop, bypassing the conditional expression and any
remaining code in the body of the loop. When a break statement is encountered inside a loop, the loop is
terminated and program control resumes at the next statement following the loop.

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”);
}
}

Using break as a form of goto:


This form of break works with a label.

Syntax: break label;

 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.

Syntax of Labelled loop

17
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women

Example without labelled loop

//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.

Example with labelled 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.

2.4 CLASSES, OBJECTS AND METHODS


2.4.1 CLASSES
 Class − A class can be defined as a template/blueprint that describes the behavior/state that the
object of its type support.
 Defining a class:
 A class is a user-defined data-type that serves to define its properties.
 Java programs must be encapsulated in a class that defines the state and behavior of the basic
program components known as objects.
 A class is that it defines a new data type. Once defined, this new type can be used to create objects
of that type. Thus, a class is a template for an object, and an object is an instance of a class. Classes
create objects and objects use methods to communicate between them.

 General form of a class:


A class is declared by use of the class keyword.

class class-name [extends super class name]


{
[Instance variable declaration;]
[Methods declaration;]
}
20
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women

 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

Box mybox ; null mybox

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

Assigning object reference variables:


 Each object has its own copy of the instance variables of its class. This means that any changes to the
variables of another also create two or more reference to the same object.
Box b1 = new Box( );
Box b2 = b1

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.

2.4.3 ACCESSING CLASS MEMBERS:

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

2.4.5 METHODS OVERLOADING


 In Java it is possible to define two or more methods within the same class that share the same name,
as long as their parameter declarations are different.
 Then the methods are said to be overloaded, and the process is referred to as method overloading.
 Method overloading is one of the ways that Java implements polymorphism.
 When an overloaded method is invoked, Java uses the type and/or number of arguments to determine
which version of the overloaded method to actually call.
 While overloaded methods may have different return types, the return type alone is insufficient to
distinguish two versions of a method.

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:

class Overload class OverloadMain


{ {
void test ( ) public static void main(String args[])
{ {
System.out.println("No parameters"); Overload ob = new Overload ();
} double result;
void test(int a) ob.test( );
{ ob.test(10);
System.out.println("a: " + a); result = ob.test(123.25);
} System.out.println("Result :" + result);
void test(int a, int b) }
{ }
System.out.println("a: " + a + "b:" + b); Output:
}
double test(double a) No parameters
{ a: 10
System.out.println("double a: " + a); a :10 b: 20
return a*a; double a: 123.25
} Result: 15190.5625
}

 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

2.4.6 STATIC MEMBERS


 The members that are declared as static are called static members.
 The static variables and static methods are often referred to as class variables and class methods.
 Static variables are used when we want to have a variable common to all the objects and accessed
without using a particular object.
26
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
 Java creates only one copy for a static variable. It was called without using any objects.
Syntax:

static data type variable1,


variable2…

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

Enter length of cuboid:5


Enter breadth of cuboid:6
Enter height of cuboid:7
Perimeter:132
Area:180
Volume:210

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

Single inheritance Multiple inheritance Multilevel inheritance Hierarchical inheritance

 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; -------
} }

 Subclass constructor: (Using super)


 A subclass constructor is used to construct the instance variables of both the subclass and the super
class .The subclass constructor uses the keyword super to invoke the constructor method of the super
class.
 The keyword super is used in the following conditions.
 Super may only be used within a subclass constructor method.
 The call to super class constructor must appear as the first statement within the subclass
constructor.
 The parameters in the super call must match the order and type of the instance variable in the
super class.
 super has two general forms.
1. The first calls the superclass’ constructor.
2. The second is used to access a member of the superclass that has been hidden by a
member of a subclass.

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
{
---------
}

class B extends A // first level


{
---------
}
class C extends B // second level
{
---------
}

 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

Fig: C contains B which contains A

HIERARCHICAL INHERITANCE
 In hierarchical inheritance, the base class consists of many derived class.

Account

Saving Fixed deposit Current

Short Medium Long

Fig: Hierarchical Classification of Bank Accounts

2.4.9 OVERRIDING METHODS


 Defining a method in the subclass that has the same name, same arguments and same return type as a
method in the superclass.
 Then, when that method is called, the method defined in the subclass is invoked and executed instead
of the one in the superclass. This is known as overriding.

32
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women

Output:
Super x = 100
Sub y = 200

2.4.10 FINAL VARIABLES AND METHODS


 All methods and variables can be overridden by default in subclasses.
 If we wish to prevent the subclasses from overriding the members of the superclass, we can declare
them as final using the keyword final as a modifier.
Example:
final int SIZE = 100;
final void showstatus ( ) {……..}
 Making a method final ensures that the functionality defined in this method will never be altered in
any way.
 Similarly, the value of a final variable can never be changed.

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 {………….}

2.4.12 ABSTRACT METHODS AND CLASSES


 We can indicate a method always be redefined in a subclass, thus making overriding compulsory.
This is done using the modifier keyword abstract in the method definition.
Example
abstract class Shape
{
…………………
…………………
abstract void draw ( );
…………………
…………………
}
 While using abstract classes, we must satisfy the following conditions:
1. We cannot use abstract classes to instantiate objects directly. For example,
Shape s = new Shape ( )
is illegal because shape is an abstract class.
2. The abstract methods of an abstract class must be defined in its subclass.
3. We cannot declare abstract constructors or abstract static methods.

2.4.13 VISIBILITY CONTROLS IN JAVA.


 Access protection
 Apply visibility modifiers to the instance variables and methods. It is also known as access
modifiers.
Three types of visibility modifiers: Four categories of visibility for class members:
Public Subclasses in the same package.
Private Non-subclasses in the same package.
Protected Subclasses in different packages.
Classes that are neither in the same package nor subclasses.

 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.

 Private Protected Access:


 A field can be declared with 2 keywords private and protected.
private protected int cno;
 It makes the fields visible in all subclasses regardless of what package they are in.

Table: Visibility of fields in a class

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

 Rules for applying appropriate access modifiers:


Use public if the fields is to be visible everywhere.
Use protected if the field is visible everywhere in the current package and also subclasses in other
packages.
Use default if the field is to be visible everywhere in the current package only.
Use private protected if the field is to be visible only in subclasses, regardless of packages.
Use private if the field is not to be visible anywhere except in its own class.

_________________________________END OF UNIT II ______________________________________

36

You might also like