Java For Beginners

Java For Beginners

April 4, 2017

This tutorial is for complete beginners in Java. In this tutorial, we will demonstrate how to get started with Java. Specifically, we will walk through installing Java and writing a simple Java class that prints a message to the console.

Getting Started With Java

This tutorial assumes you have Java installed. If you don't have Java installed on your machine, visit Oracle to download the most recent version for your operating system.

To easily test if Java is installed on your machine, open the command prompt or terminal window and run the following:

java -version

If Java is correctly installed on your machine, you should see something like this:

Alias-Macintosh:home userone$ java -version
java version "1.8.0_73"
Java(TM) SE Runtime Environment (build 1.8.0_73-b02)
Java HotSpot(TM) 64-Bit Server VM (build 25.73-b02, mixed mode)

Hello World Java

Now that we know Java is correctly installed, we can write our first Java program. In your terminal window, create a new file HelloWorld.java.

Open your newly created file and add the following:

HelloWorld.java

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

Note that we've created a class HelloWorldwith the same exact (case sensitive) name as the file we created. In Java, anything with an .java extension is considered a class. The class declaration must match the name of the file itself. If we were to define our class with public class helloWorld this would not work because it does not match the exact casing of HelloWorld.java.

Save your class HelloWorld.java and hop back over to your terminal window. Now that you've written your first Java class, it's time to compile the class into something the computer can run. In your terminal window, run:

javac HelloWorld.java

This command, javac, is the main compiler that comes with the Java SDK (what you downloaded earlier). We use the javac compiler to compile our HelloWorld.java into the computer readable HelloWorld.class file. Check your current directory (ls) and you should see the resulting

HelloWorld.class file. Now run:

java HelloWorld

If all went according to plan, you should now see your message printed out in the terminal console:

Hello World

Conclusion

That's it! You've just written your first Java program. It may not seem like much but you've written a Java class, compiled it, and executed it from the command line.

As next steps, start seeing how you can organize classes together with object oriented programming and "packages".


Join the conversation...



Submit




More by the stackchief