What Java is and how a program runs
Java is a general-purpose language created in 1995. Its big idea: write once, run anywhere.
- You write source code in a file
Hello.java. - The compiler
javacturns it into bytecode (Hello.class). - The JVM (Java Virtual Machine) runs the bytecode on any computer.
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, world");
}
}Every program starts at main. Statements end with a semicolon; blocks sit inside { }. Java is case-sensitive: Age and age are different names. Comments: // one line and /* many lines */.
Data types, variables and constants
A variable is a named box in memory. You must give its type before use: int marks = 85;
| Type | Holds | Size |
|---|---|---|
| byte, short, int, long | whole numbers | 1, 2, 4, 8 bytes |
| float, double | decimals | 4, 8 bytes |
| char | one Unicode character, e.g. 'A' | 2 bytes |
| boolean | true or false | - |
These 8 are primitive types. String, arrays and objects are reference types. A final variable is a constant: final double PI = 3.14159;. Rules for names: start with a letter, _ or $, no spaces, not a keyword like class.
Type casting: small to big is automatic (double d = 5;); big to small needs a cast (int n = (int) 7.9; gives 7).
Operators
- Arithmetic: + β * / %. Integer division drops the decimal:
7 / 2is 3;7 % 2(remainder) is 1. - Relational: == != < > <= >= give a boolean.
- Logical: && (and), || (or), ! (not).
- Assignment: =, +=, -=, *=, /=.
- Increment/decrement:
i++uses then adds 1;++iadds 1 then uses. - Ternary:
result = (marks >= 33) ? "Pass" : "Fail";
Precedence: * / % before + β; use brackets to be clear.
Control flow: if, switch and loops
if (marks >= 90) grade = 'A';
else if (marks >= 75) grade = 'B';
else grade = 'C';switch picks one of many fixed values (use break to stop falling into the next case).
- for: when you know how many times:
for (int i = 0; i < 5; i++). - while: checks first, may run zero times.
- doβ¦while: runs at least once, checks after.
breakleaves a loop;continueskips to the next round.
Example: sum of 1 to 10: int s = 0; for (int i = 1; i <= 10; i++) s += i; gives 55.
Arrays and strings
An array stores many values of one type: int[] m = {70, 85, 92}; or int[] m = new int[3];. Index starts at 0, so the last index is m.length β 1. Going past it throws ArrayIndexOutOfBoundsException. A 2-D array is a table: int[][] t = new int[3][4];.
A String is an object holding text. Strings are immutable: methods return a new string.
length(),charAt(i),substring(a, b),indexOf("x")toUpperCase(),trim(),concat()or +- Compare text with
equals(), not ==.
For a lot of joining inside loops, use StringBuilder.
OOP and class design
A class is a blueprint with fields (data) and methods (actions). An object is one thing made from it with new.
class Student {
private String name; private int marks;
Student(String n, int m) { name = n; marks = m; } // constructor
boolean passed() { return marks >= 33; }
}
Student s = new Student("Asha", 60);- Encapsulation: keep fields
private, give public getters/setters. - Inheritance:
class Topper extends Studentreuses code. - Polymorphism: overloading (same name, different parameters) and overriding (child changes a parent method).
- Abstraction: abstract classes and interfaces show what, not how.
staticmembers belong to the class, not to each object;thismeans the current object.
Exceptions and assertions
An exception is an error event at run time, such as dividing an integer by zero or opening a missing file. Handle it so the program does not crash:
try { int r = a / b; }
catch (ArithmeticException e) { System.out.println("Cannot divide by zero"); }
finally { System.out.println("Done"); }Checked exceptions (e.g. IOException) must be caught or declared with throws; unchecked ones (e.g. NullPointerException) come from programming mistakes. You can raise one with throw.
An assertion checks something you believe must be true while testing: assert marks >= 0 : "marks negative";. Assertions are off by default and turned on with java -ea; never use them to check user input.
Wrapper classes and threads
Wrapper classes wrap a primitive in an object: int β Integer, double β Double, char β Character, boolean β Boolean. Collections like ArrayList<Integer> need objects. Java converts automatically (autoboxing and unboxing). Useful methods: Integer.parseInt("42"), Double.parseDouble("2.5"), Character.isDigit(c).
A thread is a separate path of work inside one program, so it can, for example, download a file while the screen stays responsive. Create one by extending Thread or implementing Runnable, then call start() (not run()). States: new β runnable β running β waiting/blocked β terminated. When threads share data, synchronized stops them changing it at the same moment.
Try it
In the 3D, set n = 6 and predict arr[5] before you look (it is 25). Then on any computer with Java, type a program that prints the 7 times table with a for loop, and change it to stop at 7 Γ 5 using break.
Key formulas and definitions
- Compile and run: javac Hello.java β java Hello
- Array index: 0 to length β 1
- Integer division: 7 / 2 = 3; 7 % 2 = 1
- for (init; condition; update) { body }
- Object creation: ClassName obj = new ClassName(args);
- try { β¦ } catch (Type e) { β¦ } finally { β¦ }
- Autoboxing: int β Integer; Integer.parseInt("12") β 12
Worked examples
1. What does this print? int a = 17, b = 5; System.out.println(a / b + " " + a % b);
a / b with integers is 3 (decimal dropped) and a % b is 2. Output: 3 2.
2. Write a loop that adds all even numbers from 2 to 20.
int s = 0; for (int i = 2; i <= 20; i += 2) s += i; The total is 2 + 4 + β¦ + 20 = 110.
3. Find the largest value in int[] m = {45, 88, 67, 91, 30}.
int max = m[0]; for (int i = 1; i < m.length; i++) if (m[i] > max) max = m[i]; Trace: 45 β 88 β 88 β 91 β 91. Answer 91.
4. What happens with: String s = "Java"; System.out.println(s.charAt(4));
Valid indexes are 0 to 3, so charAt(4) throws StringIndexOutOfBoundsException at run time.
5. Design a class BankAccount with a private balance, a deposit method and a withdraw method that refuses to go below zero.
class BankAccount { private double balance; void deposit(double x) { if (x > 0) balance += x; } boolean withdraw(double x) { if (x <= balance) { balance -= x; return true; } return false; } double getBalance() { return balance; } } Private balance plus checks is encapsulation.
6. Convert the text "250" to a number, add 50 and print it, handling bad input.
try { int n = Integer.parseInt("250"); System.out.println(n + 50); } catch (NumberFormatException e) { System.out.println("Not a number"); } prints 300.
Common mistakes
- Comparing strings with == instead of equals(): == checks if they are the same object, not the same text.
- Using arr[arr.length] as the last element: the last index is length β 1.
- Expecting 7 / 2 to give 3.5: with two ints the answer is 3. Use 7.0 / 2.
- Calling run() instead of start() on a thread: run() just runs in the same thread.