Download presentation
Presentation is loading. Please wait.
Published bySai Surya Modified over 2 years ago
1
Lecture 4- JAVA Training
2
Selection Statements Java supports two selection statements: if and switch. These statements allow you to control the flow of your program’s execution based upon conditions known only during run time.
3
If Statement Executes a block of statements only if a test is true if ( test ) { statement ;... statement ; } Example: double gpa = console.nextDouble(); if (gpa >= 2.0) { System.out.println("Application accepted."); }
4
The if/else statement Executes one block if a test is true, another if false if ( test ) { statement(s) ; } else { statement(s) ; } Example: double gpa = console.nextDouble(); if (gpa >= 2.0) { System.out.println("Welcome to Mars University!"); } else { System.out.println("Application denied."); }
5
Nested if/else A nested if is an if statement that is the target of another if or else. When you nest ifs, the main thing to remember is that an else statement always refers to the nearest if statement that is within the same
6
Example Chooses between outcomes using many tests if ( test ) { statement(s) ; } else if ( test ) { statement(s) ; } else { statement(s) ; } Example: if (number > 0) { System.out.println("Positive"); } else if (number < 0) { System.out.println("Negative"); } else { System.out.println("Zero"); }
7
Nested if/else/if – If it ends with else, one code path must be taken. – If it ends with if, the program might not execute any path. if ( test ) { statement(s) ; } else if ( test ) { statement(s) ; } else if ( test ) { statement(s) ; } Example: if (place == 1) { System.out.println("You win the gold medal!"); } else if (place == 2) { System.out.println("You win a silver medal!"); } else if (place == 3) { System.out.println("You earned a bronze medal."); }
8
The switch Statement The switch statement provides another way to decide which statement to execute next The switch statement evaluates an expression, then attempts to match the result to one of several possible cases Each case contains a value and a list of statements The flow of control transfers to statement associated with the first case value that matches
9
The switch Statement The general syntax of a switch statement is: switch ( expression ) { case value1 : statement-list1 case value2 : statement-list2 case value3 : statement-list3 case... } switch and case are reserved words If expression matches value2, control jumps to here
10
The switch Statement Often a break statement is used as the last statement in each case's statement list A break statement causes control to transfer to the end of the switch statement If a break statement is not used, the flow of control will continue into the next case Sometimes this may be appropriate, but often we want to execute only the statements associated with one case
11
The switch Statement switch (option) { case 'A': aCount++; break; case 'B': bCount++; break; case 'C': cCount++; break; } An example of a switch statement:
12
The switch Statement A switch statement can have an optional default case The default case has no associated value and simply uses the reserved word default If the default case is present, control will transfer to it if no other case value matches If there is no default case, and no other value matches, control falls through to the statement after the switch
13
The switch Statement The expression of a switch statement must result in an integral type, meaning an int or a char It cannot be a boolean value, a floating point value ( float or double ), or another integer type The implicit boolean condition in a switch statement is equality You cannot perform relational checks with a switch statement
14
GradeReport.java public class GradeReport { //---------------------------------------------------------- // Reads a grade from the user and prints comments // accordingly. //---------------------------------------------------------- public static void main (String[] args) { int grade, category; Scanner scan = new Scanner (System.in); System.out.print ("Enter a numeric grade (0 to 100): "); grade = scan.nextInt(); category = grade / 10; System.out.print ("That grade is ");
15
GradeReport.java switch (category) { case 10: System.out.println ("a perfect score. Well done."); break; case 9: System.out.println ("well above average. Great."); break; case 8: System.out.println ("above average. Nice job."); break; case 7: System.out.println ("average."); break; case 6: System.out.println ("below average."); System.out.println ("See the instructor."); break; default: System.out.println ("not passing."); }
16
Switch case Flow Diagram
17
Example of Switch Case public class Test { public static void main(String args[]) { char grade = 'C'; switch(grade) { case 'A' : System.out.println("Excellent!"); break; case 'B' : case 'C' : System.out.println("Well done"); break; case 'D' : System.out.println("You passed"); case 'F' : System.out.println("Better try again"); break; default : System.out.println("Invalid grade"); } System.out.println("Your grade is " + grade); } Compile and run the above program using various command line arguments. This will produce the following result − Output Well done Your grade is C
18
Iteration Statements Repetition statements allow us to execute a group of statements multiple times Often they are referred to as loops Like conditional statements, they are controlled by boolean expressions Java has three kinds of repetition statements: – the while loop – the do loop – the for loop The programmer should choose the right kind of loop for the situation
19
The while Statement A while statement has the following syntax: while ( condition ) statement; If the condition is true, the statement is executed Then the condition is evaluated again, and if it is still true, the statement is executed again The statement is executed repeatedly until the condition becomes false
20
Logic of a while Loop statement true false condition evaluated
21
The while Statement An example of a while statement: int count = 1; while (count <= 5) { System.out.println (count); count++; } If the condition of a while loop is false initially, the statement is never executed Therefore, the body of a while loop will execute zero or more times
22
The while Repetition Structure Flowchart of while loop product <= 1000 product = 2 * product true false int product = 2 int product = 2; while ( product <= 1000 ) product = 2 * product; int product = 2; while ( product <= 1000 ) product = 2 * product;
23
Example--Parts of a while loop int x = 1; while (x < 10) { System.out.println(x); x++; } Label the following loop int product = 2; while ( product <= 1000 ) product = 2 * product;
24
Nested Loops Similar to nested if statements, loops can be nested as well That is, the body of a loop can contain another loop For each iteration of the outer loop, the inner loop iterates completely
25
Nested Loops How many times will the string "Here" be printed? count1 = 1; while (count1 <= 10) { count2 = 1; while (count2 <= 20) { System.out.println ("Here"); count2++; } count1++; }
26
The do Statement A do statement has the following syntax: do { statement; } while ( condition ) The statement is executed once initially, and then the condition is evaluated The statement is executed repeatedly until the condition becomes false
27
Logic of a do Loop true condition evaluated statement false
28
The do Statement An example of a do loop: The body of a do loop executes at least once int count = 0; do { count++; System.out.println (count); } while (count < 5);
29
Comparing while and do statement true false condition evaluated The while Loop true condition evaluated statement false The do Loop
30
Choosing a Loop Statement If you know how many times the loop will be iterated, use a for loop. If you don’t know how many times the loop will be iterated, but –it could be zero, use a while loop –it will be at least once, use a do-while loop. Generally, a while loop is a safe choice.
31
The for Statement A for statement has the following syntax: for ( initialization ; condition ; increment ) statement; The initialization is executed once before the loop begins The statement is executed until the condition becomes false The increment portion is executed at the end of each iteration
32
Logic of a for loop statement true condition evaluated false increment initialization
33
The for Statement A for loop is functionally equivalent to the following while loop structure: initialization; while ( condition ) { statement; increment; }
34
For Loop Example class ForLoop { public static void main(String args[]) { for(int i=1;i<=3;i++) { System.out.println(i); } } The output of the above code will be :- 1 2 3
35
Java - Methods A Java method is a collection of statements that are grouped together to perform an operation. When you call the System.out.println() method, for example, the system actually executes several statements in order to display a message on the console. Now you will learn how to create your own methods with or without return values, invoke a method with or without parameters, and apply method abstraction in the program design.
36
Creating Method Syntax public static int methodName(int a, int b) { // body } Here, public static − modifier int − return type methodName − name of the method a, b − formal parameters int a, int b − list of parameters
37
Syntax Explanation The syntax shown above includes − modifier − It defines the access type of the method and it is optional to use. return Type − Method may return a value. Name Of Method − This is the method name. The method signature consists of the method name and the parameter list. Parameter List − The list of parameters, it is the type, order, and number of parameters of a method. These are optional, method may contain zero parameters. method body − The method body defines what the method does with the statements.
38
Program Structure class XYZ{ static RETURN_TYPE fun_name([arg-list]){ // function - body } public static void main(String args[]){ // Statements fun_name([arg-list]); // calling function // Statements }
39
Sample Program class ABC{ static void fun1(){ System.out.println("Called fun1() - No Arguments"); } public static void main(String arg[]){ fun1(); }
40
Passing Arguments class ABC{ static void fun2(int i){ System.out.println("Called fun2() - Single Argument Recieved :" + i); } public static void main(String arg[]){ fun2(8); }
41
Returning Value class ABC{ static int fun3(int i){ System.out.println("Called fun3() - Single Argument Recieved :" + i); System.out.println("This function returns double of recieved argument"); return i*2; } public static void main(String arg[]){ int k = fun3(16); System.out.println(k); System.out.println(fun3(20)); }
42
Recursion in Java Recursion in java is a process in which a method calls itself continuously. A method in java that calls itself is called recursive method. It makes the code compact but complex to understand. Syntax: returntype methodname() { //code to be executed methodname(); //calling same method }
43
Working of Recursion
44
Java Recursion Example 1 : Finite times public class RecursionExample2 { static int count=0; static void p(){ count++; if(count<=5){ System.out.println("hello "+count); p(); } public static void main(String[] args) { p(); } Output: hello 1 hello 2 hello 3 hello 4 hello 5
45
Java Recursion Example 2: Factorial Number public class RecursionExample3 { static int factorial(int n){ if (n == 1) return 1; else return(n * factorial(n-1)); } public static void main(String[] args) { System.out.println("Factorial of 5 is: "+factorial(5)); }
46
Working Of the Example Working of above program: factorial(5) factorial(4) factorial(3) factorial(2) factorial(1) return 1 return 2*1 = 2 return 3*2 = 6 return 4*6 = 24 return 5*24 = 120 Final Output Output: Factorial of 5 is: 120
47
Java Recursion Example 3: Fibonacci Series public class RecursionExample4 { static int n1=0,n2=1,n3=0; static void printFibo(int count){ if(count>0){ n3 = n1 + n2; n1 = n2; n2 = n3; System.out.print(" "+n3); printFibo(count-1); } public static void main(String[] args) { int count=15; System.out.print(n1+" "+n2); //printing 0 and 1 printFibo(count-2); //n2 because 2 numbers are already printed } Output: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.