Your First Java Program: "Hello, World!"
Let's start with the traditional first program. It simply prints the text "Hello, World!" to the screen. This simple program introduces the basic structure and syntax of Java.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Let's Break It Down:
- public class HelloWorld { ... }: Every Java application must have at least one class. A class is like a blueprint for creating objects. We named our class
HelloWorld. The file must be saved asHelloWorld.java. - public static void main(String[] args) { ... }: This is the main method. It's the entry point of any Java application. When you run the program, the code inside this method is the first to be executed.
- System.out.println("Hello, World!");: This line prints the text inside the quotes to the console.
System.outis a standard output object, andprintlnis the method that prints a line of text.
Don't worry if you don't understand everything yet. We will cover each of these concepts in detail throughout this chapter.
Core Rules of Java Syntax
Java has a few fundamental rules you must follow. Think of them as the grammar rules of the language.
- Case Sensitivity: Java is case-sensitive, meaning it can tell the difference between uppercase and lowercase letters.
myVariableis not the same asMyVariable. - Class Names: By convention, class names should start with an uppercase letter. If the name has multiple words, use "PascalCase" (e.g.,
MyFirstJavaClass). - Method Names: Method names should start with a lowercase letter. If multiple words are used, follow "camelCase" (e.g.,
myFirstMethodName). - Source File Name: The name of the source file must exactly match the public class name, with a
.javaextension. For our example, the class isHelloWorld, so the file must beHelloWorld.java. - Statements and Semicolons: Every individual statement (a complete command) must end with a semicolon (
;). - Code Blocks: Code is grouped into blocks using curly braces
{ ... }. This is used for classes, methods, loops, and more.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, Java!");
}
}
Naming Things in Java
An identifier is simply a name you give to a class, variable, or method. For example, in int age = 30;, the identifier is age.
Rules for Naming:
- Can start with a letter (a-z, A-Z), an underscore (
_), or a dollar sign ($). - After the first character, it can have letters, digits (0-9), underscores, or dollar signs.
- There is no limit on the number of characters.
- Most importantly, you cannot use a Java keyword (like
class,public, orint) as an identifier.
Examples:
// Valid identifiers
int age = 25;
String studentName = "Alex";
double _salary = 50000.50;
int $value = 100;
// Invalid identifiers
// int 1stPlace = 1; // Cannot start with a digit
// int class = 10; // 'class' is a reserved keyword
Changing Access and Behavior
Modifiers are keywords that you add to change the meaning of a class, method, or variable. They are divided into two categories:
1. Access Control Modifiers
These control who can access the code. Think of them like setting permissions on a file.
- public: Accessible from any other class. It's completely open.
- private: Accessible only within the same class where it is declared. It's completely hidden.
- protected: Accessible within the same class, its subclasses (inheritance), and classes in the same package.
- (Default): If no modifier is used, it's accessible only to classes in the same package.
2. Non-Access Modifiers
These change the behavior of classes, methods, and variables.
- static: Means the member (variable or method) belongs to the class itself, not to an instance of the class. You can call a static method on the class directly (e.g.,
Math.sqrt(9)) without creating an object. - final: A final variable is a constant (its value cannot be changed). A final method cannot be overridden by a subclass. A final class cannot be subclassed.
- abstract: An abstract class cannot be used to create objects. It's designed to be subclassed. An abstract method has no body and must be implemented by the subclass.
public class Config {
public static final int VERSION = 1; // constant
private String secret = "hidden"; // private field
}
Containers for Your Data
A variable is a container that holds a piece of data. Before you use a variable, you must declare it by telling Java its data type and its name.
Types of Variables in Java
- Local Variables: Declared inside a method. They are created when the method is called and destroyed when the method finishes. They can only be used within that method.
- Instance Variables: Declared inside a class but outside any method. They belong to an instance (object) of the class. Each object gets its own copy of these variables.
- Class/Static Variables: Declared with the
statickeyword inside a class. They belong to the class itself, not to any specific object. All objects of the class share the same static variable.
int age = 30; // integer primitive
double salary = 3000.50; // double primitive
String name = "Asha"; // reference type (Object)
public class Car {
// Instance variable: each car object will have its own color.
String color;
// Class/Static variable: all cars share the same number of wheels.
static int numberOfWheels = 4;
public void displayInfo() {
// Local variable: this variable only exists inside this method.
String message = "This car is " + color;
System.out.println(message);
System.out.println("All cars have " + numberOfWheels + " wheels.");
}
}
Defining a Fixed Set of Constants
An Enum (short for enumeration) is a special class that represents a group of constants. It's perfect for things that have a fixed, limited set of options, like days of the week, planets in the solar system, or directions.
Using an enum makes your code more readable and less error-prone than using simple strings or integers.
// Defining an enum for days of the week
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
// How to use the enum
public class EnumTest {
Day day;
public EnumTest(Day day) {
this.day = day;
}
public void tellItLikeItIs() {
switch (day) {
case MONDAY:
System.out.println("Mondays are bad.");
break;
case FRIDAY:
System.out.println("Fridays are better.");
break;
case SATURDAY: case SUNDAY:
System.out.println("Weekends are the best!");
break;
default:
System.out.println("Midweek days are so-so.");
break;
}
}
}
Reserved Words in Java
Keywords are special words that are reserved by the Java language itself. You cannot use them as identifiers (names for your variables, classes, etc.). Each keyword has a specific, predefined meaning.
Note: Keywords are all written in lowercase.
| Category | Purpose | Examples |
|---|---|---|
| Declarations | Define classes, packages, and type relationships | class, interface, enum, package, import, extends, implements |
| Modifiers | Control access & behavior of classes/members | public, private, protected, static, final, abstract |
| Control Flow | Branching and looping | if, else, switch, for, while, break, continue |
| Primitive & Type | Basic type keywords | byte, short, int, long, float, double, boolean, char, void |
| Other / Exceptions / Concurrency | Exception handling and concurrency keywords | try, catch, finally, throw, throws, synchronized, volatile |
Tip for Beginners: When starting, focus on learning class, public, static, void, if, for, and the basic types (int, double, boolean). You'll encounter the others as you learn more advanced topics.
Using Blank Lines for Readability
Blank lines are lines that contain only whitespace (spaces or tabs). The Java compiler completely ignores them. Their only purpose is to improve the readability and organization of your source code.
Using blank lines to separate logical sections of code is a very good programming practice.
public class BlankLineExample {
// Declare instance variables at the top
private int id;
private String name;
// Use a blank line to separate variables from methods
public BlankLineExample(int id, String name) {
this.id = id;
this.name = name;
}
// Use a blank line to separate methods
public void printDetails() {
System.out.println("ID: " + this.id);
System.out.println("Name: " + this.name);
}
}
Good use of blank lines makes your code look cleaner and easier to navigate, but it has no effect on how the program runs.
Reusing Code with Inheritance
Inheritance is a powerful feature where a new class (the subclass or child class) is based on an existing class (the superclass or parent class). The child class inherits (gets) all the fields and methods from the parent class.
This allows you to reuse code and create a logical hierarchy. Think of it like this: a Car *is a type of* Vehicle. So, Car can be a child of the Vehicle class.
We use the extends keyword to create a subclass.
// The parent class (Superclass)
class Vehicle {
protected String brand = "Ford";
public void honk() {
System.out.println("Tuut, tuut!");
}
}
// The child class (Subclass)
class Car extends Vehicle {
private String modelName = "Mustang";
public static void main(String[] args) {
Car myCar = new Car();
// Call the method from the Vehicle class
myCar.honk();
// Display the field from the Vehicle class
System.out.println(myCar.brand + " " + myCar.modelName);
}
}
Defining a Contract with Interfaces
An interface is a completely "abstract class" that is used to group related methods with empty bodies. Think of an interface as a contract. It specifies *what* a class can do, but not *how* it does it.
Any class that "implements" an interface agrees to provide a body for all the methods defined in that interface. This is a great way to achieve abstraction and multiple inheritance-like behavior.
// 1. The interface (the "contract")
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}
// 2. A class that "implements" the interface
class Pig implements Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: oink oink");
}
public void sleep() {
// The body of sleep() is provided here
System.out.println("Zzz");
}
}
// 3. Main class to test it
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
Explaining Your Code
Comments are notes in your code that are ignored by the Java compiler. They are meant for humans to read. Good comments explain *why* something is done, not just *what* is done. They are essential for making your code understandable to others (and to your future self!).
Java supports three types of comments: