Introduction to Java
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 thanjava Main.class.
Source: Java Language Specification §7.6.
print() and println()
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 printingstrfollowed by a newline, but uses the platform’s line separator, which is not always the single character"\n".
Source: PrintStream API.
String methods
| Method | Meaning | Return type |
|---|---|---|
substring(startIndex, endIndex) | From the inclusive start to the exclusive end | String |
substring(startIndex) | From the inclusive start through the end | String |
toLowerCase() | A lowercase version | String |
toUpperCase() | An uppercase version | String |
replace(target, replacement) | Replace all literal occurrences of the target | String |
Strings are immutable: these methods return strings without modifying the original string object.
Source: String API.
Escape sequences
| Sequence | Meaning |
|---|---|
\n | Newline |
\t | Tab |
\\ | 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