Introduction to Java
Java is a powerful, object-oriented programming language widely used for building applications, ranging from web and mobile apps to enterprise systems and embedded devices. It follows the "Write Once, Run Anywhere" (WORA) principle, meaning Java programs can run on any platform that supports the Java Virtual Machine (JVM).
Installing Java
Before writing Java programs, you need to install the Java Development Kit (JDK).
Step 1: Download and Install JDK
- Visit the official Oracle website: Download JDK (opens in a new tab)
- Choose the appropriate version for your OS (Windows, macOS, or Linux).
- Install the JDK and set up the
JAVA_HOMEenvironment variable.
Ensure that you download the latest LTS (Long-Term Support) version for better stability and support.
Step 2: Verify Installation
Open a terminal or command prompt and type:
java -versionIf Java is installed correctly, you should see output similar to:
java version "23.0.1" 2025-02-20 LTS
Java(TM) SE Runtime Environment (build 23.0.1+12-LTS-39)
Java HotSpot(TM) 64-Bit Server VM (build 23.0.1+12-LTS-39, mixed mode)Writing Your First Java Program
Once Java is installed, let's write a simple program.
- Open a text editor (VS Code, IntelliJ IDEA, or Notepad++).
- Create a new file named
HelloWorld.java. - Add the following code:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}- Save the file and open a terminal in the same directory.
Compiling and Running Java Code
To compile the program, run:
javac HelloWorld.javaThis generates a HelloWorld.class file. Now, run the program:
java HelloWorldOutput:
Hello, World!Congratulations! You've successfully written and executed your first Java program.