What carries over
| PHP concept | Java equivalent | How it helps you transition |
|---|---|---|
| Variables and scalar types | int, long, double, boolean, String | The idea of typed values is the same; you just declare the type explicitly. |
Control structures (if, else, while, for, foreach) | Same keywords, same semantics | Looping and branching work identically; only syntax differences (e.g., parentheses are mandatory). |
| Functions → Methods | public static void foo() | PHP functions become static or instance methods inside a class. |
Associative arrays → Map | java.util.HashMap<K,V> | The mental model of key‑value look‑ups transfers; you just use a generic collection. |
Exception handling (try/catch/finally) | Same keywords | The flow is identical; you just catch concrete exception classes. |
String interpolation ("Hello $name") | String.format or text blocks | You still embed variables, but via String.format or ${} inside a text block. |
| Autoloading / include paths | Classpath | Both rely on a search path to locate code; you’ll use -classpath or IDE project settings. |
Composer autoload → javac compilation | javac + jar | Build tools compile source into bytecode; the concept of a build step is familiar. |
| Unit testing mindset | JUnit / TestNG | The same arrange‑act‑assert pattern; you just use a different library. |
| Dependency injection (DI) basics | Spring or CDI | PHP DI containers map to Java frameworks; the pattern is identical, only the wiring syntax changes. |
Coding habits that survive
- Write small, pure functions – In Java you’ll encapsulate them as static methods or service beans.
- Prefer early returns – Java’s
returnworks the same way, keeping methods readable. - Use meaningful names – Java’s stricter naming conventions (camelCase for methods, PascalCase for classes) are a small stylistic tweak.
- Guard clauses for input validation – Throw
IllegalArgumentExceptionjust as you’dInvalidArgumentExceptionin PHP.
What's new
Java is statically typed, compiled, and runs on the JVM. The biggest shifts are:
- Class‑centric design – Everything lives inside a class; free‑standing functions don’t exist.
- Generics – Collections are typed at compile time, eliminating many runtime errors.
- Checked exceptions – Certain exceptions must be declared or caught.
- Build tooling – Maven or Gradle replace Composer for dependency management and packaging.
- Concurrency primitives –
Thread,ExecutorService, and thejava.util.concurrentpackage are the primary way to do parallel work.
Side‑by‑side example: reading a JSON file and decoding it
PHP (using json_decode)
<?php $json = file_get_contents('data.json'); $data = json_decode($json, true); echo $data['name']; ?> Java (using Jackson)
import java.nio.file.Files; import java.nio.file.Paths; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.Map; public class ReadJson { public static void main(String[] args) throws Exception { byte[] jsonBytes = Files.readAllBytes(Paths.get("data.json")); ObjectMapper mapper = new ObjectMapper(); Map<String, Object> data = mapper.readValue(jsonBytes, Map.class); System.out.println(data.get("name")); } } What changed and why
| Aspect | PHP | Java |
|---|---|---|
| File I/O | file_get_contents reads the whole file as a string. | Files.readAllBytes returns a byte[]; Java prefers NIO for performance and explicit charset handling. |
| JSON parsing | json_decode returns a mixed array/object automatically. | Jackson’s ObjectMapper requires a target type (Map.class) and returns a generic Map<String,Object>. |
| Error handling | Returns false on failure; you check with === false. | All I/O and parsing methods throw checked exceptions (IOException, JsonProcessingException), forcing you to handle them. |
| Type safety | Dynamic typing; you trust the structure at runtime. | Generics give compile‑time guarantees about the map’s key/value types. |
| Entry point | Script runs top‑to‑bottom. | Java needs a public static void main method inside a class. |
Common pitfalls
- Forgetting to add
public static void main– Java won’t run a file without an entry point. - Mixing up primitive vs wrapper types –
intvsInteger; autoboxing helps but can introduceNullPointerException. - Ignoring the classpath – A missing JAR leads to
ClassNotFoundException; always verify Maven/Gradle dependencies. - Overusing static methods – Unlike PHP, excessive static code makes testing harder; prefer instance beans when using a DI framework.
- Assuming PHP’s loose typing – Java will reject code that compiles in PHP; declare types everywhere.
- Neglecting checked exceptions – Failing to catch or declare them stops compilation.
- Using
ArrayListwithout generics – Raw types compile but generate warnings and lose type safety.
Your 30‑day plan
Week 1 – Foundations
- Install JDK 17 (or the latest LTS) and set
JAVA_HOME. - Compile and run a “Hello World” class with
javacandjava. - Complete the official Java Language Basics tutorial (focus on types, control flow, and methods).
- Mini‑project: Build a command‑line address book that stores contacts in a
List<Contact>and prints them. Use only core Java (no external libs).
Week 2 – Object‑Oriented Deep Dive
- Create a small hierarchy:
Animal → Dog, Catdemonstrating inheritance, abstract classes, and interfaces. - Practice encapsulation: private fields with getters/setters, and immutability with
final. - Learn the Collections Framework (
ArrayList,HashMap,Set). - Mini‑project: Implement a basic inventory system with
Map<String, Integer>for stock counts, and a service class that adds/removes items.
Week 3 – Tooling & Ecosystem
- Install Maven (or Gradle) and generate a project with
mvn archetype:generate. - Add a third‑party library (e.g., Jackson) and run a unit test with JUnit 5.
- Explore IDE shortcuts for refactoring, generating getters/setters, and running tests.
- Mini‑project: Extend the inventory system to persist data as JSON using Jackson; write JUnit tests for CRUD operations.
Week 4 – Frameworks & Concurrency
- Scaffold a Spring Boot web app (
spring init) with a single REST controller. - Wire a service bean using
@Serviceand inject it with@Autowired. - Write a simple
ExecutorServicetask that prints timestamps every second. - Capstone project: Create a tiny REST API for the inventory system:
GET /items,POST /items,DELETE /items/{id}. Persist to an in‑memoryConcurrentHashMap. Add a background task that logs inventory size every minute.
FAQ
How do I run a single Java file without a build tool?
Use java with the -source and -target flags (JDK 11+ supports java MyClass.java directly). It compiles and runs in one step, handy for experiments.
Do I need to learn both Maven and Gradle?
Pick one; Maven’s XML is more explicit, Gradle’s Groovy/Kotlin DSL is concise. The concepts (dependencies, plugins, lifecycle) are the same.
Is Java’s performance really better than PHP’s?
For CPU‑bound tasks, the JVM’s JIT compilation and optimized garbage collector usually outperform interpreted PHP. For I/O‑heavy web apps, the difference narrows and depends on architecture.
Can I still use dynamic typing tricks in Java?
Only with reflection or Object types, but they defeat the purpose of static typing and should be avoided in production code.
Keep going
- See what already transfers: take the free PHP → Java readiness check
- Related: Node.js developer learning NestJS: what carries over, what's new, 30-day plan
- Related: Express developer learning NestJS: what carries over, what's new, 30-day plan
Originally published at switchbyskill.com.
