Chapter 03 of 21
Chapter 03 β€” Phase 1: Fundamentals
Java Syntax Basics
The grammar of Java. Structure, comments, printing, escape sequences, and format specifiers β€” the foundation every other chapter builds on. Master these and the rest of Java becomes much easier.
~40 min read
6 Core Topics
5 MCQs
20 Practice Problems
πŸ›οΈ
3.1 β€” ArchitectureStructure of a Java Program

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.

Analogy β€” A Book

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

Complete Java Program β€” All Layers Labelled
// β‘  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
NESTING STRUCTURE (outer to inner): β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ Package declaration β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ β”‚ Import statements β”‚ β”‚ β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ β”‚ β”‚ β”‚ Class body β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ Method body β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ Statements; β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ Rule: CODE ONLY EXISTS INSIDE A CLASS. Rule: EXECUTABLE CODE ONLY EXISTS INSIDE A METHOD. Rule: EVERY STATEMENT ENDS WITH A SEMICOLON.

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.

abstract
assert
boolean
break
byte
case
catch
char
class
const*
continue
default
do
double
else
enum
extends
final
finally
float
for
goto*
if
implements
import
instanceof
int
interface
long
native
new
package
private
protected
public
return
short
static
strictfp
super
switch
synchronized
this
throw
throws
transient
try
void
volatile
while
true
false
null

* 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 TypeDescriptionExamples
KeywordsReserved words with special meaningpublic, class, int, if
IdentifiersNames you create for variables, classes, methodsage, HelloWorld, calculateSum
LiteralsFixed values written directly in code42, 3.14, "Hello", true
OperatorsSymbols that perform operations+, -, *, /, =, ==
SeparatorsCharacters that separate tokens; , () {} [] .
Identifier Rules
Valid Identifiers βœ“
  • age β€” letters only
  • myAge β€” camelCase
  • _count β€” underscore start
  • $value β€” dollar sign start
  • totalScore2 β€” digit after start
  • MAX_SIZE β€” underscores ok
Invalid Identifiers βœ—
  • 2age β€” starts with digit
  • my-name β€” hyphen not allowed
  • my name β€” space not allowed
  • class β€” reserved keyword
  • @value β€” @ not allowed
  • hello! β€” ! not allowed
πŸ’¬
3.2 β€” CommentsThree Types of Comments

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.

When to Write Comments

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.

Single-Line Comments
// 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.

Multi-Line Comments
/*
 * 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);
Multi-Line Comment Cannot Be Nested

/* 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 */.

Javadoc Comments β€” Professional Documentation
/**
 * 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 TagPurposeExample
@paramDescribes a method parameter@param name The student's full name
@returnDescribes what the method returns@return The calculated area
@authorNames the code author@author Ahmed Ali
@versionVersion of the code@version 2.0
@throwsDocuments exceptions thrown@throws IOException if file not found
@seeLinks to related class/method@see Math#sqrt(double)
Feature// Single-line/* */ Multi-line/** */ Javadoc
Spans multiple linesβœ—βœ“βœ“
Generates documentationβœ—βœ—βœ“
Best forShort inline notesBlock explanationsAPI documentation
Can be nestedβœ“ (use more //)βœ—βœ—
πŸ–¨οΈ
3.3 β€” OutputPrinting to the Console

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.

println β€” Examples
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
Output
Hello
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.

print vs println β€” Side by Side
// 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.

printf β€” Format String + Arguments
// 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
println vs print vs printf β€” At a Glance
MethodAdds Newline?Formatting?When to Use
println()βœ“ AlwaysBasicGeneral output, one item per line
print()βœ— NeverBasicWhen you need items on the same line
printf()Only with %nβœ“ Full controlTables, decimal precision, alignment
πŸ”€
3.4 β€” Special CharactersEscape Sequences

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.

Why "Escape"?

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

EscapeNameWhat It DoesExampleOutput
\nNewlineMoves cursor to start of next line"Hi\nBye"Hi
Bye
\tHorizontal TabInserts a tab space (typically 4-8 spaces)"A\tB"A    B
\"Double QuotePrints a literal " inside a String"He said \"Hi\""He said "Hi"
\'Single QuotePrints a literal ' inside a char'\'''
\\BackslashPrints a literal \"C:\\Java"C:\Java
\rCarriage ReturnMoves cursor to start of same line"Hi\rBye"Bye (overwrites)
\bBackspaceDeletes one character before"Helo\b"Hel
\fForm FeedNew page (printers) β€” rarely usedβ€”β€”
\uXXXXUnicodeAny Unicode character by hex code"\u0041"A

Escape Sequence Examples β€” Full Programs

Escape Sequences in Action
// \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
πŸ“
3.5 β€” printfFormat Specifiers β€” Complete Guide

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.

SpecifierTypeExample CodeOutput
%dInteger (decimal)printf("%d", 42)42
%fFloat/Double (6 decimals default)printf("%f", 3.14)3.140000
%.2fFloat/Double, 2 decimal placesprintf("%.2f", 3.14159)3.14
%sStringprintf("%s", "Hello")Hello
%cCharacterprintf("%c", 'A')A
%bBooleanprintf("%b", true)true
%nPlatform newlineprintf("Hi%n")Hi + newline
%oInteger in octalprintf("%o", 8)10
%xInteger in hex (lowercase)printf("%x", 255)ff
%XInteger in hex (uppercase)printf("%X", 255)FF
%eScientific notationprintf("%e", 123456.0)1.234560e+05
%%Literal percent signprintf("100%%")100%

Width and Alignment in printf

Width, Precision, Alignment
// %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
πŸ”‘
3.6 β€” RulesCase Sensitivity in Java

Java is 100% case-sensitive. Uppercase and lowercase letters are completely different characters. This is one of the most common sources of beginner errors.

Case Sensitivity β€” Every Example
// 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!
πŸ“
3.7 β€” StyleWhitespace, Indentation & Code Style

Java ignores extra whitespace (spaces, tabs, newlines) between tokens. The following two programs are identical to the compiler:

Ugly but valid βœ“
public class A{public static void main(String[] a){System.out.println("Hi");}}
Clean and readable βœ“
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.

Java Code Style Conventions
  • 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.
🚫
3.8 β€” Watch OutMost Common Syntax Mistakes
Top Syntax Mistakes β€” Chapter 3
  1. Mixing up print and println β€” Using print when you need a newline, leading to output piling up on one line unexpectedly.
  2. Forgetting %n in printf β€” printf does NOT automatically add a newline. Use %n at the end of the format string, or output won't start on a new line.
  3. Typing \ instead of \\ β€” "C:\Users" causes an error because \U is an invalid escape. Must be "C:\\Users".
  4. Wrong quote type for chars β€” char c = "A" is wrong (double quotes = String). Must be char c = 'A' (single quotes).
  5. Using wrong format specifier β€” printf("%d", 3.14) causes a runtime exception. Use %f for floats/doubles, %d for integers only.
  6. Keyword as variable name β€” int class = 5; causes a compile error. class is a keyword.
  7. Missing semicolon after statement β€” The most common of all. Every statement ends with ;. Comments and class/method declarations do NOT use semicolons.
πŸ”
3.9 β€” TraceDry Run β€” Output Prediction

Before running code, trace through it manually. This skill is tested directly in university exams.

Trace These β€” Predict Before Revealing

Program 1:

Predict Output
System.out.print("A");
System.out.println("B");
System.out.print("C");
System.out.println("D");
System.out.println("E");
AB
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:

Predict Output
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);
3.8
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:

Predict Output
System.out.println("Hello\tWorld\nJava\tProgramming");
Hello    World
Java    Programming

Trace: \t = tab, \n = newline. So: "Hello" + tab + "World" + newline then "Java" + tab + "Programming".
Memory Tips β€” Chapter 3
  • println vs print: "ln = line = LINE BREAK. print has no ln = no line break."
  • printf %n vs \n: Use %n inside printf (platform-safe). Use \n inside 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.
πŸ“
3.10 β€” ExamUniversity Exam Preparation
2 Marks β€” Short Answer

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.

3 Marks β€” Explain with Example

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

4 Marks β€” Code + Output

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.

Model Answer
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

Q1.What is the output of: System.out.print("A"); System.out.println("B"); System.out.print("C");
AA B C (each on new line)
BAB on line 1, then C on same line (no trailing newline)
CABC all on one line
DA on line 1, BC on line 2
βœ“ print("A") β†’ A (no newline, cursor stays). println("B") β†’ B then newline. So first visible line = "AB". print("C") β†’ C (no newline, cursor stays after C). Output: line 1 = AB, then C without a newline at end.
Q2.What does the escape sequence \\ produce inside a String?
ATwo backslashes \\
BA single backslash \
CA newline character
DAn empty 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.
Q3.What is the output of: System.out.printf("%.2f", 3.14567);
A3.14567
B3.14
C3.15
D3.1
βœ“ %.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.
Q4.Which of the following is NOT a valid Java identifier?
A_myVar
B$amount
C2count
DmyVar2
βœ“ 2count 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).
Q5.What is the purpose of Javadoc comments (/** */)?
AThey are faster to write than // comments
BThey can span multiple lines unlike // comments
CThey can be processed by the javadoc tool to generate HTML documentation
DThey are executed by the JVM as special instructions
βœ“ Javadoc comments (/** */) are read by the 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.
Quick Revision β€” Chapter 3
Java program structure: package β†’ imports β†’ class β†’ fields β†’ main method β†’ statements. All code inside a class. All executable code inside methods.
Tokens: keywords, identifiers, literals, operators, separators. Identifiers can start with letter, _, or $ β€” not digits. Cannot use keywords as names.
Three comment types: // single-line, /* */ multi-line (not nestable), /** */ Javadoc (generates HTML documentation).
println() = print + newline. print() = print only, no newline. printf() = formatted, newline only with %n.
Key escape sequences: \n newline, \t tab, \" double quote, \\ backslash, \uXXXX unicode.
printf specifiers: %d int, %f float, %.2f 2 decimals, %s string, %c char, %% literal percent.
Java is 100% case-sensitive. System β‰  system. main β‰  Main. int β‰  Int.
Whitespace is ignored by compiler. But always write properly indented, readable code.
Semicolons end statements. Class/method headers and comments do NOT get semicolons.
πŸ’ͺ
3.11 β€” PracticePractice Problems

Easy

P3.1
Comment Every Line
Take the HelloWorld program and add a meaningful comment above EVERY line explaining what it does and why. Practice all three comment styles.
Easy
P3.2
print vs println Race
Write a program using ONLY print() (no println) that produces output on exactly 4 separate lines. Hint: you'll need \n escape sequences.
Easy
P3.3
Escape Sequence Gallery
Write one println statement per escape sequence demonstrating: \n, \t, \", \\. Show clearly what each one produces in the output.
Easy
P3.4
Windows Path Printer
Print this exact path: C:\Program Files\Java\jdk-17\bin\javac.exe. Count carefully β€” how many backslashes do you need in the code?
Easy
P3.5
Quoted Dialogue
Print this exact dialogue (with all punctuation):
Teacher: "What is Java?"
Student: "Java is 'awesome'!"
Easy
P3.6
Spot the Keyword
From this list, identify which are Java keywords and which are valid identifiers: class, myClass, static, Static, int, integer, void, Void, true, isTrue
Easy
P3.7
Invalid Identifier Hunt
Write down which of these are invalid and why: _test, 2value, my-name, $price, for, goto, MAX SIZE, camelCase
Easy
P3.8
printf Basic
Use printf to print your name (string), age (integer), and GPA (float to 2 decimals) in one formatted line using %s, %d, %.2f.
Easy

Medium

P3.9
Formatted Grade Card
Use printf to print a student grade card with 4 subjects. Each row: subject name (left-aligned, 15 chars), marks (right-aligned, 5 chars), grade (3 chars). Add a header row and separator line.
Medium
P3.10
Output Prediction Sheet
Without running, predict the exact output of 5 given code snippets mixing print, println, printf, and escape sequences. Then verify each one. Document every prediction that was wrong and explain why.
MediumPredict
P3.11
Javadoc Practice
Write a class with 3 static methods (add, subtract, multiply). Write complete Javadoc for each: @param for each parameter, @return, and a description. Then run javadoc to generate the HTML docs.
Medium
P3.12
Bug Collector
Find and fix all errors: System.out.Println("Hello\World"); System.Out.print("Tab:\there"); system.out.printf("%.d", 3.14);
MediumDebug
P3.13
Receipt Printer
Print a shopping receipt using printf: item name (left-aligned 20 chars), quantity (5 chars), unit price (8.2f), total (8.2f). Include header, 3 items, and a total row. All columns aligned perfectly.
Medium
P3.14
Unicode Art
Research Unicode character codes for: stars (β˜… = \u2605), arrows (β†’ = \u2192), checkmarks (βœ“ = \u2713), hearts (β™₯ = \u2665). Use them to print a decorative information card using println.
Medium

Hard

P3.15
Single-Statement Multi-line
Using ONE System.out.println() statement, reproduce this exact output (7 lines, tabs for alignment): a formatted ASCII table with borders made of ─, β”‚, β”Œ, ┐, β””, β”˜ unicode characters.
Hard
P3.16
Precision Rounding Experiment
Predict then verify: what does printf produce for %.0f with 0.5, 1.5, 2.5, 3.5? Research "banker's rounding" β€” does Java use it? Write your findings as comments in the code.
HardResearch
P3.17
Reverse-Engineer
Given this exact output, write the Java code that produces it β€” you must figure out which print method and escape sequences were used:
Line "one"
    Tabβ†’here
Path: C:\test\run
Done!
Hard
P3.18
The Great Printf Table
Using printf exclusively, print a complete class timetable: days as column headers, times as row headers, subject names in cells. Use %-Ns for left-aligned strings and ensure all columns are perfectly aligned regardless of cell content length.
Hard
Chapter 3 Challenge

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.