Thursday 11 July 2013

Java Hello World (Console)

This is a short tutorial for your first application in Java. I use Eclipse as software integrated developer environment (IDE), however there are many more (like Netbeans).

Let's start off with basic installation. First thing you need to install is Java Development Kit (JDK). After JDK, you need to install Eclipse IDE for Java Developers.

Open your Eclipse and click on "File"->"New"->"Project". Select "Java Project" and click "Next".



Type in a name like "HelloJava" and click "Finish".


A folder named HelloJava is created on left side of screen (Package Explorer). If you double click on that folder you can see its contents. Right-click on src subfolder and select "New"->"Package". Name it test.hello and click "Finish".


Now your package will appear in src subfolder. Right click on that package and select "New"->"Class". In name field type Hello and check the "public static void main(String[] args)" option. Click "Finish".



After this you will get some code that looks like this:

package test.hello;

public class Hello {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
 }
}


Now add a line System.out.println("This is my Hello Java!"); within main method so  it looks like following:

package test.hello;

public class Hello {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  
  System.out.println("This is my Hello Java!");
 }
}

System.out.println("Something, something");  is used to print out whatever is contained within quotation marks (in this case it will print out Something, something.

To run the program, click on green "play" button in upper left corner or press CTRL+F11. Result of your program will appear below your code in console.

Now let's add text input. For this we need to create a Scanner. It will save whatever we write in one line and then we can use it to print out what has been saved in it. To do this we need to insert two lines above our current code. First line is the declaration of Scanner with name "scanner" and it should be Scanner scanner = new Scanner(System.in);. You will notice that the word Scanner is underlined. It means you need to import that class to your project. To do this, simply hover over the word Scanner and select "import java.util.Scanner;". Second line is for printing text and it should be System.out.println(scanner.nextLine()); Your code should now look like this:

package test.hello;

import java.util.Scanner;

public class Hello {
 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub

  Scanner scanner = new Scanner(System.in);
  System.out.println(scanner.nextLine());
 }
}

Now you can run it, type whatever you wish in console and when you press "Enter" (new line), it will repeat what you wrote. That's it!