0% found this document useful (0 votes)
5 views25 pages

Java Control Statements Explained

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)
5 views25 pages

Java Control Statements Explained

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

MUTHAYAMMAL COLLEGE OF ARTS AND SCIENCE, RASIPURAM

DEPARTMENT OF COMPUTER SCIENCE

PAPER NAME: JAVA PROGRAMMING PAPER CODE: 23M4UCSC04

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:

public static void main(String args[]) if(condition)


{
1 Statement-1;
}
Ststement_2;

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:

public static void main(String args[]) switch(expression)


{ {
case label1:
char choice=’-‘; block1 statement;
float a=4,b=3,c; break;
case label2:
switch(choice) block2 statement;
{ break;
…….
case ‘+’: default:
c=a+b; default block;
}
break; statement-n;
case ‘–‘:
c=a-b;
break;
case ‘*’:
c=a*b;
break;
case ‘/’:
c=a/b;
break;
}
[Link] (c);
}
ITERATION STATEMENT

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:

matrix1[1][0]=31; for(initialization; condition; increment and decrement)


matrix1[1][1]=32; {
for(initialization; condition; increment and decrement)
matrix1[1][2]=13; {
matrix2[0][0]=4; body of loop;
}
matrix2[0][1]=5; }
matrix2[0][2]=6;
matrix2[1][0]=31;
matrix2[1][1]=2;
matrix2[1][2]=1;
for(i=0;i<3;i++)
{
for(j=0;j<3;++)
{
ans[i][j]=matrix[i][j]+matrix[i][j];
[Link](ans[i][j]);
}
[Link] (“\n”);
}
}
Additional Features Of For Loop:
1) more than one variable can be initialized in the initialization section.
The variable must be separated by comma.
eg.
for(i=1;sum=0;i<=n;i++)
sum=sum+i;
2) More than one condition can be checked.
eg.
for(i=1;sum=0;i<=5&&sum<=10;i++)
sum=sum+i;
8
3) It is possible to use assignment statement in the initialization and increment section.
eg.
for(x=(m+n)/2;x>0;x=x/2)
4) It is possible to omit one on more section but the test condition must be stated.
eg.
for(i<=10)
{
[Link] (“%d”,i);
i++;
}
5)It is possible to set time delay the loop.
eg.
for(j=1000;j>=0;j--)
GOTO Statement:
o It is branching statement and is used to transfer the control to any statement.
o It is an unconditional statement, since it is simply transfer the control without checking any
condition.
Syntax:
goto label name;
label name-> variable name
Types:
1)forward jump
2)backward jump.
Forward Jump:
If the label statement is placed after the goto statement.
In the forward jump a set of statement are skipped and the control is transferred to label statement.
/*program*/
class number
{ Syntax:
public static void main(String args[])
goto label;
{ label: stat-x
int number=4;
if(number<=5)
goto last;
else
{
9
[Link] (“the number is not less than 5”);
}
last: [Link] (“the number is less than 5”);
}
Backward Jump
 If the label statement is placed before the goto statement.
 In the backward jump a set of statements repeatly executed. The statements are executed
infinite number of times.
 To terminate the infinite execution the user has check the condition.
/*program*/
class backward
{
public static void main(String args[])
Label: stat-x
{
read:int number=3; Goto;
if(number<=5)
[Link](“the number is less than 5”);
else
{
goto read;
}
}

Statement Label Vs Case Label


Statement label Case label
1)the label must be variable names 1)the case labels may be integer constant or single
character constants
2)the labeled statement can be placed anywhere in 2)the case labeled should be placed after the case
the program keyword

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:

 We can give a label to a block of statements.


 A label is any valid java variable name.
 To give a label to a loop, place it before the loop with a semicolon at the end.

Classes and objects


What is class?
 A class is a user defined data type.
 A class is essentially a description of how to make an object that contain fields and methods.
Define a class:
 Once class type has been defined, we can create variable of that type using declaration.
 Variable is called as instance of class.
 Inside square bracket is optional.

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

Eg: int -> returns integer


Eg: void->doesn’t return any value.
Method name->valid identifier
Parameter-list->it is enclosed in parameter.
List contain variable name & type of variables are separated by commas.
Eg: ( int m, float x, float y)
Body->operation to be performed on data.

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.

Program: single inheritance


class Room
{
int length;
int breadth;
room(int x,int y)
{
length=x;
breadth=y;
}
Syntax:
int area()
class subclassname extends
{
superclassname
return(length*breadth);
{
}
Variables declaration;
}
19 Methods declaration;
}
class bedroom extends Room
{
int height;
bedroom(int x,int y,int z)
{
super(x,y)
height=z;
}
int volume()
{
return(length*breadth*height);
}
}
class InherTest
{
public static void main(String args[])
{
bedRoom room1=new bedRoom(14,12,10);
int area1=[Link]();
int volume1=[Link]();
[Link](“Area1=”+area1);
[Link](“Volume=”+volume1);
}
}
Subclass constructor
 A subclass constructor is used to construct the instance variable of both the subclass and the
superclass.
 The subclass constructor uses the keyword super to invoke the constructor method of the superclass.
 The keyword super is used subject to the following conditions
1. super may only be used within a subclass constructor.
2. The call to superclass constructor must appear as the first statement within the subclass constructor.
3. The parameters in the super call must match the order and type of the instance variable declared in
the superclass.
Multilevel inheritance
 A common requirement in object-oriented programming is the use of derived class as a superclass.
 Java supports this concept and uses it extensively in building its class library.

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:

 A class that is declared using “abstract” keyword is known as abstract class.


 It can have abstract methods(methods without body) as well as concrete methods (regular methods
with body).
 A normal class(non-abstract class) cannot have abstract methods.
23
Example:
abstract class Shape
{
abstract void draw();
}
 When a class contains one or more abstract methods.
 It should be declared abstract
 While using abstract classes, we must satisfy the following conditions:
 We cannot use abstract classes to instantiate objects directly.
Eg:
shape s = new shape() is illegal because shape is an abstract class.
 The abstract methods of an abstract class must be defined in its class.
 We cannot declare abstract constructors or abstract static methods.

Methods with varargs


 Varargs is a short name for variable arguments.
 In Java, an argument of a method can accept arbitrary number of values.
 This argument that can accept variable number of values is called varargs.
The syntax for implementing varargs is as follows:
accessModifier methodName(datatype… arg)
{
// method body
}
Visiblity Control (OR) Access Modifiers:
There are four types of Java access modifiers:
1. Private: The access level of a private modifier is only within the class. It cannot be accessed from
outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be accessed
from outside the package. If we do not specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and outside the package
through child class. If we do not make the child class, it cannot be accessed from outside the
package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from within the class,
outside the class, within the package and outside the package.

24
************** UNIT II COMPLETED*****************

25

You might also like