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
java -versionopenjdk 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:
| Editor | Good for |
|---|---|
| IntelliJ IDEA Community | Free, the most popular Java editor |
| Visual Studio Code | Light and fast, add the "Extension Pack for Java" |
| Eclipse | Free, used in many companies and universities |
Your First Program
Create a file named Main.java and type this code:
Example
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
javac Main.java
java MainHello, 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
java Main.javaPrinting More Than One Line
Each println prints its text and then moves to a new line:
Example
public class Main {
public static void main(String[] args) {
System.out.println("Name: Ayesha");
System.out.println("City: Karachi");
System.out.println("Course: Java");
}
}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.printlnis an error; it must beSystem - File name mismatch:
public class Mainin a file calledmain.javawill not compile - Missing braces: every
{needs a matching}
Exercise
Exercise
Which command compiles the file Main.java?
