Java Notes
Write, compile, and run your first Java program — a detailed walkthrough of Hello World, explaining every line, common errors beginners face, and how to progress beyond the basics.
Every programmer's journey starts with "Hello, World!" — but we'll go far beyond just printing a line. This lesson will help you write, understand, compile, and run your first Java programs while explaining every single element.
The Classic Hello World
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}Hello, World!
This simple program has more going on than you might think. Let's dissect every single token.
Line-by-Line Breakdown
Line 1: public class HelloWorld {
public // Access modifier: visible from anywhere
class // Keyword: declares a class (blueprint for objects)
HelloWorld // Class name: MUST match the filename (HelloWorld.java)
{ // Opening brace: starts the class bodyRules for the class declaration:
- Class name starts with an uppercase letter (convention)
- Uses PascalCase (each word capitalized)
- File must be named
HelloWorld.java(exact match, case-sensitive) publicmeans any other class can see this class
Line 2: public static void main(String[] args) {
This is the entry point — where the JVM starts executing your program:
public // JVM must access this from outside the class
static // Can be called without creating an object
void // This method returns nothing
main // The exact name JVM looks for (case-sensitive)
(String[] args) // Array of command-line arguments
{ // Method body startsWhy each keyword is necessary:
public— JVM calls this from outside, so it must be accessiblestatic— JVM hasn't created any objects yet, so it can't call instance methodsvoid— the program doesn't "return" a value to the OS (in Java)main— this specific name is hardcoded in the JVM specificationString[] args— allows passing data from command line
Line 3: System.out.println("Hello, World!");
System // Class from java.lang package (auto-imported)
.out // Static field of System: the standard output stream (PrintStream)
.println // Method of PrintStream: prints text + newline
("Hello, World!") // The String argument to print
; // Statement terminator (required in Java!)Line 4-5: Closing braces
} // Closes the main method
} // Closes the HelloWorld classStep-by-Step: Write, Compile, Run
Step 1: Write the Code
Save the following in a file named exactly HelloWorld.java:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}Step 2: Compile
Open terminal/command prompt in the same directory:
If successful, this creates HelloWorld.class (no output means success).
Step 3: Run
Note: Use the class name (no .class extension, no .java extension).
Hello, World!
Going Beyond Hello World
Program 2: Working with Variables
public class PersonalGreeting {
public static void main(String[] args) {
// Declare and initialize variables
String name = "Alice";
int age = 25;
double height = 5.6;
boolean isStudent = true;
// Print information
System.out.println("=== Personal Information ===");
System.out.println("Name: " + name);
System.out.println("Age: " + age + " years");
System.out.println("Height: " + height + " feet");
System.out.println("Student: " + isStudent);
// Simple calculation
int birthYear = 2024 - age;
System.out.println("Birth year: ~" + birthYear);
}
}=== Personal Information === Name: Alice Age: 25 years Height: 5.6 feet Student: true Birth year: ~1999
Program 3: User Input
import java.util.Scanner; // Import Scanner class
public class UserInput {
public static void main(String[] args) {
// Create Scanner object to read input
Scanner scanner = new Scanner(System.in);
// Prompt and read input
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.print("Enter your age: ");
int age = scanner.nextInt();
// Process and display
System.out.println("\nHello, " + name + "!");
System.out.println("In 10 years, you'll be " + (age + 10) + " years old.");
// Close scanner (good practice)
scanner.close();
}
}Enter your name: John Enter your age: 28 Hello, John! In 10 years, you'll be 38 years old.
Program 4: Simple Calculator
=== Simple Calculator === Enter first number: 15.5 Enter operator (+, -, *, /): * Enter second number: 3.2 15.50 * 3.20 = 49.60
Program 5: Loops and Patterns
Right Triangle:
*
* *
* * *
* * * *
* * * * *
Number Pyramid:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5 Program 6: Methods and Organization
public class TemperatureConverter {
// Method to convert Celsius to Fahrenheit
public static double celsiusToFahrenheit(double celsius) {
return (celsius * 9.0 / 5.0) + 32;
}
// Method to convert Fahrenheit to Celsius
public static double fahrenheitToCelsius(double fahrenheit) {
return (fahrenheit - 32) * 5.0 / 9.0;
}
// Method to print a conversion table
public static void printConversionTable() {
System.out.println("╔════════════╦════════════╗");
System.out.println("║ Celsius ║ Fahrenheit ║");
System.out.println("╠════════════╬════════════╣");
for (int c = 0; c <= 100; c += 10) {
double f = celsiusToFahrenheit(c);
System.out.printf("║ %5.1f°C ║ %5.1f°F ║%n", (double)c, f);
}
System.out.println("╚════════════╩════════════╝");
}
public static void main(String[] args) {
// Single conversions
double boilingF = celsiusToFahrenheit(100);
double freezingC = fahrenheitToCelsius(32);
System.out.println("Water boils at: " + boilingF + "°F");
System.out.println("Water freezes at: " + freezingC + "°C");
System.out.println();
// Print table
printConversionTable();
}
}Water boils at: 212.0°F Water freezes at: 0.0°C ╔════════════╦════════════╗ ║ Celsius ║ Fahrenheit ║ ╠════════════╬════════════╣ ║ 0.0°C ║ 32.0°F ║ ║ 10.0°C ║ 50.0°F ║ ║ 20.0°C ║ 68.0°F ║ ║ 30.0°C ║ 86.0°F ║ ║ 40.0°C ║ 104.0°F ║ ║ 50.0°C ║ 122.0°F ║ ║ 60.0°C ║ 140.0°F ║ ║ 70.0°C ║ 158.0°F ║ ║ 80.0°C ║ 176.0°F ║ ║ 90.0°C ║ 194.0°F ║ ║ 100.0°C ║ 212.0°F ║ ╚════════════╩════════════╝
Common Beginner Errors and How to Fix Them
Error 1: File name doesn't match class name
// File saved as: hello.java (lowercase 'h')
public class Hello { // ERROR: class is 'Hello' but file is 'hello.java'
public static void main(String[] args) {
System.out.println("This won't compile!");
}
}error: class Hello is public, should be declared in a file named Hello.java
Fix: Rename file to Hello.java (exact case match).
Error 2: Missing semicolons
public class MissingSemicolon {
public static void main(String[] args) {
System.out.println("Hello") // ERROR: missing ;
System.out.println("World");
}
}error: ';' expected
System.out.println("Hello")
^Error 3: Wrong case for keywords
public class WrongCase {
// ERROR: 'String' not 'string', 'System' not 'system'
public static void main(string[] args) { // wrong!
system.out.println("Hello"); // wrong!
}
}error: cannot find symbol
public static void main(string[] args) {
^
symbol: class stringFix: Java is case-sensitive. Use String, System, int (all exact).
Error 4: Using println vs print
public class PrintDifference {
public static void main(String[] args) {
// println adds a newline at the end
System.out.println("Line 1");
System.out.println("Line 2");
System.out.println(); // just a blank line
// print does NOT add a newline
System.out.print("Same ");
System.out.print("line ");
System.out.print("output");
System.out.println(); // manually add newline
// printf for formatted output
System.out.printf("Name: %s, Age: %d, GPA: %.2f%n", "Alice", 20, 3.85);
}
}Line 1 Line 2 Same line output Name: Alice, Age: 20, GPA: 3.85
Error 5: Running with .class extension
$ java HelloWorld.class ← WRONG
Error: Could not find or load main class HelloWorld.class
$ java HelloWorld.java ← WRONG (unless Java 11+ single-file)
Error: Could not find or load main class HelloWorld.java
$ java HelloWorld ← CORRECT
Hello, World!Using Command Line Arguments
// Run: java CommandLineArgs Alice 25 Number of arguments: 2 args[0] = Alice args[1] = 25 Hello Alice, you are 25 years old!
Understanding Output Methods
Language: Java, Version: 21 Pi is approximately 3.14 Java | 21 | 3.142 Using Java version 21 === Format Specifiers === %d → integer: 42 %f → float: 3.140000 %.2f → 2 decimals: 3.14 %s → string: Hi %c → char: A %b → boolean: true %10d → right-aligned: [ 42] %-10d → left-aligned: [42 ]
Common Mistakes
- Forgetting that Java is case-sensitive —
Mainis notmain,stringis notString,systemis notSystem. - Not saving the file with
.javaextension — some text editors add.txtautomatically. Make sure it'sHelloWorld.java, notHelloWorld.java.txt. - Using an old terminal directory — your terminal must be in the same directory as the
.javafile (or use full paths). - Confusing
printwithprintln—printstays on the same line,printlnmoves to the next line. - Missing the
mainmethod signature — even one wrong word (Publicinstead ofpublic,void Maininstead ofvoid main) means the JVM can't find the entry point. - Using smart/curly quotes — word processors use "Hello" (curly quotes). Java needs "Hello" (straight quotes). Always use a code editor.
Best Practices for Beginners
- Use a proper code editor — VS Code, IntelliJ IDEA Community, or Eclipse (not Notepad or Word)
- Save frequently and compile often — don't write 50 lines then compile; build incrementally
- Read error messages from top to bottom — fix the first error first; later ones may be cascading
- Type the code yourself — don't copy-paste when learning; muscle memory matters
- Experiment — change values, break things on purpose, see what happens
- Use meaningful names —
StudentGradenotsg,calculateTotalnotct
Interview Questions
Q1: Explain every keyword in public static void main(String[] args).
Answer: public — access modifier allowing JVM to call this method from outside the class. static — belongs to the class itself, so JVM can call it without creating an object. void — the method doesn't return any value. main — the specific method name the JVM is programmed to look for as the entry point. String[] args — parameter to receive command-line arguments as an array of Strings.
Q2: What happens if you write static public void main instead of public static void main?
Answer: It works perfectly! The order of access modifiers (public) and non-access modifiers (static) doesn't matter in Java. Both public static void main and static public void main are valid. However, the convention is public static void main.
Q3: Can a Java program have multiple classes? Multiple main methods?
Answer: Yes to both. A .java file can contain multiple classes (only one public). Each class can have its own main method. When you run java ClassName, the JVM executes the main method of that specific class. This is useful for testing individual classes.
Q4: What is the difference between System.out.println() and System.out.print()?
Answer: println() prints the argument followed by a newline character (cursor moves to next line). print() prints the argument without a newline (cursor stays on the same line). println() with no argument just prints a blank line.
Q5: Why does the file name need to match the public class name?
Answer: This is a Java language rule that enables the compiler and ClassLoader to locate class files predictably. When code references com.example.MyClass, the JVM knows to look for com/example/MyClass.class. This one-to-one mapping between public class names and files is fundamental to Java's class-loading mechanism.
Summary
Your first Java program teaches fundamental concepts: class structure, the main method entry point, and output statements. Every element has a purpose — from public (accessibility) to static (no object needed) to String[] args (command-line input). As you progress, remember: Java demands precision (case-sensitivity, semicolons, matching braces), but this strictness is what makes Java programs reliable. Practice by writing, breaking, and fixing programs — that's how you truly learn.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Your First Java Program.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, fundamentals, introduction, first
Related Java Master Course Topics