Java Control Statements Explained
Java Control Statements Explained
CONTROL STATEMENTS:
The decision making statement are used to control the flow of execution.
If statement.
switch statement.
conditional operator statement.
If Statement:
It is a decision making statement and is used to take a decision based on a given condition.
If the condition is true, the statement-1 will be executed and the control is transferred to the statement-n. If
the condition is false, the block is skipped.
Example: Syntax:
class positive
{ If(condition)
public static void main(String args[]) {
Statement-1;
{ }
int a=9;
if(a>0)
[Link](“a is positive”);
}
1. The if statement takes the below forms.
2. simple if statement.
3. if-else statement.
4. nested if-else statement.
5. else if ladder statement.
If the condition is true the statement-1 will be executed and the control is transferred to the
statement-n.
If the condition is false if block is skipped and statement-n will be executed.
Program:
class mark
{ Syntax:
Statement-n;
{
int marks=89;
char category=sports;
if(category==sports)
{
marks=marks+5;
}
[Link](marks);
}
If-Else Statement:
It is a two way decision making statement.
it is used to execute a set of statements based on a condition.
If the condition is true, the true block statements will be executed.
if the condition is false, the false block statements will be executed.
In either care either the true block or the false block will be executed.
largest of two number
class large Syntax:
{
if(condition)
public static void main(String args[]) {
{ True block statement;
}
int a=9,b=6; else
if(a>b) {
False block statement;
[Link](“a is large“); }
else Statement-n;
[Link](“b is large”);
}
Nested if-else statement or dangling else:
If an if-else statement is placed with in another if-else statement, it is a nested if-else statement.
Execution:
If conditions-1 is true than condition-2 is check. If condition-2 is true statement-1 will be executed
and the control transferred to statement-n.
If condition -1 is true and condition-2 is false,statement-2 will be executed.
If condition-1 is false, statement-3 will be executed.
Example:
/*Largest of three numbers*/
class largest
2 Syntax:
If(condition-1)
{
If(condition-2)
{
public static void main(String args[])
{
int a=9,b=6,c=5;
if(a>b)
{
if(a>c)
{
[Link]( a);
}
else
{
[Link]( c);
}
}
else
{
if(b>c)
{
[Link]( b);
}
else
{
[Link]( c);
}
} output: 9
else-if ladder:
It is the multi path decision making statement.
Execution:
As soon as a condition is true the statement associated with the condition is executed, and the control
is transferred to statement-n.
If all the n conditions are false the default statement will be executed.
Example Program:
/*Write a program to process student results based on the given data.*/
class marklist
{
public static void main(String args[]) Syntax:
{
If(condition-1)
int m1=89, m2=90, m3=99, m4=90, m5=80; {
If(condition1)
float avg;
Statement-1;
avg=(m1+m2+m3+m4+m5)/5; else-if(condition-2)
statement-2;
[Link](“tot”+tot+”avg”+avg);
else-if(condition-3)
if(avg>79) statement-3;
………..
3 …………
}
else
default statement;
[Link](“Distinction”);
else if(avg>59)
[Link] (“First class”);
else if(avg>49)
[Link] (“Second class”);
else if(avg>39)
[Link] (“Third class”);
else
[Link] (“Fail”);
}
Conditional Operator Statement:
It is a operator and is used to make two way decision
General Format:
exp1?:exp2:exp3
exp1,exp2,exp3-> expressions.
If expression1 is true, expression 2 is evaluated and value is assigned to left hand side variable.
If expression1 is false, expression3 is evaluated and value is assigned to left hand side variable.
It should be used in an assignment statement.
Eg:
class large
{
public static void main(String args[])
{
int a=7,b=6,c;
c=(a>b)?a:b;
[Link](c);
}
Switch statement:
The Switch statement is a Multi-way Decision Statement.
The Switch Statement is a Multiple Branching Statement.
The switch statement is used to select one operation from many operations.
Execution:
Where expression is an integer expression or a single character constants. Block1,Block2..etc, are a
group of statement or may be a single statements. There is no need to put braces around the blocks.
4
Label1,Label2…etc, are case labels and must be unique.
The case labels may be integer constants or single character constants. The case labels should end
with the colon.
The switch statement tests the value of the expression against the case labels. When a match is found
a block of statements associated with the case is executed.
The break statement denoted the end of the case and causes an exits from the switch statement and
the control is transferred to the default case is optional.
If no match is found the default block will be executed.
1)/*PROGRAM*/
class Add
{ Syntax:
While loop:
It is an entry controlled loop Statement.
5
Execution:
If the condition is true the body of the loop will be executed.
If the condition is false the control is terminate at the loop.
/*sum of digits*/
class sum
{
public static void main(String args[]) Syntax:
{ While (condition)
int num=123,r,q=0; {
Body of the loop;
while(num>0) }
{
r=num%10;
q=q+r;
num=num/10;
}
[Link] (num);
}
DO…..Whileloop:
It is an exit controls loop.
Execution:
The body of the loop is executed and then the condition is check.
If the condition is true the body of the loop will be executed. otherwise the control is
terminated
Even if the condition false at the begin the loop is executed for the first time
/*program*/
class sums
{
public static void main(String args[])
{
int sum,n=5,i;
Syntax:
sum=0;i=1;
do Do
{
{ Body of the loop;
sum=sum+i; }
i++; While (condition);
6
}
while(i<=n);
[Link] (“the sum of first 5 numbers”+n+sum);
}
For Loop:
It is entry control loop.
General Form:
Execution:
The initialization of the control variable is done using the assignment statement.
The value of the control variable is tested using the test condition.
If the condition is true body of the will be executed.
If the condition is false the body of the loop will not executed and the control is transferred to the
statement following the loop.
The control variable is increment or decrement using the increment or decrement section and the new
value is tested against to the condition.
/*Fibonacci*/
Syntax:
class Fibonacci
{ for(initialiazation;condition;increment and
decrement)
public static void main(String args[]) {
{ body of loop;
}
int f0=0,f1=1,f2,n=5,i;
[Link] (f0);
[Link](f1);
for(i=0;i<=n;i++)
{
f2=f0+f1;
[Link] (f2);
f0=f1;
f1=f2;
}
Nested For Loop:
It is entry control loop.
/*to find the addition of 2 matrix*/
class matrix
7
{
public static void main(String args[])
{
int matrix1[][]=new int[3][3],matrix2[][]=new int[3][3], ans[][]=new int[3][3],i,j;
matrix1[0][0]=3;
matrix1[0][1]=23;
matrix1[0][2]=23; Syntax:
JUMPS IN LOOPS:
Loops Performs a set of operations repeatedly until the control variable fails to satisfy the Test
Condition.
Java permits a jump from one statement to the end or beginning of a loop as well as a jump out
of a loop.
Jumping Out of a Loop
10
When the break statement in placed inside a loop, the loop is immediately exited and the program
continues with the statement immediately following the loop.
When the loops are nested, the break would only exit from the loop containing it.
Skipping a part of a loop
The continue statement tells the compiler, “Skip the following statements and continue with the next
iteration”.
General format:
continue;
Labelled loops:
Example:
class empty
{
}
Classname & superclassname are java identifiers.
Extends->properties of superclass extended to classname [Link] is called inheritance.
Field declaration:
Data is grouped in a class by placing data fields inside body of the class definition.
These variables are called instance variable because they are created whenever an object of the class
is instantiated.
Syntax:
Example
class classname [extend super class
class rectangle
name]
{ {
[Fields declaration;]
11
[Methods declaration;]
}
int length;
int width;
}
rectangle has two integer type instance variable. These are known as member variable.
Method declaration:
Methods are declared inside body of the class but immediately after the declaration of instance
variable.
Method declaration basic parts:
Syntax:
Name of the method (method name).
Type method name (parameter
Types of the value method return (type).
list)
List of parameter (parameters-list).
{
Body of the method.
Method body;
Type -> type of value the method would return.
}
Program:
class rectangle
{
int length;
int width;
void getdata(int x,int y)
{
length=x;
width=y;
}
int rectraea()
{
int area=length*width;
return(area);
12
}
}
Creating objects
Object:
An object is essentially a block of memory that contains space to store all instance variables.
Creating an object is also referred to as instantiating an object.
Objects are created using new operator.
New operator creates an object of the specified class &returns a reference to that object.
Example:
Rectangle rect1;
rect1=new Rectangle();
i) Declares variable to hold object reference.
ii)Assigns object reference to variable.
rect1 is a reference to rectangle object both statement are combined.
Rectangle rect1=new Rectangle();
Create any number of objects,
Rectangle rect1=new Rectangle();
Rectangle rect2=new Rectangle();
Assigning object reference variable to another,
Rectangle r1=new Rectangle ();
Rectangle r2=r1;
Accessing class members
can’t access instance variable and method directly.
use object& dot operator
object [Link] name=value;
object [Link] name(parameter-list);
object name is name of the object.
variable name is name of the instance variable of the class.
method name is method.
parameter-list is a comma separated list of actual values.
1) Instance variables of rectangle class may be accessed and assigned values.
[Link]=15;
[Link]=10;
2) method getdata can be used to assign values to the instance variable
[Link](15,10);
13
Passes 15,10 values to x & y.
Compute area of the rectangle using 2 ways.
1) To access instance variables using dot operator and compute the area.
int area1=[Link]* [Link];
2 ) To call rectarea inside the class .
int area1=[Link]();
Example:
class rectangle
{
int length , width ;
void getdata(int x,int y)
{
length=x;
width=y;
}
int rectarea()
{
int area=length*width;
{
int area=length*width;
return(area);
}
}
class rectarea
{
public static void main(String args[])
{
int area1, area2;
rectangle rect1=new rectangle ();
rectangle rect2=new rectangle ();
[Link]=15;
[Link]=10;
area1=[Link]*[Link];
[Link](20,12);
area2=[Link]();
[Link](+area1);
14
[Link](+area2);
}
}
OUTPUT:
area1=150
area2=290
CONSTRUCTORS
Java supports a special type of method called a constructor, enables an object to initialize itself
when it is created.
Constructors have the same name as the class itself.
They don’t specify any return type not even void.
Example:
class rectangle
{
int l , w;
rectangle(int x,int y)
{
l = x;
w = y;
}
int rectarea()
{
return(l*w);
}
}
class rectanglearea
{
public static void main(String args[])
{
rectangle rect1=new rectangle(15, 10);
int area1=[Link]();
[Link](“area1”+area1);
}
}
METHOD OVERLOADING
15
Methods have the same name, but different parameter lists and different definitions are called
method overloading. It is also called function polymorphism.
Method overloading is used, when objects are required to perform similar tasks but different
input parameters.
Java matches up method name first and number & type of parameter.
Example:
class room
{
float l;
float b;
room(float x,float y)
{
l=x;
b=y;
}
room(float x)
{
l=b=x;
}
int area()
{
return(l*b);
}
}
class rectangle
public static void main(String args[])
{
room r1=new room(25.0,15.0);
room r2=new room(20.0);
int area1=[Link]();
int area2=[Link]();
[Link](+area1);
[Link](+area2);
}
}
STATIC MEMBERS:
16
Class contain 2 sections,
[Link] variable - instance variable .
[Link] method -instance method.
Access using dot operator:
To define a member is common to all objects & accessed without using a particular object.
Member belongs to the class rather than the object.
Eg:
static int count;
static int max(int x,int y);
these are static members.
Static member are associated with the class.
static variable & method are called as class variable & method.
it can be called without using objects.
Program:
class mathoperation
{
static float mul(float x,float y)
{
return x/y;
}
class mathapplication
{
public static void main(String args[])
float a=[Link](4.0,5.0);
float b=[Link](a,2.0);
[Link](“b=’’+b);
}
}
RULES:
Can call only other static methods.
can access only static data.
can’t refer to this or super.
NESTING OF METHODS:
A method can be called by using only by its name by another method of the same class. This
is known as nesting of methods.
Example:
17
class nesting
{
int m,n;
nesting(int x,int y)
{
m=x;
n=y;
}
int largest()
{
if (m>=n)
return(m);
else
return(n);
}
void display()
{
int large=largest();
[Link](“largest value=”+large);
}
}
class nestingtest
{
public static void main(String args[])
{
nesting nest=new nesting(50,40);
[Link]();
}
}
INHERITANCE:
The mechanism of deriving a new class from an old one is called inheritance.
The old class is known as the base class or super class or parent class and the new one is called the
sub class or derived class or child class.
Inheritance may take different forms:
Single inheritance(only one super class)
Multiple inheritance (several super classes)
18
Hierarchical inheritance(one super class, many sub class)
Multilevel inheritance(Derived from a derived class)
Java does not directly implement multiple inheritance.
This concept is implemented using a secondary inheritance path in the form of interfaces.
A
A A
A B
B C D
B B
C
Defining a subclass:
This keyword extends signifies that the properties of the super class name are extended to the sub
class name.
The sub class will contain its own variables and methods as well those of the super class.
20
A
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.
A derived class with multilevel base class is declared as follows.
class A
{
………………..
…………………
}
class B extends A
{
…………………..
…………………..
}
class C extends B
{
……………….
……………..
}
Hierarchical inheritance
Here certain features of one level are shared by many other below the level.
A hierarchical classification of accounts in a commercial is shown below.
ACCOUNT
21
Fixed-deposit current
Savings
Medium Long
Short
Overriding Methods
Declaring a method in subclass which is already present in the parent class is known as method
overriding.
Methods is called,the method defined in the subclass is invoked and executed instead of the one in
the superclass .
Example:
class super
{
int x;
super(int x)
{
this.x=x;
}
void display()
{
[Link](“Super x=”+x);
}
class sub extends super
{
int y;
sub(int x,int y)
{
super(x);
this.y=y;
}
void display()
{
[Link](“super x=”+x);
[Link](“sub y=”+y);
}
}
class OverridingTest
{
public static void main(String args[])
{
22
sub s1=new sub(100,200);
[Link]();
}
}
Final Variables and Methods
final is a non-access modifier applicable only to a variable, a method or a class. Following are
different contexts where final is used.
Final variable – to create constant variable
Final method -- prevent method overriding
Final classes – prevent inheritance
Example:
final int SIZE=100;
final void showstatus();
The functionality defined in this method will be altered in any way.
The value of the final variable can never be changed.
Final Classes:
To prevent a class being further subclasses for security.
A class that cannot be subclassed is called a final class.
This achieved in java using final keyword as follows,
final class Aclass{…………….}
final class Bclass extends someclass{………………}
Declaring a class final prevents any unwanted extension to the class.
Finalizer Methods:
A Constructor method is used to initialize in object when it is declared. This process is known as
initialization.
Java supports a concept called finalization, which is just opposite to initialization.
Java run-time is an automatic garbage collecting system.
It automatically frees up the memory resources used by the object.
But object may hold other non-object resources such as file descriptors or window system fonts.
The garbage collector cannot free these resources in order to free these resources we must use
finalizer method.
The finalizer method is simply finalize() can be added to any class.
Abstract Method and Classes:
24
************** UNIT II COMPLETED*****************
25