Related post

If, if..else , if..else..if statement in Java

 

Java conditional statement


If , If...else , nested if statement in Java

The If statement generally is used to test a condition. It is used to check whether a condition is true or false before executing a statement. 

For example, you might want to check if x is equal to y , if yes then add x and y or otherwise.


There are other examples like -

You might want to allow user to only register their profile only if they are of certain age. And the example goes on and on.


The if statement isn't just about testing alone, I would say it is needed in every program. The truth is, you can't just let users enter anything they like, there has to be rules and regulations, for example, if you have a form that allows user to enter their username and phones number, the colon for phone must accept only numbers and if the user does not follow up with the rules, an error must be displayed. This is where if statement is in use.


Let's see how it works in Java 

Syntax for If statement


   if ( expression ) {

//Statement ;

}




Examples



//by Zhullyblog

public class sample{

 public static void main(String[] args) {

 int num = 10;

 //test the statement

  if (num > 1){

    System.out.println("The number is greater than 1");

    }

  }

}


Screenshot

Java if statement

Result




If....else statement


The if else statement is used to test and also return result if the condition turns out to be false.


Syntax



if ( expression ){

  //Statement ;

}

else {

 //Statement;

}



Examples



//by Zhullyblog

public class sample{

 public static void main(String[] args) {

 int num = 10;

 //test the statement

  if (num > 1){

    System.out.println("The number is greater than 1");

    }

    else {

      System.out.println("The number is less than 1");

    }

  }

}




Screenshot

Java if else statement


Result


Let's move


Break statement in Java


Continue statement in Java


Inheritance in Java


Please share 







Follow us on




Comments