Ch 06 Java Control Structures and Methods
Control Structures
A programming language uses control structures to cause the flow of execution to advance and branch.
Java’s control structures are of 2 basic categories- Decision and Looping.
Note: Some times “sequence” of operations is also considered along with decision and looping.
Decision Structure or Selection Statement
The if construct is kind of Conditional Branching where the program control proceeds in different
directions depending on a condition or the value of a specified variable or [Link] supports 2 types
of decision structures- if construct and switch construct.
No if Construct switch construct
1 The if construct is kind of Conditional Branching The switch construct is kind of Conditional Branching
where the program control proceeds in different where the program control proceeds in different
directions depending on a [Link] directions depending on the value of a specified
condition specified evaluates to a Boolean variable or [Link] value of the variable is
[Link] the value is true, the statements inside match with a specific “case” and if the value matches,
the if construct executes. corresponding statements are executed.”break”
keyword is used exit from the switch construct.
2 If construct can check all types of complex Switch construct can only check for simple equality is
Boolean logical conditions and is more suited for more suited for it.
such situations.
3 If construct can use multiple variables in the Switch construct can only use it’s own variable for
condition. condition.
4 If construct can check if the variable falls in a Switch construct can directly check only for straight
range of values. matches.
5 If construct can be used with all data types. The variable being checked in a switch construct has
to byte,short,int or char data types.
6 2 conditions in the same if construct may be No 2 case statements in switch can have identical
same. values.
Java syntax allows this although logically it may
not be meaningful.
7 There are 3 variations of the if construct. There are no variations of switch construct.
1)Simple if 2)if with else 3)if else if else
Note1:If break statement is omitted after every case, the control will “fall through” to next case statement.
Note2:When using nested ifs (below),there could occur a problem of which else belongs to which if.(Dangling Else Problem)
Nested if construct Nested switch construct
A nested if is an if construct that is placed inside A nested switch construct is a switch construct that
another if construct. is placed inside another switch construct.
Ternary Operator or Conditional Operator (? :)
The ternary operator is named so because it takes 3 [Link] is a compact form of the if [Link]
syntax is
boolean expression ? expression1 : expression2;
1 2 3
1
If construct ternary operator
1 Code is more simple and easy to Code may become complex and difficult to
understand understand
2 Code is cumbersome for simple cases Code is compact and concise.
3 If (x>0) then y=(x>0)? 1:-1;
y=1;
else
y=-1; *
2nd example for ternary operator: [Link]((num%2==0) ? “num is even” :
”num is odd”);
Possible Question:Differentiate between Unary,Binary and Ternary Operators with the help of examples.
Loop Structures or Iteration Statement
Loops are used to repeatedly perform a set of commands multiple [Link] supports 3 types of looping
structures-
while loop,do while loop and for loop.
No while loop do while loop For loop
1 The while loop is top tested The do while loop is bottom The for loop is top tested or entry
or entry controlled loop that tested or exit controlled loop controlled loop that repeats a
repeats a block of that repeats a block of block of statements as longs as
statements as longs the the loop’s counter does not reach
statements as longs the
Boolean condition is true. it’s target value.
Boolean condition is true.
2 If the loop condition is The loop body will be executed If the loop condition is initially
initially false, the loop body atleast once. false, the loop body will not be
will not be execute. execute.
3 Variable has to be declared Variable has to be declared Variable can be declared in the
outside the loop. outside the loop. initialization section of for loop.
4 Variable has to be Variable has to be incremented Variable can be incremented or
incremented or decremented or decremented inside the decremented in the increment/
inside the loop. loop. decrement section of for loop.
5 When the number of When specific code has to When the number of iterations
iterations is not known, executed once regardless of (repetitions) is known, for loop is
while loop is the best. whether condition is true or the easiest and the most
false, the do while loop can be compact.
used.*
*Note:This is useful in some cases for example when a Menu has to be displayed initially.
No Sentinel* Controlled Loop (while and Counter Controlled Loop (for)
do while)
1 Sentinel controlled loops repeats a block of Counter controlled loop repeats a block of statements
statements as longs the Boolean condition is as longs as the loop’s counter does not reach it’s
true. target value.
2 Sentinel controlled loops do not have a built Counter controlled loop can have a built in variable
in variable. which is declared in the initialization section of for
loop.
3 More suited when the number of iterations is More suited when the number of iterations is known.
not known.
Eg while loop, do while loop Eg for loop
*Note:Sentinel means “look out man”.It refers to the condition which is tested each time the block of code
is executed.
No Entry Controlled or Top Tested Exit Controlled or Bottom Tested
or Pre Tested Loop or Post Tested Loop
1) The Condition is Tested at the beginning of The Condition is Tested at the end of the Loop
the Loop.
2) If the loop condition is initially false (while The loop body will be executed atleast once.
loop) or true (until loop), the loop body will
2
not be executed.
3) Eg Eg
do while…loop do while loop
for loop
No Infinite Loop Empty Loop
1 An Infinite is a loop which never ends. An Empty is a loop which does not contain any
statement in the loop body.
2 Generally the infinite loop is used when exit Generally empty loop is used to introduce a time
from the loop depends on an extra condition delay.
inside the loop body rather than the loops
condition.
3 eg for (int i=0; i<10; ) eg for (int i=0; i<10; i++);
[Link](“OK”);
No break continue
1 Break is used to instantly exit out of a loop. Continue does not exit out of a loop but skips the
rest of the statements after it in the loop.
2 Control goes to the statement immediately Control goes to the condition part of the while and
after the loop. do while loops and to increment/decrement section
of the for loop.
Nested Loop [Link](0)
A nested loop is one loop placed inside another [Link](0) is used to terminate the execution of
loop. a java program.
return value return Statement
The return value is the value returned from the The return statement is used to return a value from
called method to the calling [Link] a method the called method to the calling [Link] can also
does not return a value, it is called a void method.
be used to exit from the current method and
transfer control back to the calling method.
Eg1 return ans;
Eg 2 return;
Other possible questions: Differences between break and [Link](0), break and return, return and
[Link](0).
Why are break, continue and return known as “jump” statements?
Break, continue and return known as “jump” statements because they transfer control unconditionally.
Note:If the above is a 2 mark question also explain break, continue and return.
Method or Function
A method is a named block of java statements which are grouped together to perform an action or to
return the result of an operation.A method consists of the method header and the method body.A method
may or may not take arguments(parameters) and it may or may not return a value to the calling method.
umber ofAdvantages
times that of
theMethods or Function
1)Large and complex programs becomes smaller and more manageable
ody will execute is already
2)Maintenance becomes easier as changes have to be made only in the required methods.
d by the
3) Loop Counter.
Methods allow reusability of [Link] a method has been created it can be called whenever required.
4)The programmer does not have to worry about the unnecessary details of how the tasks are
implementated of inside the method.
The Structure Of A Method (Function)
3
Note: When the method does not return any value, it is specified to return “void”
No Actual Parameters* Formal Parameters
1 These are Parameters that appear in the These are Parameters that appear in the
calling method and they pass the values to definition of the called method and they receive
formal parameters. the values passed as actual parameters.
2 int z=max(x,y) public static max(int num1,num2){
Here x and y are actual parameters. Here num1 and num2 are formal parameters.
Note: Parameter is also called Argument
Method Definition
The declaration of a method with it’s header and body is known as method definition.
Method Prototype or Method Header Method Signature
The first line of the method definition which tells the The part of the method definition which consists of
compiler about the number of arguments of the number of arguments of the method and the data
method, the data type of the arguments and return type of the arguments BUT NOT THE RETURN TYPE
type of the method is the method prototype. is the method signature.
Eg public static int findSum(int a,int b) Eg findSum(int a,int b)
*Method signatures are used by the compiler to resolve methods calls in the case of overloaded methods.
The main() method
main() is a special method which is invoked * by the Java Virtual Machine and is the starting point of
execution for all java [Link] Java compiler will not compile classes that do not contain a main( )
method.
* called
public class j01 Scope of a variable
{ The scope of a variable refers to parts of the
public static void main(String args[]) program in which the variable is available.A
{ general rule is that the variable is available within
double n1=5; the set of braces it is declared.
if(n1==5) Note:Related to scope is “Visibility”.Visibility
{ refers to the whether a variable can be used from
double n2=6; a given place in the program.
[Link](n1); Local Variable
[Link](n2); A local variable is variable which is declared
} inside a method The scope of a local variable is
[Link](n1); limited to the method in which it is declared. (ie it
[Link](n2); //Error, n2 is out of cannot not be used outside that method).It has to
scope be declared before it is used.
}
}
Note:A variable declared as formal parameter in a method also has local scope.(Refer example below)
General Rules for Variable Scope
VARIABLES DECLARED INSIDE A BLOCK (BRACES) ARE ONLY AVAILABLE IN THAT BLOCK
1) Variables declared inside a class(global variables) are available to all methods in the class
4
2) Variables declared inside a method (local variables) are only available in that method
3) Variables declared inside a for loop or if construct are only available in within that construct
4)Variables declared in outer blocks are available in inner blocks but not vice versa
OR Braces can be used to understand Variable [Link] variables declared inside a pair of brackets are only available between them.
IMP: “Flow Of Control” when 1 Method calls another Method (FOR UNDERSTANDING ONLY)
package example;
a,b and solution are local
public class example
variables in main() method.
{ ie they cannot be used
public static void main(String[] args) outside main() method.
{
int a=1,b=2,solution;
[Link]("Beginning of main" ); Here main() is the calling
solution=findBigger(a,b); method and a and b are
[Link]("Bigger number is "+solution ); Actual Parameters
[Link]("End of main" );
n1,n2 and big are local
} variables in findBigger()
public static int findBigger( int n1,int n2) method. ie they cannot be
{ used outside findBigger()
int big; method.
[Link]("Beginning of findBigger" );
if (n1>n2)
findBigger is the called
big=n1; method and n1 and n2 are
else Formal Parameters
big=n2;
[Link]("End of findBigger" );
return big;
}
}
Output
Beginning of main
Beginning of findBigger
End of findBigger
Bigger number is 2
End of main
Types Of Parameter Passing
Types of parameter passing refers to ways in which arguments can be passed into a [Link]
primitive data types are passed they are passed by value,but when reference data types or objects of
classes are passed,they behave as if they are passed by reference.
Example below only for understanding parameter passing behavior.
Pass by Value Pass by Reference
package j01; package j01;
public class j01 public class j01
{ {
public static void main(String[] args) public static void main(String[] args)
{ {
int n1=1,n2=2; c c1=new c(); //like Scanner s1=new Scanner();
[Link]("Original value of n1 : "+n1 ); c1.n1=1;
[Link]("Original value of n2: "+n2 ); c1.n2=2;
swap(n1,n2); [Link]("Original value of n1 : "+c1.n1 );
[Link]("New value of n1 : "+n1 ); [Link]("Original value of n2: "+c1.n2 );
[Link]("New value of n2: "+n2 ); swap(c1);
} [Link]("New value of n1 : "+c1.n1 );
public static void swap( int a,int b) [Link]("New value of n2: "+c1.n2 );
{ }
int temp; public static void swap(c ca )
5
temp=a; {
a=b; int temp;
b=temp; temp=ca.n1;
} ca.n1=ca.n2;
}HOTS:What will be output if formal parameters are n1 ca.n2=temp;
and n2? }
}
class c
{
int n1;
int n2;
}
Output Output
Original value of n1 : 1 Original value of n1 : 1
Original value of n2: 2 Original value of n2: 2
New value of n1 : 1 New value of n1 : 2
New value of n2: 2 New value of n2: 1
No Pass by Value Pass by Reference
1 Pass by value occurs when the actual parameters Pass by reference occurs when the actual parameters
are primitive data types like int,double etc. are reference data types like objects of classes .
2 Pass by value is a type of Parameter passing in Pass by reference is a type of Parameter passing in
which the called method has copies of the actual which the called method works with references to the
parameters. actual parameters.
3 Changes made within the called method are not Changes made within the called method are reflected
reflected in the calling method. in the calling method.
Although Strings are Reference types, changes made to Strings are not reflected in the calling
[Link].
Strings are reference data types but they are an exception to the rules of pass by reference because
Strings are immutable and cannot be [Link] changing a String which is passed by reference
to a method will not change the original String.
Types of Methods
Computational Methods Manipulative Methods Procedural Methods
Computational methods perform Manipulative methods manipulate Procedural methods perform a
a mathematical calculation and information or perform tests and required action but do not return
return a numeric value. return return a success or failure any value.
code.
Eg double findSum(int a,int b) boolean checkPresent(String s) void display(double d)