Syntax and types
โ Report an issue with this lessonpublic class Main {
public static void main(String[] args) {
String name = "Ada";
int age = 28;
double price = 29.99;
System.out.println(name + " is " + age + " years old");
}
}
Every Java file needs a class matching its filename, and execution
starts from a main method -- this boilerplate is unavoidable
even for the smallest program.
Java's primitive types (int, double,
boolean, char, long, ...) are not
objects -- they live directly on the stack and have no methods. Each has
a corresponding wrapper class (Integer,
Double, Boolean, ...) used whenever you need an
object, such as inside a generic collection:
int primitive = 42;
Integer boxed = 42; // autoboxing: primitive -> wrapper, automatic
int unboxed = boxed; // unboxing: wrapper -> primitive, automatic
List<Integer> scores = new ArrayList<>();
scores.add(95); // autoboxed to Integer automatically
This autoboxing is convenient but has a sharp edge: wrapper objects
compare by reference with ==, not by value (except for a
small cached range of Integer values from -128 to 127, which
makes the bug even sneakier since it "works" for small numbers):
Integer a = 200;
Integer b = 200;
System.out.println(a == b); // false! different objects
System.out.println(a.equals(b)); // true -- compares value
Integer small1 = 100;
Integer small2 = 100;
System.out.println(small1 == small2); // true, thanks to caching -- don't rely on this
Always use .equals() to compare wrapper objects (and any
object type, including String) -- reserve ==
for primitives, where it correctly compares values.
String concatenation with + is convenient for a couple of
values, but building a string across a loop with + creates a
new String object on every iteration, since strings are
immutable in Java too. For loops, StringBuilder is the
efficient choice:
StringBuilder sb = new StringBuilder();
for (Course c : courses) {
sb.append(c.getTitle()).append(", ");
}
String joined = sb.toString();
Try it yourself
Run your code and get it working before marking this lesson complete.
9 more lessons โ including Capstone project: a course catalog service โ plus a certificate are waiting.
Unlock the full course โ $149.99