If statement in Java

Hello friends how are you, today in this blog i will teach you what is if statement, syntax of if statement , how if statement works and many programs using if statement in a very simple way.

Let's start

 If statement in Java

 

  • It is used to test the condition.
  • If the condition is true its body will execute otherwise does not execute.
class Easy
{
 public static void main(String[] args) 
 {
  int x=10;
  if(x>5)
  {
      System.out.println("x is greater than 5");    
  }
 }
}
/*
### Output ###
x is greater than 5
*/

Here we will use single variable for number and after taking user input we will apply condition on it.
if number is greater than 0 then print positive, if number is less than 0 print negative and when number is equal to 0 print zero.

import java.util.Scanner;
class Easy
{
 public static void main(String[] args) 
 {
  Scanner in=new Scanner(System.in);
  int no;
  System.out.println("Enter any number");
  no=in.nextInt();
  if(no>0)
   System.out.println("number is positive");    
  if(no<0)
   System.out.println("number is negative");    
  if(no==0)
   System.out.println("number is zero");  
 }
}
/*
### Output ###
Enter any number
-5
number is negative
*/

Hello we will take three variable for numbers and after taking user input we will apply condition on it and will print the result.

//import library
import java.util.Scanner;
class FindGreater 
{
 public static void main(String[] args) {
  Scanner in=new Scanner(System.in);
  //variable declaration
  int no1,no2,no3;
  //taking user input
  System.out.println("Enter first number");
  no1=in.nextInt();
  System.out.println("Enter second number");
  no2=in.nextInt();
  System.out.println("Enter third number");
  no3=in.nextInt();
  //applying condition
  if (no1>no2&&no1>no3)
         System.out.println(no1+" is greatest");
  if (no2>no1&&no2>no3)
         System.out.println(no2+" is greatest");
  if (no3>no1&&no3>no2)
         System.out.println(no3+" is greatest");
}
   
}
/*
###OUTPUT###
Enter first number
85
Enter second number
92
Enter third number
74
92 is greatest
*/

Request:-If you found this post helpful then let me know by your comment and share it with your friend. 
If you want to ask a question or want to suggest then type your question or suggestion in comment box so that we could do something new for you all. 

 If you have not subscribed my website then please subscribe my website. 

 Try to learn something new and teach something new to other. Thanks.

Post a Comment

0 Comments