types

int num = 5;
float floatNum = 5.99f;
char letter = 'D';
boolean bool = true;
String site = "cheatsheets.zip";

Primitive versus object

int is a primitive value Integer is an object Collections store objects, not primitives

Autoboxing converts between them automatically That convenience is also the source of null pointer exceptions when an Integer is null and gets unboxed

Strings

String first = "John";
String last = "Doe";
String name = first + " " + last;

Strings are immutable + creates a new string In a loop, use StringBuilder

Comparison

String s1 = new String("cheatsheets.zip");
String s2 = new String("cheatsheets.zip");

s1 == s2;       // false
s1.equals(s2);  // true

== compares references equals compares contents That distinction has caused more bugs than any syntax quirk

Information

String str = "abcd";
str.length();
str.substring(2);
str.contains("c");

length() is a method, not a field Arrays use length as a field That inconsistency is worth memorising once

Next

Objects in 03 objects

Posted