Sunday, July 13, 2008

Small Programs

Hello World



public class HelloWorld{
  public static void main(String args[]){
    System.out.println("Hello World");
  }
}
c:\>java HelloWorld
Hello World



Command Line Arguments




public class CmdArgs{
  public static void main(String args[]){
    System.out.println("The first argument is " + args[0]);
  }
}
c:\>java CmdArgs Hello
Hello


Usage of If-else



public class ExIf{
  public static void main(String args[]){
    if(args[0].equals("args")){
      System.out.println("You entered args");
    }
    else{
      System.out.println("You did not enter args");
    }
  }
}
c:\>java ExIf args
You entered args


Usage of For loop



public class ExFor{
  public static void main(String args[]){
    for(int i=1;i<=args.length;i++){
      System.out.println("The " + i + "th argument is " + args[i-1]);
    }
  }
}
c:\>java ExFor One Two Three
The 1th argument is One
The 2th argument is Two
The 3th argument is Three


Usage of while loop



public class ExWhile{
  public static void main(String args[]){
    int i=1;
    while(i<=args.length){
      System.out.println("The " + i + "th argument is " + args[i-1]);
      i++;
    }
  }
}
c:\>java ExWhile One Two Three
The 1th argument is One
The 2th argument is Two
The 3th argument is Three

No comments: