The statements of a java program will always be executed in sequential order. If we do not want to execute the statements in a sequential order then we need to take the help of control statements.
The control statements will help the programmer to decide the flow of execution in a program.
The control statements are classified into following categories.
1. Conditional Statements 1.1 if-else statement 1.2 Switch statement 2. Iterating Statements
2.1 for loop 2.2 while loop 2.3 do-while loop 2.4 for-each loop 1. Conditional Statements:
These statements can execute a group of statements based on a condition or a value.
1.1 If else statement:
The if-else stmt can be used for executing a group of statements based on condition.
Syntax: if(condition){
Stmt1 } else {
stmt2 }
* If the condition is satisfied then if block will be executed and if the condition is not satisfied then execute else block.
Ex:
Class IfElseDemo {
Public static void main (String [] args) {
int n=2;
if (n%2=0) {
System.out.println(“Even Number”);
} else {
System.out.println(“Odd Number”);
} }
} Rules:
* Specifying condition to the if statement is mandatory and it should be only Boolean type.
* Specifying an else block is optional.
* Specifying flower braces is optional. If we do not specify flower braces then it will consider only one statement and that one statement is mandatory. If we want to consider multiple stmts then specify the flower braces is mandatory and within the flower braces we can specify any no of stmts (0 or more).
* In if-else stmt we can execute exactly one block either if block or else block. There is no chance of slipping both the blocks and no chance of executing both the blocks.
1.2 Switch statement:
The switch stmt can be used for executing a group of stmts based on a value.
Syntax:
Switch (argument) {
Case label 1: statement1;
break;
Case label 2: statement2;
break;
Case label 3: statement3;
break;
default: statement;
}
* If an application contains less no of options then use if else. But if an application contain multiple options then recommended to use switch statement because it improves the readability of the code.
Ex:
Class SwitchDemo{
Public static void main(String[] args){
int ch=3;
Switch(ch){
Case 1: System.out.println(“first choice”);
break;
Case 2: System.out.println(“second choice”);
break;
Case 3: System.out.println(“third choice”);
break;
Case 4: System.out.println(“fourth choice”);
break;
default: System.out.println(“wrong choice”);
} }
}
* Replace switch statement by if else ladder.
Class SwitchDemo {
Public static void main (String[] args) {
int ch=3;
if(ch==1){
System.out.println(“first choice”);
}
elseif(ch==2){
System.out.println(“second choice”);
}
elseif(ch==3){
System.out.println(“third choice”);
}
elseif(ch==4){
System.out.println(“fourth choice”);
} else{
System.out.println(“wroong choice”);
} }
} Rules:
* Specifying the argument to switch stmt is mandatory and it should be either byte type, short type, char type or int type.
* Specifying the case & default both are optional.
* Specifying the flower braces to the switch stmt is mandatory.
* The default stmt can be specified within the switch block. Generally the default stmt will be specified after all the cases.
* A switch stmt can contain any no of case (0 or more).
* A switch stmt can contain atmost one default stmt.
* The case labels must be unique. Most not be empty and must not be repeated.
PROGRAM: To read data from keyboard.
import java.io.*;
class ReadData{
Public static void main (String[] args) Throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print(“Enter first number:”);
String s1=br.readline();
int a=Integer.parseInt(s1);
System.out.print(“Enter second number:”);
String s2=br.readline();
int b=Integer.parseInt(s2);
System.out.print(“sum:”+(a+b));
} }
Ex:Program to write the biggest number using If Else condition.
class IfElseDemo {
public static void main(String[] args) {
int a=10, b=30, c=20, d=8;
if((a>b)&(a>c)&(a>d)) {
System.out.println("a is big);
}
elseif((b>c)&(b>c)&(b>d)) {
System.out.println("b is big);
}
if((c>a)&(c>b)&(c>d)) {
System.out.println("c is big);
} else {
System.out.println("d is big);
} }
}
O/P: b is big
Ex: Write a program to perform mathematical calculations using switch statement.
Class SwitchDemo{
Public static void main(String[] args){
int a=8, b=4, c;
int ch=3;
Switch(ch){
Case 1: c=a+b;
System.out.println(“sum is:”+c);
break;
Case 2: c=a-b;
System.out.println(“subtraction is:”+c);
break;
Case 3: c=a*b;
System.out.println(“multiplication is:”+c);
break;
Case 4: c=a/b;
System.out.println(“division is:”+c);
break;
} }
}
O/P: multiplication is: 32
* Switch argument & continues until it encounters a break statement (or) teachers end of the switch statement.
* The break statements is a transfer statement which will transfer from inside switch to outside.
So that it stops (or) skips the execution of remaining cases. So that remaining statements are not executed.
* Replacing switch with else if ladder.
Class SwitchDemo{
Public static void main(String[] args){
int ch=2;
if(ch==1){
System.out.println(“first choice”);
}
if(ch==2){
System.out.println(“second choice”);
}
if(ch==3){
System.out.println(“third choice”);
}
if(ch==4){
System.out.println(“fourth choice”);
} else{
System.out.println(“wrong choice”);
}
} }
O/P: Second choice
Replacing switch with else if ladder is not recommended to reduce the readability of the program.
Iterating statements:
The iterating statements can be used if we want to execute a group of statements repeatedly multiple times.
1. For Loop:
Purpose: A for loop has to be used if we want to execute a group of statements multiple times & it should be used when we know the exact number of iterations.
Syntax:
* Program to write multiplication table using for loop:
Class forDemo{
public static void main(String[] args) {
int n=6;
for(int i=1; i<=10; i++){
System.out.println(n+"*"+i+"="+(n*i));
} }
}
O/P: 6 Multiplication table
Rules:
* All the three sections (initialization, condition, inc/dec) of for loop a re optional.
* Specifying the section seperators (semicolons) is mandatory.
Ex: for(;;)
* If we do not specify initialization, inc/dec then the compiler will not provide any initialization
& will not provide inc/dec, but if we do not specify any condition then compiler will provide a boolean value “true”.
for(;true;)
* for(;;) – infinite loop.
* The initialization & inc/dec section can contain any valid java statement but the condition section must be of only boolean type.
* The initialization section can contain multiple initializations separated by comma, and all the initializations must be of the same type & the datatype must be specified only one time.
* The inc/dec section can contain multiple inc/dec separated by comma.
* The condition section can contain multiple condition which has to be combined using logical operators. Use only 5 operators (&, &&, |, ||, ^) but not use (!) operator this is complementing not combining the condition.
* All the three sections of for loop are independent.
For(i=1; j<=6; k++)
* Specifying the flower braces is optional. If we do not specify the flower braces, it will consider only one(first) statement & that statement is mandatory. If we want to consider multiple statements specifying the flower braces is mandatory & within the flower braces we can specify any number of statements.
* The variable that is declared inside a for loop can be used in for loop.
Even Numbers from 1 to 100:
class EvenMumbers {
public static void main(String[] args) {
for(int n=2; n<=100; n++) {
if(n%2==0) {
System.out.println(n);
n++;
} else {
System.out.println(“odd numbers”);
} }
} }
2. while loop:
While loop can be used for executing a group statements responsibility multiple times. The while loop should be used when we don’t know the exact no of iterations.
Syntax: while(condition) {
Statements }
*Multiplication table using while loop:
Ex: class WhileDemo
{
public static void main(String[] args) {
int n=8, i=1;
while(i<=10) {
System.out.println(n+"*"+i+"="+(n*i));
i++;
} }
} Rules:
* For a while loop, specifying the condition is mandatory and it must be of boolean type.
* In a while loop, specifying the flower braces is optional. If we donot specify the flower braces, will consider only one statement & that one statement is mandatory.
* If we want to consider multiple statements then specifying the flower braces is mandatory.
Within the flower braces, we can specify any number of statements.
** Every statement in a java program has to be executed at some point of time. If the control is unable to reach any statement in the program then the compiler would raise an error called
“unreachable statement”.
do-while loop:
The loop can be used for executing a group of statement repeatedly multiple times. This loop should be used when we donot know the exact no of iterations.
Syntax:
do {
Statements } while(condition);
Program: To write multiplication table using do while loop.
class DoWhileDemo {
public static void main(String[] args) {
int n=8, i=10;
do {
System.out.println(n+"*"+i+"="+(n*i));
i--;
}while(i>=1);
} }
Difference between while & do-while loop?
* In a while loop, the statements will be executed after the condition is checked. Where as in a do-while loop, the statements will be executed before the condition is checked.
* In a while loop, if the condition is false for the first time then the statements will not be executed where as in a do-while loop, if the condition is false for the first time then the statements will be executed for one time.
* In a while loop, the statements will be executed for 0 (or) more times. In a do-while loop, the statements will be executed for 1 (or) more times.
The loops can be nested:
class NestedloopDemo {
psum(String[] args) {
for(int i=1; i<=5; i++) {
for(int j=1; j<=5; j++) {
System.out.println("*");
}
System.out.println();
} }
}
O/P: * * * * *
* * * * *
* * * * *
* * * * *
* * * * *
*ASSIGNMENT * * * * *
* * * *
* * *
* *
*
*
* *
* * *
* * * *
* * * * * Transfer Statement:
The transfer statement can be used for transferring the control from one location to another location.
1. Break Statement:
The break statement can be used either in switch (or) in loops. The purpose of break statement in switch is to transfer the control from inside the switch to outside the switch.
So that it skips the execution of remaining cases.
The purpose of break statement in a loop is to transfer the control from inside the loop to outside the loop so that it skips the execution of remaining iterations.
Ex:
class BreakDemo {
psum(String[] args) {
int sum=0, capacity=234;
for(int i=1;i<=10;i++) {
System.out.println(i);
sum=sum+i;
if(sum>=capacity) break;
}
System.out.println(sum);
} }
O/P: 1 2 3 ' ' ' 13
sum=--Alternative code for previous ex using while loop:
class BreakDemo {
psum(String[] args) {
int sum=0, capacity=234;
while(sum<capacity) {
System.out.println(i);
sum=sum+i;
i++;
}
System.out.println(sum);
} }
ASSIGNMENT:
Print 100 prime numbers from using loops.
Sum of digits of an number
Reverse of a number
*
* *
* * *
* * * *
* * * * * class pyramid1 {
psum(String[] args) {
for(int i=1; i<=5; i++) {
for(int j=1; j<=i; j++) {
System.out.println("*");
}
System.out.println();
} }
}
* * * * *
* * * *
* * *
* *
* class pyramid2
{
psum(String[] args) {
for(int i=1; i<=5; i++) {
for(int j=1; j<=5; j++) {
if(i<=j)
System.out.println("*");
} else {
System.out.println("-");
}
System.out.println("-");
}
System.out.println();
} }
}
2. Continue Statement:
The continue statement can be used for skipping the current iteration &
continuing with the next iteration.
Ex:
class continueDemo {
psum(String[] args) {
for(int i=1; i<=10; i++) {
if(i==7|i==3) continue;
System.out.println(i);
} }
}
O/P: 1 2 4 5 6 8 9 10
Note: It is recommended to use the break & continue statement along with a condition.
ARRAYS
Array:
If an application requires multiple values then we can store those multiple values by declaring multiple variables in a program. If the no of variables are increased in the program
then the code size will increase & it will reduce the readability of the code.
* To reduce the code size & to improve the readability of the code, we take the help of the concept called an “Array”.
* An array is a derived data type using which we can store multiple values.
The arrays are classified into two types.
1. Single Dimension Array 2. Multi Dimension Array 1. Single Dimension Array:
Single Dimension Array can be used for representing a group of values either a single row (or) single column.
Syntax:
datatype arrayname[];
* To represent an array we take the help of square braces[]. Each pair of square braces represents one-dimension.
Rules:
* The pair of square braces can be specified either before the array name (or) after the array name.
int rollNo[];
float[] percent;
char [] grade;
boolean result[];
* We must not specify the size of the array at the time of array declaration boolean result[5];
* Percent is an array name where we can store multiple values of float datatype.
* The name of the array can be any valid java identifier.
int x[];
* Syntax for creating an array. We can use any way of both the two types.
1. datatype arrayname[] = new datatype[size];
or 2. datatype arrayname[];
arrayname = new datatype[size];
Ex: 1. int arr[] = new int[5];
or 2. int arr[];
arr = new int[5];
* At the time of array creation, specifying the size of the array is mandatory & it should be of either byte (or) int (or) char type.
Ex: byte x = 10;
int y = 10;
long z = 10;
int[] arr1 = new int[x]; //valid because of byte type int[] arr2 = new int[y]; //valid because of int type int[] arr3 = new int[z]; //invalid because of long type int[] arr4 = new int[10]; //valid because of int type
int[] arr5 = new int[-10]; //invalid [ Negative array size exception]
int[] arr6 = new int[1.0]; //invalid because of float int[] arr7 = new int[‘z’]; //valid because of char int[] arr8 = new int[0]; //valid but no result
int[] arr9 = new int[]; //invalid because of boolean
int[] arr10 = new int[]; //invalid because of size is missing
int[] arr = new int[10];
arrayname[index] = starting address of array + index * size of array type
arr[0] = 1000 + 0 * 4 = 1000 arr[1] = 1000 + 1 * 4 = 1004 arr[6] = 1000 + 6 * 4 = 1024
* When an array is created, the memory for that array will be allocated in continuous memory locations. The allocation of the memory will be based on type of the array & size of the array.
* An array is a collection of multiple elements & to access those elements we take the help of index positions.
* The index of an array always starts with ‘0’.
* The range of the index will be 0 to [size-1] why starts with ‘0’ means to reduce the wastage of memory of ‘0’ if they starts with “1”.
* Once the memory for the array is allocated, all the elements in that array will be initialized automatically with default values of the array type.
* Every array is internally an object which provides a variable called “length” which will specify the size of the array.
Syntax for accessing the array elements:
arrayname[index]
Syntax for assigning the array elements:
arrayname[index] = value;
Ex: arr[0] = 11;
Note:
If we specify an index position which is outside the range of the array index then we get a runtime error called as “ArrayIndexOutOfBandsException”.
for each loop (or) Enhanced for loop:
This loop is designed to work on arrays(collections). It is introduced in 1.5 version of java.
Syntax:
for(Variable declaration : arrayname) {
Statements }
Rules:
* The declaration of the variable in for each loop must be same as that of the array type.
Class ArrayDemo{
Psum (String[] args){
Int[] arr;
arr = new int[5];
System.out.println(arr[0]);
System.out.println (arr[1]);
System.out.println (arr[2]);
System.out.println (arr[3]);
System.out.println (arr[4]);
arr[0] = 12;
arr[1] = 23;
arr[2] = 34;
arr[3] = 45;
arr[4] = 56;
for(int i=0; i<arr.length; i++){
System.out.println (arr[j]);
}
for(int x : arr){
System.out.println (x);
} } }
Example:
Class Student{
Psum(String[] args){
int marks[];
marks = new int[5];
marks[0] = 99;
marks[1] = 100;
marks[2] = 94;
marks[3] = 39;
marks[4] = 90;
int total = 0;
boolean result = true;
for(int i=0;i<marks.length;i++){
System.out.println("subject"+(i+1)+"marks:"+marks[i]);
total = total + marks[i];
if(marks[i]<35) boolean = false;
}
System.out.println("Total:"+total);
int avg = total/marks.length;
System.out.println("Average:"+avg);
if(result) {
if(avg>=75){
System.out.println("grade:"+Distinction);
}
else if (avg>60){
System.out.println("Grade:"First class);
}
else if (avg>50){
System.out.println("Grade:"Second class);
} else {
System.out.println("Grade:"Third class);
} }
else {
System.out.println("Welcome Again");
} }
}
Declaring Creating & Initializing the array elements in a single line:
Syntax: datatype[] arrayname = {list of values};
Ex: int[] arr = {11,45,21,38,43,25};
With in the flower braces, we can specify any no of values separated by a comma.
* When we are declaring, creating & initializing the array elements in a single line then we must not specify the size of the array. The size of the array will be decided automatically based on number of elements specified within the flower braces.
int[] arr = {11,45,21,53,72,81}; 1 double[] arr = {10.5,4.8,3.9,11.5,13.3};
char[] ch = {‘a’, ‘b’, ‘c’,’d’};
Int[] arr; 2
arr = new int[6]; 3
arr[0] = 11; 4
arr[1] = 45; 5
arr[2] = 21; 6
arr[3] = 53; 7
arr[4] = 72; 8
arr[5] = 81; 9
* Instead of using 2 to 9 we can directly use 1.