CCA Guide
Introduction to Java

Introduction to Java

Curated by Last modified: 2 min read

View Markdown

Hello World

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}

Classes

Classes are blueprints for objects: they describe information and behavior. Creating an object is called instantiation.

When thinking about a class, ask: What does it represent? How does it behave?

Review clarification

These course examples place methods in classes. Java also has primitive values, so describing it as object-oriented does not mean every value is an object.

Related: Object-oriented programming.

Java execution

The compiler turns source (.java) into bytecode (.class), which runs on a Java Virtual Machine (JVM). JVM implementations make the same bytecode usable on many platforms.

For the example above, save Main.java, then run:

javac Main.java
java Main

Correction to the original file-name rule

With ordinary file-based compilation, a public top-level class needs a matching filename. The original note stated this as a rule for every class. Run java Main, using the class name rather than java Main.class.

Source: Java Language Specification §7.6.

print() writes without ending the current line. println() writes its argument and then ends that line.

Correction to the original shortcut

println(str) is similar to printing str followed by a newline, but uses the platform’s line separator, which is not always the single character "\n".

Source: PrintStream API.

String methods

MethodMeaningReturn type
substring(startIndex, endIndex)From the inclusive start to the exclusive endString
substring(startIndex)From the inclusive start through the endString
toLowerCase()A lowercase versionString
toUpperCase()An uppercase versionString
replace(target, replacement)Replace all literal occurrences of the targetString

Strings are immutable: these methods return strings without modifying the original string object.

Source: String API.

Escape sequences

SequenceMeaning
\nNewline
\tTab
\\One backslash

Concatenation

System.out.println("Hello" + " " + "World" + 5); // Hello World5
System.out.println("Hi" + 5 + 5); // Hi55
System.out.println(1 + 2 + "Three"); // 3Three

The extra quote after 5 in the original first example was a syntax error. The + operator concatenates when a string is involved, converting the other operand to text. Evaluation proceeds left to right: the last example adds the two integers before reaching the string.

Related: Strings and characters · Variables · Commenting

Linked to this page