JAVA — CHAPTER 2

Intro to Java Programming · Concept Cheat Sheet
First Program printf Arithmetic Comparisons String Class
1 YOUR FIRST JAVA PROGRAM
public class Welcome1 { public static void main(String[] args) { System.out.println("Welcome to Java!"); } }

Anatomy of the program

  • class Welcome1 — every app needs at least one class
  • public static void main(String[] args) — the entry point the JVM calls first
  • System.out.println(...) — prints text + moves to a new line
  • File name must match the public class name: Welcome1.java
  • Statements end with a semicolon ;
2 MODIFYING OUTPUT & printf

print vs println vs printf

  • print() — no newline after
  • println() — newline after
  • printf() — formatted output with placeholders
System.out.printf("%s is %d years old.%n", "Amit", 21); // %s = string, %d = int, %n = newline
3 READING INPUT & ARITHMETIC
Scanner input = new Scanner(System.in); System.out.print("Enter two integers: "); int num1 = input.nextInt(); int num2 = input.nextInt(); int sum = num1 + num2;

Arithmetic operators

OpMeaning
+ - *add, subtract, multiply
/division (int / int = int)
%remainder (modulus)

Precedence: ()* / %+ -, left-to-right.

4 DECISION MAKING — EQUALITY & RELATIONAL OPERATORS
OperatorMeaning
==equal to
!=not equal to
> <greater / less than
>= <=greater/less than or equal
if (num1 == num2) { System.out.println("Numbers are equal"); }
5 OBJECTS-NATURAL CASE STUDY: THE STRING CLASS

Creating & using

  • String name = "Java";
  • Strings are objects — immutable once created

Common methods

  • length() — number of characters
  • toUpperCase()/toLowerCase()
  • charAt(i) — character at index
  • equals() — compare content
String s = "Java"; System.out.println(s.length()); // 4 System.out.println(s.toUpperCase()); // JAVA
6 METHOD REFERENCE TABLE

class String

MethodReturns
length()number of characters
charAt(i)char at index i
substring(a,b)substring from a to b-1
toUpperCase()/toLowerCase()new cased String
equals(obj)true if content matches
trim()String with whitespace removed from ends

class Scanner

MethodReturns
nextInt()next token as int
nextDouble()next token as double
next()next token as String
nextLine()rest of the current line as String
hasNextInt()true if next token is an int