Java Tutorial menu

Java Get Started

To write Java programs you need the Java Development Kit (JDK) and a text editor.

Install the JDK

The JDK contains the compiler (javac), the JVM (java) and the standard library. Download a free JDK such as Eclipse Temurin or Oracle OpenJDK, and choose a Long Term Support (LTS) version like Java 21.

After installing, open a terminal (Command Prompt on Windows) and check the version:

Example

text
java -version
Output
openjdk version "21.0.4" 2024-07-16 LTS

Your version number may be different. If you see a version, Java is ready.

Choose an Editor

You can write Java in any text editor, but an editor made for coding helps a lot:

EditorGood for
IntelliJ IDEA CommunityFree, the most popular Java editor
Visual Studio CodeLight and fast, add the "Extension Pack for Java"
EclipseFree, used in many companies and universities

Your First Program

Create a file named Main.java and type this code:

Example

java
public class Main {
  public static void main(String[] args) {
    System.out.println("Hello, Karachi!");
  }
}

The file name must match the class name exactly. A class called Main must be saved in Main.java, with a capital M.

Compile and Run

Open the terminal in the folder where you saved the file and run these two commands:

Example

text
javac Main.java
java Main
Output
Hello, Karachi!

The first command creates Main.class. The second command starts the JVM and runs it. Notice that you write java Main, without .class at the end.

Since Java 11 you can also run a single file in one step:

Example

text
java Main.java

Printing More Than One Line

Each println prints its text and then moves to a new line:

Example

java
public class Main {
  public static void main(String[] args) {
    System.out.println("Name: Ayesha");
    System.out.println("City: Karachi");
    System.out.println("Course: Java");
  }
}
Output
Name: Ayesha
City: Karachi
Course: Java

Common Beginner Errors

  • Missing semicolon: every statement ends with ;
  • Wrong capital letters: Java is case sensitive, so system.out.println is an error; it must be System
  • File name mismatch: public class Main in a file called main.java will not compile
  • Missing braces: every { needs a matching }

Exercise

Exercise

Which command compiles the file Main.java?

Learn Java with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp