Java: Accept a number and check the number is even or not

Java Basic: Exercise-49 with Solution

Write a Java program to accept a number and check whether the number is even or not. Prints 1 if the number is even or 0 if odd.

Pictorial Presentation:

Java Basic Exercises: Accept a number and check the number is even or not

Sample Solution:

Java Code:

import java.util.*;
 public class Exercise49 {
     public static void main(String[] args){
	 Scanner in = new Scanner(System.in);
	 System.out.print("Input a number: ");
     int n = in.nextInt(); 
            if (n % 2 == 0) {
			else {

Sample Output:

Input a number: 20                                                     


Flowchart: Java exercises: Accept a number and check the number is even or not

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to print the odd numbers from 1 to 99. Prints one number per line.
Next: Write a Java program to print numbers between 1 to 100 which are divisible by 3, 5 and by both.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.

Java: Tips of the Day

Handling Null Pointer Exception

Null pointer exception is a runtime exception that is thrown when an application is trying to use an object reference with a null value.

String fruit;

Here a null reference variable is passed as an argument of a method.


In the above code snippet, null is directly passed to a function. In both these instances, there is a high possibility of throwing the NullPointerException.

This exception can be fixed by using the if-else condition.

public class NullPointerExceptionExample{
    public static void main(String args[]){
        String fruit = "apple";
}//Using an if-else condition
    static void positionLocator(String fruit){
        if(fruit != null){
           System.out.println("Second character: "+fruit.charAt(0));
        else {
           System.out.println("NullPointerException thrown");

Ref: https://bit.ly/3mi39Nr


We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook