xSKILLby Infirals
Register

Java for Beginners

0 of 24 notes read 0%

Reading progress is saved to your INFIRALS account. Sign in to keep this note marked as read.

Your first program, line by line

Starting out10 min readLesson 2 of 3

2.1 The shape of a Java program

A Java file is built from a class that contains a main method. Inside the method, each instruction is a statement that ends with a semicolon. Braces mark the start and end of a block, so indentation is for humans while braces tell the compiler where the block stops.

Java is case sensitive. System, system, and SYSTEM are three different names. The order of statements matters because the program runs from top to bottom inside main. A comment can explain intent, but the compiler ignores it.

For now, put one public class in each file and match the file name to it. A file can hold other classes, and they can be non-public, but one public class per file is a simple rule while you learn.

2.1.1 Printing text

System.out.print writes text without a line break. System.out.println writes text and then moves to the next line. A string literal is text inside double quotes, such as "Java". The + operator joins a string with another value, so "Score: " + 12 produces Score: 12.

A println call ends the current line, so a series of calls produces one line per call. An empty println() adds a blank line. Use print when you want to build a line in pieces.

java
public class Main {
    public static void main(String[] args) {
        System.out.print("Loading");
        System.out.print("...");
        System.out.println(" done");
        System.out.println("Sum: " + (4 + 6));
        System.out.println("Text: " + 4 + 6);
    }
}

Output

Loading... done
Sum: 10
Text: 46

2.1.2 Formatting values

System.out.printf formats values. The first argument is a format string, and later arguments fill its placeholders. %s accepts text, %d accepts an integer, %f accepts a decimal number, and %.2f rounds the display to two places. %n inserts a platform-specific line break. Widths such as %6d pad a number with spaces.

Formatting is useful for reports and aligned columns. Plain concatenation is easier to read when a sentence has one or two values.

java
public class Main {
    public static void main(String[] args) {
        String name = "Ravi";
        int score = 42;
        double average = 87.5;
        System.out.printf("Name: %s%n", name);
        System.out.printf("Score: %d%n", score);
        System.out.printf("Average: %.2f%n", average);
    }
}

Output

Name: Ravi
Score: 42
Average: 87.50

2.1.3 Escape sequences

Some characters cannot appear directly inside a string literal, or they need a visible representation. Java uses a backslash to begin an escape sequence:

  • \" puts a double quote inside a string.
  • \\ produces one backslash.
  • \n produces a newline character.
  • \t produces a tab character.

A path written as "C:\notes" fails because \n starts an escape. Write "C:\\notes" to display C:\notes. A single quote needs escaping only inside a character literal, as in '\''; the same quote inside a double-quoted string is fine.

Escape sequences are one character at runtime even though they take two characters in the source. That detail matters when you count the length of a string.

java
public class Main {
    public static void main(String[] args) {
        System.out.println("She said \"hello\".");
        System.out.println("Folder: C:\\notes\\java");
        System.out.println("First line\nSecond line");
        System.out.println("Name:\tRavi");
    }
}

Output

She said "hello".
Folder: C:\notes\java
First line
Second line
Name:	Ravi

2.1.4 Comments and naming

A comment records context that the code cannot show by itself. Use // for a note on one line and /* ... */ for a block. A /** ... */ comment is a Javadoc comment; tools can turn it into documentation for classes and methods.

Good comments explain why a choice was made, what a non-obvious value means, or which rule a calculation follows. Repeating what the next line plainly does adds noise. Update a comment when the code changes, because a stale comment can mislead a reader more than no comment does.

Use PascalCase for class names, camelCase for methods and variables, and UPPER_SNAKE_CASE for constants. Avoid vague names such as tp; totalPrice tells a reader what the value holds.

java
public class Main {
    public static void main(String[] args) {
        // Price in rupees.
        double price = 480.0;
        /*
           A discount of 25 percent.
           The result is used once.
        */
        double discount = price * 0.25;
        System.out.println(price - discount);
    }
}

Output

360.0

2.1.5 Compiler messages in your first week

A Java error message has a location and a symptom. Read the file and line first, then the message, then the caret that points at the likely token. Common first-week messages include:

  • A missing semicolon after a statement.
  • A misspelled method or variable name, reported as cannot find symbol.
  • A missing closing brace, which can make the compiler report an error far from the real gap.
  • A string used with the wrong operator.
  • A main method with the wrong signature.

Fix one error at a time and recompile. If a single missing brace causes a page of errors, look for the first one that mentions an unexpected end of file. An editor with bracket matching can find it faster than reading every message.

2.1.6 Execution order and main

The launcher finds the main method and starts there. Statements run in order until the method ends or a return exits it. Method calls inside main are evaluated before the next statement continues.

args holds command-line arguments in an array. If you run java Main red blue, then args.length is 2, args[0] is "red", and args[1] is "blue". With no extra words, the array is empty and has length 0. The program does not receive the class name as an argument.

For now, keep all code in main and call helper methods later. As programs grow, execution still starts in main; it simply delegates work to other methods.

java
public class Main {
    public static void main(String[] args) {
        String first = "Hello";
        String second = "Java";
        System.out.println(first + ", " + second + "!");
        System.out.println("Start");
        System.out.println("End");
    }
}

Output

Hello, Java!
Start
End

2.1.7 Practice

  1. Print a three-line receipt with println.
  2. Print the same receipt with printf, using %s for a name and %d for a count.
  3. Print a sentence that contains double quotes, a tab, and a backslash.
  4. Write a comment above a calculation that explains the rate you used.
  5. Introduce a missing semicolon, compile, and name the part of the message that pointed to it.

Compare the outputs of steps 1 and 2. The visible text can match while the spacing and alignment differ.

Interview questions

3 questions from this note. Open one to see the answer; no account needed.

  • 01What is the difference between `print` and `println`?

    `print` writes its argument without adding a line break. `println` adds the platform line separator after writing.

  • 02Why does `"Count: " + 2 + 3` print `Count: 23`?

    The expression joins left to right, so the number 2 becomes text before 3 is added. Use parentheses around `2 + 3` to add the numbers first.

  • 03What does `%n` mean in a `printf` format string?

    It inserts the platform line separator, while `\n` inserts a newline character. Both end the visible line in normal console output.