ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming»
  • Programming Languages

Java Program: Using If-Else Statement in Java Programming

Updated on October 31, 2013

Get A Website Plus a Free Domain Name in Just 1 Hour!

Bring the new technology in your hands! Share your skills, improve and impress. Get Your Own Website and a Free Domain Name Here!

If and Else Statement in Java with Sample Java Source Code

If and else statement in Java programming means if(condition here meets){implement your code here} else{implement this code instead}. Hence the syntax for if and else statement in Java programming is this:

if(condition)

{

Write your code here

}

else

{

Write your code here

}

Usually the if and else statement is used if the program has a unique condition to be done and the other condition is exactly the opposite of that unique condition. The else statement is just another gateway for the program to execute something if it does not meet the unique condition it needs on the if statement.

For example, we will write a program about determining whether the user is a teenager or not. So we will have an algorithm that says, if the user is age 13-19, the program will say that she/he is a teenager. Else if the user is less than or greater than the specified ages, the program will say, you are not a teenager. Just note that if the user will enter he/she is 12 the program will say “you are not a teenager”, the output is similar also if the user enters that he/she is 20. See the Java Free Source code below:

Package name: teenager_identifier

package teenager_identifier;

import java.util.Scanner;


public class Main {

    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter your age: ");
        int user_age = input.nextInt();

        if(user_age >= 13 && user_age <= 19)
        {
            System.out.println("You are a Teenager.");
        }
        else
        {
           System.out.println("You are not a Teenager.");
        }
    }

}

Sample Output:

Simple isn't it? :) Happy Programming!

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.