Simple Java Programs

28
SAMPLE JAVA PROGRAMS

description

 

Transcript of Simple Java Programs

  • 1.
    • SAMPLE JAVA PROGRAMS

2. Comparing Two Numbers This is a very simple example of Java that teaches you the method of comparing two numbers and finding out the greater one . 3.

  • First of all, name a class "Comparing" and take two variables in this class (ie, a & b). Here we have taken a=5 and b=10,
  • Now we have to find out whether a=b, a>b or b>a.
  • To find out this apply if and else condition one by one.
  • Now apply the condition "if (a=b)", if this satisfies then print both are equal.
  • If this doesn't satisfy, then check whether a>b by applying the "else if" condition and print the message "a is greater than b.
  • Again this doesn't satisfy then 'else' condition as shown in the example will show that b is greater than a.

4.

  • code of the program:
  • class Comparing{ publicstaticvoid main(String[]args){ int a=5,b=10; if (a==b){ System.out.println("Bothareequal"); } elseif (a>b){ System.out.println("aisgreaterthanb"); } else { System.out.println("bisgreaterthana"); } } }

5. How to compile & run

  • Compiling:
  • javac Comparing.java
  • Run:
  • java Comparing
  • Out put:
  • bisgreaterthana

6. Program to list all even numbers between two numbers

  • This is a program for listing out all the even numbers between two numbers.

7.

  • For this first create a class namedAllEvenNumunder 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 theSystemmethod.
  • As we have to find out all the even numbers between 1 and the input number, define an integer variable 'num'.
  • Now applyParseIntmethod that parses the string character into decimal integer.
  • Applyforloop in which define an integer i=1 and i