Even Numbers Example in Java

Java Exercise : Write a program to list all even numbers between two numbers

Here you will learn to write a program for listing out all the even numbers between two numbers. For this first create a class named AllEvenNum under the java.io package. Now use the try/catch exception to avoid any kind of input error. After this create a buffer class in which all the input data are stored and modified. Then give message as to "Enter number" in the System method. 

As we have to find out all the even numbers between 1 and the input number, define an integer variable 'num'. Now apply ParseInt method that parses the string character into decimal integer. Again apply for loop in which define an integer i=1 and i<=  num also with an increment operator. Then apply the if condition that i/2=0 i.e. to find even numbers which are divided by the integer 2. In the end apply the catch exception. 

Now and compile and run the program, and enter your desired number to get all even numbers between 1 and this numbers. 

Here is the code of program:

import java.io.*;

class AllEvenNum{
  public static void main(String[] args) {
    try{
      BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
      System.out.println("Enter number : ");
      int num = Integer.parseInt(br1.readLine());
      System.out.println("Even Numbers:");
      for (int i=1;i <=num ; i++){
        if(i%2==0 ){
          System.out.print(i+",");
        }
      }
    }
    catch(Exception e){}

  }

Do you have a Java Problem?
Ask It in The Java Forum

Java Books
Java Certification, Programming, JavaBean and Object Oriented Reference Books

Return to : Java Programming Hints and Tips

All the site contents are Copyright © www.erpgreat.com and the content authors. All rights reserved.
All product names are trademarks of their respective companies.
The site www.erpgreat.com is not affiliated with or endorsed by any company listed at this site.
Every effort is made to ensure the content integrity.  Information used on this site is at your own risk.
 The content on this site may not be reproduced or redistributed without the express written permission of
www.erpgreat.com or the content authors.