Java Programming Basics: A Beginner's Guide
Java is one of the most widely used programming languages in the world, powering everything from Android apps to enterprise backend systems. If you are just getting started, this post walks through the fundamentals you need to write your first programs.
1. Your First Program
Every Java program starts with a class and a main method, which is the entry point the JVM runs first:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Save this as HelloWorld.java, compile it with javac HelloWorld.java, then run it with java HelloWorld.
2. Variables and Data Types
Java is statically typed, meaning every variable must be declared with a type:
int age = 25;
double price = 19.99;
char grade = 'A';
boolean isActive = true;
String name = "Alex";
The primitive types you'll use most often are int, double, boolean, and char. String is technically an object, not a primitive, but you'll use it constantly.
3. Control Flow
Java supports the usual conditionals and loops:
if (age >= 18) {
System.out.println("Adult");
} else {
System.out.println("Minor");
}
for (int i = 0; i < 5; i++) {
System.out.println("Count: " + i);
}
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
4. Methods
Methods let you organize and reuse logic:
public static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int result = add(3, 4);
System.out.println(result); // 7
}
5. Classes and Objects
Java is object-oriented, so most real programs are built from classes that model data and behavior:
public class Car {
String model;
int year;
public Car(String model, int year) {
this.model = model;
this.year = year;
}
public void describe() {
System.out.println(year + " " + model);
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car("Toyota Corolla", 2024);
myCar.describe(); // 2024 Toyota Corolla
}
}
6. Arrays and Collections
Arrays hold a fixed number of elements of the same type:
int[] numbers = {1, 2, 3, 4, 5};
for (int n : numbers) {
System.out.println(n);
}
For dynamic-sized collections, Java's standard library provides classes like ArrayList:
import java.util.ArrayList;
ArrayList<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
System.out.println(names.get(0)); // Alice
Where to Go Next
Once these basics feel comfortable, the natural next steps are exploring exceptions, interfaces, generics, and the collections framework in more depth. Writing small practice programs, like a calculator or a to-do list manager, is one of the fastest ways to make these concepts stick.
