Wednesday, March 25, 2015

First Java program

Here goes the first java program to print hello world in eclipse or netbeans.

****Hello World******

class First {
  public static void main(String[] arguments) {
    System.out.println("Hello World");
  }
}

output: Hello World

*****Print integers*****
class Integers {
  public static void main(String[] arguments) {
    int c; //declaring a variable
 
  /* Using for loop to repeat instruction execution */
 
    for (c = 1; c <= 10; c++) {
      System.out.println(c);
    }
  }
}
output:
1
2
3
4
5
6
7
8
9
10


*****If-else statement*****

class Condition {
  public static void main(String[] args) {
    boolean learning = true;
 
    if (learning) {
      System.out.println("Java programmer");
    }
    else {
      System.out.println("What are you doing here?");
    }
  }
}



Swapping using temporary or third variable

import java.util.Scanner;
 
class SwapNumbers
{
   public static void main(String args[])
   {
      int x, y, temp;
      System.out.println("Enter x and y");
      Scanner in = new Scanner(System.in);
 
      x = in.nextInt();
      y = in.nextInt();
 
      System.out.println("Before Swapping\nx = "+x+"\ny = "+y);
 
      temp = x;
      x = y;
      y = temp;
 
      System.out.println("After Swapping\nx = "+x+"\ny = "+y);
   }
}

Output:
Enter x and y
3
4
Before Swapping
x=3
y=4
After swapping
x=4
y=3

No comments:

Post a Comment