Why this matters
Java powers large systems where reliability and maintainability matter: banking back ends, Android apps, and enterprise services. Its strong typing catches many mistakes at compile time, and its runtime handles memory for you, so you can focus on logic rather than manual allocation.
You should learn Java because it teaches habits that transfer widely. Everything must live inside a class, types are explicit, and errors are handled deliberately. Those constraints feel strict at first but make large codebases easier to read and safer to change as a team grows.
The tooling around Java is another reason it endures. Compilers, build tools, and IDEs can see the full type structure of a program, so they catch mistakes before you run anything and can refactor confidently. That feedback loop is especially valuable on projects where many people touch the same code over many years.
The big picture
Java source is written in .java files and compiled into bytecode. That bytecode does not run directly on your processor; the JVM reads it, verifies it, and executes it. This extra layer is the reason the same compiled program can run on Windows, macOS, and Linux without being rebuilt.
At the language level, everything revolves around classes and objects. A class is a blueprint describing state as fields and behaviour as methods. An object is one instance of that blueprint. When you call a method, you send a message to a specific object, and that object runs its own copy of the code.
One detail worth keeping in mind is the difference between a reference and the object it points to. Variables of a class type hold references, so copying one gives you two names for the same object. Methods that receive a reference can change the object's fields, which is why careful encapsulation matters more in Java than in languages with value semantics.
Core ideas
Classes and objects
A class groups data and the behaviour that operates on it. Fields hold the data, a constructor sets the initial state, and methods define what the object can do. You create an object with the new keyword, which allocates memory and runs the constructor.
Keeping fields private and exposing behaviour through methods is called encapsulation. It lets you change the internal representation later without breaking code that uses the class. This is the single most important habit for writing Java that survives refactoring.
class Dog {
private String name;
Dog(String name) { this.name = name; }
void bark() { System.out.println(name + " says woof"); }
}
Dog rex = new Dog("Rex");
rex.bark();
Watch out. Making every field public. Start with private and add accessors only when needed.
Types and variables
Java is statically typed, so every variable has a declared type known at compile time. Primitive types such as int, double, and boolean store values directly; reference types such as String and arrays store addresses of objects. Understanding that split explains most null-related bugs.
You can also use var for local variables when the type is obvious from the right-hand side. The variable is still statically typed; the compiler simply infers it. Use it to reduce clutter, not to hide what a value really is.
int age = 30;
double price = 9.99;
boolean active = true;
String name = "Ada";
var count = 3;
Watch out. Comparing strings with ==. Use equals so you compare content rather than references.
Control flow
Java uses familiar constructs: if and else for decisions, for and while for loops, and switch for multi-way choices. Blocks are marked with braces, and conditions must be boolean expressions. indent your code consistently because the compiler ignores whitespace.
The enhanced for loop iterates over arrays and collections without an index variable. Break exits a loop early and continue skips to the next iteration. Prefer clear, shallow nesting; deeply nested conditionals are a sign that a method should be split.
if (age >= 18) {
System.out.println("adult");
} else {
System.out.println("minor");
}
for (int score : scores) {
System.out.println(score);
}
Watch out. Writing if (age = 18). Assignment is not a boolean expression in Java, so the compiler rejects it.
Arrays and collections
Arrays hold a fixed number of values of one type, created with new or an initialiser. Their length is fixed after creation. For most real work you will use the collection framework instead: List for ordered sequences, Set for unique values, and Map for key-value pairs.
Collections grow as needed and come with useful methods for searching and sorting. The generic type in angle brackets tells the compiler what the collection holds, which catches mistakes early. Prefer the interface type in declarations and an implementation on the right side.
int[] scores = { 10, 20, 30 };
List<String> names = new ArrayList<>();
names.add("Ada");
names.add("Grace");
Watch out. Assuming arrays resize. Use an ArrayList when the number of items is unknown.
Exceptions
When something goes wrong, Java throws an exception. Checked exceptions must be handled or declared, which forces you to acknowledge failures such as missing files. Unchecked exceptions, including NullPointerException, signal programming mistakes and need not be declared.
Handle exceptions with try and catch, and use finally or try-with-resources for cleanup. Catch the most specific type you can and avoid empty catch blocks that swallow errors. A good message at the point of failure beats a broad catch at the top.
try (var reader = Files.newBufferedReader(path)) {
return reader.readLine();
} catch (IOException e) {
throw new IllegalStateException("Cannot read config", e);
}
Watch out. Catching Exception everywhere. Handle specific failures and let unexpected ones surface.
Packages and the JVM
Packages group related classes and avoid name collisions. You import classes you use from other packages, and the compiler resolves the rest. Keeping your own code in meaningful packages makes a large project far easier to navigate than one giant folder.
The JVM also provides garbage collection, reclaiming objects that are no longer reachable. You do not free memory manually, but you can still hold references too long and keep objects alive accidentally. Knowing that references determine lifetime helps you diagnose leaks.
import java.util.List;
import java.util.ArrayList;
public class App {
public static void main(String[] args) {
System.out.println("Hello, Java");
}
}
Watch out. Naming your file differently from its public class. The file name must match.
Methods
A method is a named block of code attached to a class. It takes inputs as parameters, performs work, and optionally returns a result. Methods are how Java organises behaviour: instead of one long procedure, you build small pieces that each do one thing well.
Unlike a C-style function, a Java method always belongs to a class and is invoked on an object or on the class itself. That ownership matters for access to state and for how the method participates in inheritance. Master methods and you have mastered the shape of Java programs.
Declaring a method
A declaration has an access modifier, an optional static keyword, a return type, a name, and a parameter list in parentheses. The body sits in braces. Convention says method names use lower camel case and read like verbs, such as calculateTotal or sendMessage.
The return type is part of the method's contract. Callers rely on it, so changing it changes the method as surely as changing its name. Java enforces this at compile time: a missing or mismatched return statement is an error, not a surprise at runtime. That strictness is why well-typed method signatures make large programs easier to assemble.
public int square(int n) {
return n * n;
}
Parameters and arguments
Parameters are variables declared in the method signature; arguments are the values you pass when calling it. Java uses pass by value, so the method receives a copy of the value. For objects the copied value is a reference, so the method can mutate the object but cannot reassign the caller's variable.
void greet(String name, int times) {
for (int i = 0; i < times; i++) {
System.out.println("Hi " + name);
}
}
greet("Ada", 2);
Return values and void
A method with a return type must return a compatible value on every path. The return statement ends the method immediately. A void method returns nothing; it is used for side effects such as printing, updating a field, or writing to a file. You may use a bare return in void to exit early.
boolean isAdult(int age) {
return age >= 18;
}
void log(String message) {
if (message == null) return;
System.out.println(message);
}
Overloading
You can define several methods with the same name as long as their parameter lists differ. This is overloading, and the compiler picks the right version from the arguments you pass. It lets one name cover sensible variations without forcing awkward names like addInts and addDoubles.
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
String add(String a, String b) { return a + b; }
Static vs instance
An instance method belongs to an object and can access that object's fields using this. A static method belongs to the class and can only use static members directly. Use static for pure utilities and factory helpers; use instance methods when behaviour depends on object state.
class Math2 {
static int twice(int n) { return n * 2; }
}
int result = Math2.twice(4);
Recursion and scope
A recursive method calls itself to solve a smaller version of a problem. It needs a base case that stops the recursion and a step that moves toward it. Variables declared inside a method are local: they exist only while that call runs, and each recursive call gets its own copies.
int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
Varargs and C comparison
Varargs let a method accept zero or more values of one type using three dots. Inside the method the values arrive as an array. In C you write standalone functions and pass pointers when you need many values; in Java the method stays inside a class and the language manages the collection for you.
int sum(int... nums) {
int total = 0;
for (int n : nums) total += n;
return total;
}
sum(1, 2, 3);
Function reference
These are the functions you will reach for most often. Each one is shown with its syntax, its inputs and outputs, a working example, and the mistakes to avoid.
method
User-defined method
A method is a named block of code inside a class that performs a task. Defining one lets you reuse the same logic from many places instead of copying it.
| Syntax | returnType name(parameters) { body } |
|---|---|
| Parameters | returnType — The type returned, or void if nothing is returned. name — The method's name. parameters — Zero or more typed inputs. |
| Returns | The value declared by returnType, or nothing when it is void. |
public class Greeter {
public String greet(String name) {
return "Hello, " + name;
}
}
What you can do with it. Group a repeatable task into one named unit. Split a large program into small, testable pieces. Hide implementation details behind a clear method name.
Choose it when. Choose a method when you need to reuse a block of logic, rather than pasting the same lines in several places.
| Mistake | Fix |
|---|---|
| Forgetting a return statement in a non-void method. | Return a value of the declared type on every code path. |
| Naming a method so vaguely that its job is unclear. | Use a verb that says what it does, like calculateTotal. |
static method
User-defined method
A static method belongs to the class itself rather than to an object. You call it on the class name, which makes it ideal for helpers that do not need instance data.
| Syntax | static returnType name(parameters) { body } |
|---|---|
| Parameters | static — Marks the method as belonging to the class. returnType — The type it returns, or void. name — The method name. |
| Returns | The declared return value; callable without creating an object. |
public class MathUtils {
public static int square(int n) {
return n * n;
}
}
int result = MathUtils.square(5);
What you can do with it. Write utility functions such as conversions or checks. Provide factory methods that create objects. Keep constants and helpers together in one class.
Choose it when. Choose a static method when the logic does not depend on an object's state, rather than creating an object just to call it.
| Mistake | Fix |
|---|---|
| Calling a static method on an instance. | Call it through the class name, such as MathUtils.square(5). |
| Trying to use instance fields inside a static method. | Pass what you need in as parameters, or make the method non-static. |
constructor
User-defined method
A constructor initialises a new object when you create it with new. Its name matches the class and it has no return type.
| Syntax | public ClassName(parameters) { body } |
|---|---|
| Parameters | ClassName — Must match the class name exactly. parameters — Values used to set up the new object. |
| Returns | Nothing explicitly; it produces a fully initialised instance. |
public class User {
private String name;
public User(String name) {
this.name = name;
}
}
User u = new User("Ada");
What you can do with it. Set required fields when an object is created. Guarantee an object starts in a valid state. Offer several constructors for different ways to build an object.
Choose it when. Choose a constructor when an object needs setup at birth, rather than calling a separate init method later.
| Mistake | Fix |
|---|---|
| Adding a return type to a constructor. | A constructor has no return type, not even void. |
| Forgetting to initialise a required field. | Set every essential field inside the constructor. |
method overloading
User-defined method
Overloading lets you define several methods with the same name but different parameter lists. Java picks the right one based on the arguments you pass.
| Syntax | type name(type1 a) { ... }
type name(type1 a, type2 b) { ... } |
|---|---|
| Parameters | name — The shared method name. parameters — A different count or type per version. |
| Returns | Whatever each individual version declares. |
public int area(int side) {
return side * side;
}
public int area(int width, int height) {
return width * height;
}
What you can do with it. Offer convenient versions of the same operation. Support optional inputs without nullable arguments. Keep related behaviour under one clear name.
Choose it when. Choose overloading when the same concept accepts different inputs, rather than inventing names like areaSquare and areaRect.
| Mistake | Fix |
|---|---|
| Overloading only by return type. | Vary the parameters; return type alone is not enough to distinguish methods. |
| Making two versions with identical parameter lists. | Change the number or types of parameters. |
varargs
User-defined method
Varargs let a method accept any number of arguments of one type. Inside the method, those arguments arrive as an array.
| Syntax | type name(Type... values) { body } |
|---|---|
| Parameters | Type... — Declares a variable-length parameter of that type. values — The arguments, treated as an array inside the method. |
| Returns | Whatever the method declares; the caller may pass zero or many values. |
public int sum(int... numbers) {
int total = 0;
for (int n : numbers) total += n;
return total;
}
int s = sum(1, 2, 3, 4);
What you can do with it. Write helpers that take a flexible number of inputs. Build simple logging or formatting functions. Accept a list without forcing the caller to create an array.
Choose it when. Choose varargs when the count of inputs varies, rather than requiring callers to build an array every time.
| Mistake | Fix |
|---|---|
| Placing other parameters after the varargs parameter. | Keep varargs last in the parameter list. |
| Treating the parameter as a single value. | Iterate over it as an array. |
recursion
User-defined method
Recursion is when a method calls itself to solve a smaller version of the same problem. It needs a base case so the calls eventually stop.
| Syntax | type name(parameters) { if (base) return value; return name(smaller); } |
|---|---|
| Parameters | baseCase — The condition that ends the recursion. smallerInput — A reduced input passed to the next call. |
| Returns | The final result built up as each call returns. |
public int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
What you can do with it. Walk tree or nested structures. Express problems like factorial and Fibonacci cleanly. Traverse folders and their subfolders.
Choose it when. Choose recursion when a problem naturally breaks into smaller versions of itself, rather than forcing it into a loop that is harder to read.
| Mistake | Fix |
|---|---|
| Forgetting the base case. | Always define a condition that stops the calls, or you get a stack overflow. |
| Passing an input that never gets smaller. | Make each call move toward the base case. |
String.length()
Standard library function
length() returns the number of characters in a string. You use it to check sizes, loop through characters, or validate input.
| Syntax | string.length() |
|---|---|
| Returns | An int giving the character count of the string. |
String name = "Ada";
int n = name.length();
System.out.println(n);
What you can do with it. Check whether a password is long enough. Loop over each character by index. Reject empty input before processing it.
Choose it when. Choose length() whenever you need the size of a string, rather than counting characters yourself.
| Mistake | Fix |
|---|---|
| Calling length() on a null string. | Check for null first, or use an empty string instead of null. |
| Confusing it with the array length field. | Strings use length(); arrays use .length without parentheses. |
String.substring()
Standard library function
substring() extracts part of a string between a start index and an optional end index. The start is included and the end is excluded.
| Syntax | string.substring(beginIndex, endIndex) |
|---|---|
| Parameters | beginIndex — The first index to include. endIndex — The index where extraction stops, not included. |
| Returns | A new string containing the selected characters. |
String s = "Hello, world";
String first = s.substring(0, 5);
String rest = s.substring(7);
What you can do with it. Pull a name or code out of a longer string. Trim a prefix or suffix after checking it. Split text at a known position.
Choose it when. Choose substring() when you know the positions of the text you want, rather than searching by pattern.
| Mistake | Fix |
|---|---|
| Assuming the end index is included. | Remember the range is start-inclusive and end-exclusive. |
| Using an index beyond the string length. | Check bounds with length() first to avoid an exception. |
List.add()
Standard library function
add() appends an element to a List, growing it as needed. It is the basic way to build a collection whose size you do not know up front.
| Syntax | list.add(element) |
|---|---|
| Parameters | element — The object to add to the list. |
| Returns | A boolean, true for most lists, indicating the add succeeded. |
List<String> names = new ArrayList<>();
names.add("Ada");
names.add("Grace");
What you can do with it. Collect results as you read a file. Build a list of user selections. Accumulate items before processing them.
Choose it when. Choose List.add() when you need a growable collection, rather than a fixed-size array.
| Mistake | Fix |
|---|---|
| Adding the wrong type into a generic list. | Match the declared type, such as List<String>. |
| Expecting add to return the new size. | It returns a boolean; use size() for the count. |
Map.get()
Standard library function
get() looks up a value by its key in a map. It returns the associated value, or null when the key is not present.
| Syntax | map.get(key) |
|---|---|
| Parameters | key — The key whose value you want. |
| Returns | The value for the key, or null if there is no mapping. |
Map<String, Integer> ages = new HashMap<>();
ages.put("Ada", 36);
Integer age = ages.get("Ada");
What you can do with it. Look up a setting by its name. Count how often each word appears. Fetch an object by an identifier.
Choose it when. Choose Map.get() when you need fast lookup by key, rather than scanning a list linearly.
| Mistake | Fix |
|---|---|
| Assuming a missing key throws an error. | It returns null; check the result or use containsKey. |
| Using a key of the wrong type. | Match the map's declared key type. |
Arrays.sort()
Standard library function
Arrays.sort() arranges the elements of an array in ascending order. It changes the array in place instead of making a new one.
| Syntax | Arrays.sort(array) |
|---|---|
| Parameters | array — The array to sort. comparator — An optional custom ordering. |
| Returns | Nothing; the original array is reordered. |
int[] nums = {5, 2, 9, 1};
Arrays.sort(nums);
System.out.println(Arrays.toString(nums));
What you can do with it. Order numbers before displaying them. Sort strings alphabetically. Prepare data for a binary search.
Choose it when. Choose Arrays.sort() for arrays when you need ascending order, rather than writing your own sorting loop.
| Mistake | Fix |
|---|---|
| Expecting a sorted copy while the original stays unchanged. | sort mutates the array in place; copy it first if you need the original. |
| Forgetting to import java.util.Arrays. | Add the import before calling the method. |
Math.max()
Standard library function
Math.max() returns the larger of two numbers. It is a small helper that avoids writing an if statement for a simple comparison.
| Syntax | Math.max(a, b) |
|---|---|
| Parameters | a — The first number. b — The second number. |
| Returns | The greater of a and b. |
int top = Math.max(10, 20);
double limit = Math.max(0.5, ratio);
What you can do with it. Clamp a value to at least a minimum. Find the larger of two measurements. Compute the bigger dimension for layout math.
Choose it when. Choose Math.max() for a quick two-value comparison, rather than writing an if/else block.
| Mistake | Fix |
|---|---|
| Passing mixed types that need a common type. | Use matching numeric types or let Java widen them. |
| Looking for a version that takes three arguments. | Nest calls, like Math.max(a, Math.max(b, c)). |
Integer.parseInt()
Standard library function
parseInt() converts a string of digits into an int. You use it whenever text input must become a number you can calculate with.
| Syntax | Integer.parseInt(string) |
|---|---|
| Parameters | string — Text containing a whole number. radix — An optional base, such as 16 for hexadecimal. |
| Returns | An int parsed from the text. |
String input = "42";
int value = Integer.parseInt(input);
int hex = Integer.parseInt("FF", 16);
What you can do with it. Turn form input into a number. Read numeric configuration from a file. Convert hexadecimal text into a decimal value.
Choose it when. Choose Integer.parseInt() when you have a string that should be a whole number, rather than treating it as text.
| Mistake | Fix |
|---|---|
| Passing text that is not a valid integer. | Catch NumberFormatException or validate first. |
| Forgetting that surrounding spaces cause failure. | Trim the string before parsing. |
stream().filter()
Standard library function
filter() keeps only the elements of a stream that match a condition. Combined with a terminal operation, it gives you a compact way to select data.
| Syntax | collection.stream().filter(predicate).collect(...) |
|---|---|
| Parameters | predicate — A lambda returning true for elements to keep. |
| Returns | A stream of the matching elements, ready for further operations. |
List<Integer> evens = nums.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
What you can do with it. Select records that meet a condition. Chain selection with mapping and sorting. Replace verbose loops with readable pipelines.
Choose it when. Choose stream().filter() for concise selection over collections, rather than writing an explicit loop with an if inside.
| Mistake | Fix |
|---|---|
| Forgetting a terminal operation, so nothing runs. | End the pipeline with collect, forEach, or count. |
| Expecting filter to modify the original list. | Streams do not change the source; collect the result into a new list. |
Common mistakes here
| Mistake | Fix |
|---|---|
| Forgetting a return on one branch of a non-void method. | Ensure every path returns a value, or throw an exception. |
| Overloading only by return type. | Overloads must differ in parameter list, not just return type. |
| Calling an instance method with the class name. | Create an object first, or mark the method static if it needs no state. |
| Writing recursion without a reachable base case. | Define the stopping condition first and move toward it each call. |
| Expecting a method to change a primitive argument. | Return the new value, or wrap it in an object or array. |
The example, line by line
This small program creates an object, calls one of its methods, and prints the result.
| Code | What it does |
|---|---|
1public class Greeter { | Declares a public class; the file must be named Greeter.java. |
2 public static void main(String[] args) { | Declares the entry point the JVM calls when the program starts. |
3 Greeter g = new Greeter(); | Creates a Greeter object with the new keyword. |
4 String message = g.build("Ada", 3); | Calls the instance method with two arguments and stores the result. |
5 System.out.println(message); | Prints the returned string to the console. |
6 } | Closes the main method. |
7 String build(String name, int repeats) { | Declares an instance method that takes a name and a repeat count. |
8 return ("Hi " + name + " ").repeat(repeats).trim(); | Builds the greeting and returns it using String.repeat and trim. |
9 } | Closes the build method. |
10} | Closes the class. |
public class Greeter {
public static void main(String[] args) {
Greeter g = new Greeter();
String message = g.build("Ada", 3);
System.out.println(message);
}
String build(String name, int repeats) {
return ("Hi " + name + " ").repeat(repeats).trim();
}
}
Worked variations
A static utility
When a method needs no object state, make it static and call it through the class. Utility classes like this are common in Java, though keep them focused and give them a private constructor so nobody instantiates them.
final class Strings {
private Strings() {}
static String shout(String text) {
return text.toUpperCase() + "!";
}
}
Strings.shout("hello");
Overloaded formatting
Overloading lets one method name handle several input shapes. Here the compiler chooses the version that matches the arguments, which keeps calling code clean.
String format(String value) { return "[" + value + "]"; }
String format(int value) { return String.format("[%03d]", value); }
format("hi");
format(7);
A recursive search
Recursion often reads more naturally than a loop for tree-shaped data. The method checks the base case first and then calls itself on a smaller subtree, with each call getting its own local variables.
boolean contains(Node node, String target) {
if (node == null) return false;
if (node.value.equals(target)) return true;
return contains(node.left, target) || contains(node.right, target);
}
Common mistakes
| Mistake | Fix |
|---|---|
| Putting unrelated methods into one giant class. | Split behaviour into classes with one clear responsibility. |
| Using == to compare String contents. | Use String.equals for value comparison. |
| Declaring everything public static. | Use instance methods for state and static only for true utilities. |
| Ignoring a null argument until it crashes deep in a method. | Validate inputs at the boundary with Objects.requireNonNull. |
| Calling a method before its object is fully constructed. | Avoid leaking this from a constructor. |
Practice
- Write a static method that converts Celsius to double-precision Fahrenheit and returns it.
- Create a class with two fields and an instance method that uses them.
- Overload a method to accept either an int or a String and print each differently.
- Implement a recursive method that computes the sum of numbers from one to n.