Every Java program follows the same layered structure. Think of it like a set of nesting boxes: the package is the outer container, then the class, then methods, then statements inside methods. Nothing exists outside this hierarchy.
A Java program is like a book: package = the library shelf (organises files). import = the bibliography (other books you reference). class = one book. method = a chapter. statement = a sentence. Every sentence (statement) ends with a full stop (semicolon ;).
Complete Program Anatomy
// β PACKAGE DECLARATION (optional β organises .java files into folders) package com.university.java; // β‘ IMPORT STATEMENTS (bring in classes from other packages) import java.util.Scanner; import java.util.Arrays; // β’ CLASS DECLARATION (required β wraps ALL code) public class MyProgram { // β£ FIELDS / CLASS VARIABLES (optional β data at class level) static int counter = 0; // β€ MAIN METHOD (required entry point β JVM starts here) public static void main(String[] args) { // β₯ LOCAL VARIABLE DECLARATION int age = 20; // β¦ STATEMENTS (instructions β each ends with ;) System.out.println("Hello from MyProgram!"); System.out.println("Age: " + age); } // end main // β§ OTHER METHODS (optional user-defined methods) static void greet() { System.out.println("Hello!"); } } // end class MyProgram
Java Reserved Keywords
Keywords are words that Java has already claimed for its own use. You cannot use these as variable names, class names, or method names. Java has 53 reserved keywords.
* const and goto are reserved but not used in Java. true, false, null are literals, not keywords β but also cannot be used as identifiers.
Tokens and Identifiers
A Java program is made of tokens β the smallest meaningful units the compiler reads. There are 5 types:
| Token Type | Description | Examples |
|---|---|---|
| Keywords | Reserved words with special meaning | public, class, int, if |
| Identifiers | Names you create for variables, classes, methods | age, HelloWorld, calculateSum |
| Literals | Fixed values written directly in code | 42, 3.14, "Hello", true |
| Operators | Symbols that perform operations | +, -, *, /, =, == |
| Separators | Characters that separate tokens | ; , () {} [] . |
ageβ letters onlymyAgeβ camelCase_countβ underscore start$valueβ dollar sign starttotalScore2β digit after startMAX_SIZEβ underscores ok
2ageβ starts with digitmy-nameβ hyphen not allowedmy nameβ space not allowedclassβ reserved keyword@valueβ @ not allowedhello!β ! not allowed
Comments are notes for humans. The Java compiler reads your code and completely ignores every comment. They have no effect on program execution β they exist purely to explain your code to yourself and others.
Comment the WHY, not the WHAT. Don't write // increment i by 1 above i++ β that's obvious. Write why you're incrementing: // move to next student record. Good comments explain reasoning; bad comments repeat what the code already says.
β Single-Line Comment //
Anything after // on the same line is a comment. Use for short explanations on a single line.
// This entire line is a comment β compiler ignores it int age = 20; // inline comment: this variable stores the student's age // Comments can temporarily disable code (useful for debugging): // System.out.println("This line is commented out β won't run"); System.out.println("This line runs"); // active code
β‘ Multi-Line Comment /* */
Everything between /* and */ is a comment, no matter how many lines. Cannot be nested.
/* * This is a multi-line comment. * Useful for longer explanations, * algorithm descriptions, or section headers. * The * at the start of each line is just convention β not required. */ int result = 0; /* You can also write it without the leading stars: This is still a valid multi-line comment. It ends here: */ System.out.println(result);
/* outer /* inner */ still outer? */ β this causes a compile error. The first */ closes the entire comment. If you need to comment out a block that already has /* */ comments, use // on each line or an IDE shortcut (Ctrl+/ in IntelliJ selects multiple lines).
β’ Javadoc Comment /** */
Special comments used to generate official HTML documentation (like the Java API docs you see online). Start with /** (two stars), end with */.
/** * Calculates the area of a rectangle. * This method multiplies length by width to compute the area. * * @param length The length of the rectangle (must be positive) * @param width The width of the rectangle (must be positive) * @return The area of the rectangle as a double * @author Ahmed Ali * @version 1.0 */ public static double rectangleArea(double length, double width) { return length * width; }
| Javadoc Tag | Purpose | Example |
|---|---|---|
@param | Describes a method parameter | @param name The student's full name |
@return | Describes what the method returns | @return The calculated area |
@author | Names the code author | @author Ahmed Ali |
@version | Version of the code | @version 2.0 |
@throws | Documents exceptions thrown | @throws IOException if file not found |
@see | Links to related class/method | @see Math#sqrt(double) |
| Feature | // Single-line | /* */ Multi-line | /** */ Javadoc |
|---|---|---|---|
| Spans multiple lines | β | β | β |
| Generates documentation | β | β | β |
| Best for | Short inline notes | Block explanations | API documentation |
| Can be nested | β (use more //) | β | β |
Java has three print methods. Knowing exactly when to use each is essential β examiners love to ask output prediction questions that depend on the difference between them.
β System.out.println() β Print + New Line
println stands for print line. It prints the given value and then automatically moves the cursor to the next line. Think of it as printing text + pressing Enter.
System.out.println("Hello"); // prints: Helloβ΅ System.out.println("World"); // prints: Worldβ΅ System.out.println(42); // int: 42 System.out.println(3.14); // double: 3.14 System.out.println(true); // boolean: true System.out.println('A'); // char: A System.out.println(2 + 3); // expression: 5 System.out.println(); // empty println β blank line System.out.println("Age: " + 20); // concatenation: Age: 20
World
42
3.14
true
A
5
Age: 20
β‘ System.out.print() β Print, Stay on Same Line
print (no 'ln') prints the value but does NOT add a newline. The cursor stays right after the last printed character. The next print call continues from there.
// Using print β all on same line: System.out.print("A"); System.out.print("B"); System.out.print("C"); // Output: ABC (one line, cursor stays after C) System.out.println(); // manually add newline // Mixing print and println: System.out.print("First "); System.out.print("Second "); System.out.println("Third"); // adds newline System.out.println("Fourth"); // starts on new line // Output: // First Second Third // Fourth
β’ System.out.printf() β Formatted Print
printf gives you precise control over how values are displayed β number of decimal places, column widths, alignment. Think of it as filling in a template with placeholders.
// Syntax: System.out.printf("format string", arg1, arg2, ...); // Each %specifier in the format string is replaced by the next argument System.out.printf("Name: %s%n", "Ahmed"); // Output: Name: Ahmed System.out.printf("Age: %d%n", 20); // Output: Age: 20 System.out.printf("GPA: %.2f%n", 3.75689); // Output: GPA: 3.76 (rounds to 2 decimal places) System.out.printf("%-10s %5d %8.2f%n", "Ahmed", 20, 3.75); // Output: Ahmed 20 3.75 // β left-aligned β right-aligned in 5 chars // Multiple values in one printf: String name = "Sara"; int age = 19; double gpa = 3.9; System.out.printf("Student: %s | Age: %d | GPA: %.1f%n", name, age, gpa); // Output: Student: Sara | Age: 19 | GPA: 3.9
| Method | Adds Newline? | Formatting? | When to Use |
|---|---|---|---|
println() | β Always | Basic | General output, one item per line |
print() | β Never | Basic | When you need items on the same line |
printf() | Only with %n | β Full control | Tables, decimal precision, alignment |
Some characters are impossible to type directly inside a String β like a newline, a tab, or a double quote (since double quotes mark the start/end of the string). Escape sequences are special two-character combinations starting with a backslash \ that represent these characters.
The backslash tells Java to escape (break out of) the normal meaning of the next character. " normally means "end of string". But \" means "literal double quote character inside the string." The backslash changes the character's meaning.
Complete Escape Sequence Table
| Escape | Name | What It Does | Example | Output |
|---|---|---|---|---|
\n | Newline | Moves cursor to start of next line | "Hi\nBye" | Hi Bye |
\t | Horizontal Tab | Inserts a tab space (typically 4-8 spaces) | "A\tB" | A B |
\" | Double Quote | Prints a literal " inside a String | "He said \"Hi\"" | He said "Hi" |
\' | Single Quote | Prints a literal ' inside a char | '\'' | ' |
\\ | Backslash | Prints a literal \ | "C:\\Java" | C:\Java |
\r | Carriage Return | Moves cursor to start of same line | "Hi\rBye" | Bye (overwrites) |
\b | Backspace | Deletes one character before | "Helo\b" | Hel |
\f | Form Feed | New page (printers) β rarely used | β | β |
\uXXXX | Unicode | Any Unicode character by hex code | "\u0041" | A |
Escape Sequence Examples β Full Programs
// \n β newline within a single string System.out.println("Line 1\nLine 2\nLine 3"); // Output: // Line 1 // Line 2 // Line 3 // \t β tab alignment System.out.println("Name\tAge\tCity"); System.out.println("Ahmed\t20\tDubai"); System.out.println("Sara\t19\tAbu Dhabi"); // Output: // Name Age City // Ahmed 20 Dubai // Sara 19 Abu Dhabi // \" β printing double quotes System.out.println("She said \"Java is powerful!\""); // Output: She said "Java is powerful!" // \\ β printing backslash (Windows file path) System.out.println("Path: C:\\Users\\Ahmed\\Desktop"); // Output: Path: C:\Users\Ahmed\Desktop // \u β Unicode character System.out.println("\u0048\u0065\u006C\u006C\u006F"); // Output: Hello (each \uXXXX is one Unicode character) // Combining multiple escapes: System.out.println("Results:\n\tMath:\t95\n\tScience:\t88"); // Output: // Results: // Math: 95 // Science: 88
Format specifiers are placeholders inside a printf format string. They start with % and tell Java what type of value to insert and how to format it.
| Specifier | Type | Example Code | Output |
|---|---|---|---|
%d | Integer (decimal) | printf("%d", 42) | 42 |
%f | Float/Double (6 decimals default) | printf("%f", 3.14) | 3.140000 |
%.2f | Float/Double, 2 decimal places | printf("%.2f", 3.14159) | 3.14 |
%s | String | printf("%s", "Hello") | Hello |
%c | Character | printf("%c", 'A') | A |
%b | Boolean | printf("%b", true) | true |
%n | Platform newline | printf("Hi%n") | Hi + newline |
%o | Integer in octal | printf("%o", 8) | 10 |
%x | Integer in hex (lowercase) | printf("%x", 255) | ff |
%X | Integer in hex (uppercase) | printf("%X", 255) | FF |
%e | Scientific notation | printf("%e", 123456.0) | 1.234560e+05 |
%% | Literal percent sign | printf("100%%") | 100% |
Width and Alignment in printf
// %10d β right-align integer in 10-character-wide field System.out.printf("%10d%n", 42); // Output: " 42" (8 spaces + 42) // %-10d β left-align in 10-character-wide field System.out.printf("%-10d|%n", 42); // Output: "42 |" // Building a formatted table: System.out.printf("%-15s %5s %8s%n", "Name", "Age", "GPA"); System.out.printf("%-15s %5d %8.2f%n", "Ahmed Ali", 20, 3.75); System.out.printf("%-15s %5d %8.2f%n", "Sara Khan", 19, 3.90); System.out.printf("%-15s %5d %8.2f%n", "Omar Salem", 21, 3.55); // Output: // Name Age GPA // Ahmed Ali 20 3.75 // Sara Khan 19 3.90 // Omar Salem 21 3.55
Java is 100% case-sensitive. Uppercase and lowercase letters are completely different characters. This is one of the most common sources of beginner errors.
// Keywords are lowercase β uppercase versions don't exist: public β Public β PUBLIC β class β Class β CLASS β static β Static β STATIC β void β Void β VOID β int β Int β INT β // Class names β MUST match filename exactly: HelloWorld β (file: HelloWorld.java) helloworld β (would need file: helloworld.java) // System.out.println β all three parts case-sensitive: System.out.println() β system.out.println() β (system must be capital S) System.Out.println() β (out must be lowercase) System.out.PrintLn() β (method name must be println) // Variable names β case creates completely different variables: int age = 20; int Age = 25; // different variable! 'age' β 'Age' int AGE = 30; // another different variable!
Java ignores extra whitespace (spaces, tabs, newlines) between tokens. The following two programs are identical to the compiler:
public class A{public static void main(String[] a){System.out.println("Hi");}}
public class A { public static void main(String[] a) { System.out.println("Hi"); } }
Both compile identically. But always write clean code β readability is a professional skill and is sometimes graded in university assignments.
- Indentation: Use 4 spaces (or 1 tab) per nesting level. Be consistent.
- Opening brace: On the same line as the declaration β
class Foo {not on a new line. - One statement per line: Never put two statements on one line (even though it's allowed).
- Blank lines: Separate logical sections with a blank line for readability.
- Naming: Classes β PascalCase. Variables/methods β camelCase. Constants β ALL_CAPS.
- Mixing up print and println β Using
printwhen you need a newline, leading to output piling up on one line unexpectedly. - Forgetting %n in printf β
printfdoes NOT automatically add a newline. Use%nat the end of the format string, or output won't start on a new line. - Typing \ instead of \\ β
"C:\Users"causes an error because\Uis an invalid escape. Must be"C:\\Users". - Wrong quote type for chars β
char c = "A"is wrong (double quotes = String). Must bechar c = 'A'(single quotes). - Using wrong format specifier β
printf("%d", 3.14)causes a runtime exception. Use%ffor floats/doubles,%dfor integers only. - Keyword as variable name β
int class = 5;causes a compile error.classis a keyword. - Missing semicolon after statement β The most common of all. Every statement ends with
;. Comments and class/method declarations do NOT use semicolons.
Before running code, trace through it manually. This skill is tested directly in university exams.
Program 1:
System.out.print("A"); System.out.println("B"); System.out.print("C"); System.out.println("D"); System.out.println("E");
CD
E
Trace: print("A") β A (no newline). println("B") β B then newline. Line 1: AB. print("C") β C (no newline). println("D") β D then newline. Line 2: CD. println("E") β E then newline. Line 3: E.
Program 2:
System.out.printf("%.1f%n", 3.76); System.out.printf("%.0f%n", 3.76); System.out.printf("%5d%n", 42); System.out.printf("%-5d|%n", 42);
4
42
42 |
Trace: %.1f β 1 decimal, rounds 3.76 to 3.8. %.0f β 0 decimals, rounds 3.76 to 4. %5d β right-aligned in 5 chars: " 42". %-5d β left-aligned in 5 chars: "42 " then the pipe.
Program 3:
System.out.println("Hello\tWorld\nJava\tProgramming");
Java Programming
Trace: \t = tab, \n = newline. So: "Hello" + tab + "World" + newline then "Java" + tab + "Programming".
- println vs print: "ln = line = LINE BREAK. print has no ln = no line break."
- printf %n vs \n: Use
%ninside printf (platform-safe). Use\ninside println/print strings. - Escape sequences: "Backslash breaks the spell" β \n = newline, \t = tab, \\ = backslash, \" = quote.
- Case sensitivity rule: "Java sees A and a as strangers β they've never met." Treat every letter's case as significant.
- Semicolons: "Every sentence (statement) needs a full stop (;). Class and method headers are NOT sentences β no semicolon."
- %.2f β "dot 2 = 2 decimal places". %.0f = no decimals. %8.2f = 8-wide, 2 decimals.
Q: What is the difference between System.out.print() and System.out.println()?
Answer: System.out.println() prints the given value and then moves the cursor to the beginning of the next line (adds a newline character at the end). System.out.print() prints the value and leaves the cursor on the same line β no newline is added. The next output from print() or println() will continue from the cursor's current position. Example: two consecutive print("A") and print("B") calls produce AB on one line, while two println() calls produce A and B on separate lines.
Q: What are escape sequences in Java? List any four with examples.
Answer: Escape sequences are special two-character combinations within a String that begin with a backslash (\) and represent characters that cannot be typed directly in code or have special meaning. The backslash "escapes" the normal meaning of the following character.
Four important escape sequences:
\n β Newline: moves cursor to start of next line. Example: println("Hello\nWorld") prints on two lines.
\t β Tab: inserts horizontal tab space. Example: println("Name\tAge") adds tab between words.
\" β Double quote: prints a literal " inside a String. Example: println("She said \"Hi\"") outputs: She said "Hi"
\\ β Backslash: prints a single \. Example: println("C:\\Java") outputs: C:\Java
Q: Write a Java program using printf to print a formatted student report with name, roll number, and GPA β right-aligned in 15, 8, and 6 character columns respectively.
public class StudentReport { public static void main(String[] args) { // Header System.out.printf("%-15s %8s %6s%n", "Name", "Roll No", "GPA"); System.out.printf("%-15s %8s %6s%n", "----------", "-------", "---"); // Data rows System.out.printf("%-15s %8d %6.2f%n", "Ahmed Ali", 2023001, 3.75); System.out.printf("%-15s %8d %6.2f%n", "Sara Khan", 2023002, 3.90); System.out.printf("%-15s %8d %6.2f%n", "Omar Salem", 2023003, 3.55); } }
MCQ Bank
System.out.print("A"); System.out.println("B"); System.out.print("C");\\ produce inside a String?\\ is the escape sequence for a literal backslash. The first \ tells Java "escape the next character". The second \ is the character being escaped. Result: one printed backslash. So "C:\\Java" prints C:\Java.System.out.printf("%.2f", 3.14567);%.2f formats a float/double to exactly 2 decimal places with rounding. 3.14567 rounded to 2 decimals: the third decimal is 5, so the second decimal rounds up from 4 to 5. Result: 3.15._myVar$amount2countmyVar22count is invalid because identifiers cannot start with a digit. They can start with a letter, underscore (_), or dollar sign ($). A digit can appear AFTER the first character (e.g., count2 is valid)./** */)?javadoc tool to automatically generate HTML API documentation β like the official Java docs at docs.oracle.com. They support special tags like @param, @return, @author to structure the documentation.// single-line, /* */ multi-line (not nestable), /** */ Javadoc (generates HTML documentation).println() = print + newline. print() = print only, no newline. printf() = formatted, newline only with %n.\n newline, \t tab, \" double quote, \\ backslash, \uXXXX unicode.%d int, %f float, %.2f 2 decimals, %s string, %c char, %% literal percent.System β system. main β Main. int β Int.Easy
print() (no println) that produces output on exactly 4 separate lines. Hint: you'll need \n escape sequences.\n, \t, \", \\. Show clearly what each one produces in the output.C:\Program Files\Java\jdk-17\bin\javac.exe. Count carefully β how many backslashes do you need in the code?Teacher: "What is Java?"
Student: "Java is 'awesome'!"
class, myClass, static, Static, int, integer, void, Void, true, isTrue_test, 2value, my-name, $price, for, goto, MAX SIZE, camelCaseMedium
System.out.Println("Hello\World"); System.Out.print("Tab:\there"); system.out.printf("%.d", 3.14);Hard
Line "one"
Tabβhere
Path: C:\test\run
Done!Test your real mastery of Java syntax.
- No-IDE test: Without autocomplete, write from memory a complete Java program with correct package declaration, import, class, Javadoc comment, and main method. No errors allowed.
- Escape puzzle: What does this print β trace it completely before running:
System.out.println("\\n is a \\\"newline\\\"\\ttab is \\t"); - printf challenge: Print a multiplication table from 1Γ1 to 5Γ5 using ONLY printf β all values right-aligned in a 4-character-wide column. No println allowed.
- Research: What is
System.out.format()? How is it different from (or the same as)printf()? Test it.