1 - Conditional structure If & else else in Java
In Java, an if statement is a conditional statement that executes a set of statements according to a condition whether it is verified or not.Syntax:
if( condition ){ set of statements ...... } else{ set of statement... ... }
Example
int youAge=19; if(yourAge <= 18 ){ System.out.println("You are minor, because your age is : " + yourAge ); } else{ System.out.println("You are major, because your age is : " + yourAge ); }
Here is a complete example
Example
import java.util.Scanner; public class If { public static void main(String[] args) { System.out.println("How old are you !"); Scanner age=new Scanner(System.in); int yourAge=age.nextInt(); if ( yourAge < 18 ) { System.out.println("you are minor, because your age is : "+ yourAge); } else{ System.out.println("you are majorr, because your age is : "+ yourAge); } age.close(); } }
This displays:
You are major, if the age typed is> = 18
You are minor, if the age typed is <18
Note :
The else { command is not required2 - Loop For Java
There are many situations that require you to run a block of instructions several times in your applications. Loops can execute a block of code a number of times. The for Java loop will be useful in this caseSyntax:
For (start counter, end counter, counter increment) { Block of instructions }
Example:
For (int i = 1; i <= 10; i ++) { System.out.println ("hello!"); }
The above example shows 10 times the message "Hello !"
Hello !
Hello !
Hello !
Hello !
Hello !
Hello !
Hello !
Hello !
Hello !
Hello !
3 - Java while loop
The while loop is a control statement that allows the code to be repeatedly executed as long as a boolean condition is achieved.Syntax:
While (condition) { Block of instructions ... }
Example
Int i = 1; While (i <= 10) { System.out.println ("hello!"); i ++; }
The above example shows 10 times the message hello! And stops.
No comments:
Post a Comment