Complete Java Programming Guide
Read on to explore complete java programming guide — a beginner-friendly walkthrough by Codekilla.
Java is a high-level, object-oriented programming language that lets you write code once and run it anywhere—from smartphones to enterprise servers. Created by Sun Microsystems in 1995 (now owned by Oracle), Java compiles to bytecode that runs on the Java Virtual Machine (JVM), making your programs platform-independent. You write .java files, compile them into .class bytecode, and the JVM handles the rest. Think of Java as the universal translator of the programming world: write on Windows, deploy on Linux, run on Mac—no rewriting needed.
Java powers Android apps, backend systems at Netflix and Amazon, financial trading platforms, and even spacecraft software. It's statically typed, meaning you declare variable types explicitly, and it's garbage-collected, so you don't manually manage memory like in C++. If you've heard of Kotlin, Scala, or Groovy, those languages also run on the JVM, sharing Java's ecosystem.
- Industry Dominance: Java ranks among the top 3 most-used languages globally, with millions of developers and a massive job market.
- Android Development: Nearly all Android apps use Java or Kotlin (which interoperates with Java), reaching billions of devices.
- Enterprise Backbone: Banks, insurance firms, and Fortune 500 companies rely on Java for mission-critical systems because of its stability and scalability.
- Rich Ecosystem: Libraries and frameworks like Spring Boot, Hibernate, and Apache Kafka solve real problems out-of-the-box.
- Learning Foundation: Mastering Java teaches you object-oriented principles that translate directly to C#, C++, and other OOP languages.
Java's syntax resembles C++ but removes pointers and manual memory management. Every application starts with a main method inside a class. Here's the canonical "Hello, World!" that demonstrates the basic structure:
javapublic class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } }
You save this as HelloWorld.java (filename MUST match the public class name), compile with javac HelloWorld.java, then run java HelloWorld. The public static void main(String[] args) signature is mandatory—public makes it accessible to the JVM, static means you don't need an object instance, and String[] args captures command-line arguments.
Java enforces OOP through classes and objects. You model real-world entities as classes (blueprints) and create objects (instances) from them. The four pillars are Encapsulation, Inheritance, Polymorphism, and Abstraction.
Encapsulation hides internal state using private fields and exposes controlled access via public getters/setters. Inheritance lets child classes extend parent classes with extends, reusing code. Polymorphism allows objects to take multiple forms—a Dog and Cat can both be treated as Animal. Abstraction uses interfaces and abstract classes to define contracts without implementation details.
javapublic class BankAccount { private double balance; public BankAccount(double initialBalance) { this.balance = initialBalance; } public void deposit(double amount) { if (amount > 0) { balance += amount; } } public double getBalance() { return balance; } }
This class encapsulates balance—you can't access it directly from outside, only through deposit() and getBalance(). The constructor BankAccount(double initialBalance) initializes the object when you create it with new BankAccount(100.0).
Java has two categories of types: primitives (stored directly in memory) and reference types (point to objects). Primitives include int, double, boolean, char, long, float, short, and byte. Reference types are classes, interfaces, and arrays.
| Primitive | Size | Example | Use Case |
|---|---|---|---|
int | 32-bit | int age = 25; | Whole numbers (most common) |
double | 64-bit | double price = 19.99; | Decimal numbers |
boolean | 1-bit | boolean isActive = true; | True/false flags |
char | 16-bit | char grade = 'A'; | Single characters |
String | Reference | String name = "Alice"; | Text (technically a class) |
You declare variables with type name = value;. Java is strongly typed—once you declare int count, you can't assign "hello" to it. Use final to create constants: final double PI = 3.14159; prevents reassignment.
javaint studentCount = 30; double averageScore = 87.5; boolean isPassing = averageScore >= 60; String courseName = "Java Fundamentals";
Control flow determines execution order. If-else statements handle branching logic, switch statements match values, and loops repeat code blocks.
javapublic class GradeCalculator { public static String getLetterGrade(int score) { if (score >= 90) { return "A"; } else if (score >= 80) { return "B"; } else if (score >= 70) { return "C"; } else if (score >= 60) { return "D"; } else { return "F"; } } public static void main(String[] args) { // For loop: iterate fixed number of times for (int i = 0; i < 5; i++) { System.out.println("Iteration: " + i); } // While loop: condition-based repetition int countdown = 3; while (countdown > 0) { System.out.println(countdown); countdown--; } // Enhanced for-each loop String[] subjects = {"Math", "Science", "History"}; for (String subject : subjects) { System.out.println(subject); } } }
Modern Java (14+) introduced switch expressions that return values directly, eliminating break statements and making code cleaner.
Collections store groups of objects. The main interfaces are List (ordered), Set (unique elements), and Map (key-value pairs). You use implementations like ArrayList, HashSet, and HashMap instead of arrays for dynamic sizing.
| Collection | Ordered? | Duplicates? | Best For |
|---|---|---|---|
ArrayList | Yes | Yes | Fast random access |
LinkedList | Yes | Yes | Frequent insertions/deletions |
HashSet | No | No | Unique elements, fast lookup |
HashMap | No (keys) | No (keys) | Key-value storage |
javaimport java.util.ArrayList; import java.util.HashMap; public class CollectionsDemo { public static void main(String[] args) { // ArrayList: dynamic array ArrayList<String> tasks = new ArrayList<>(); tasks.add("Code review"); tasks.add("Write tests"); tasks.add("Deploy"); for (String task : tasks) { System.out.println("TODO: " + task); } // HashMap: key-value pairs HashMap<String, Integer> scores = new HashMap<>(); scores.put("Alice", 95); scores.put("Bob", 87); scores.put("Charlie", 92); System.out.println("Bob's score: " + scores.get("Bob")); } }
Use generics (<String>, <Integer>) to enforce type safety—an ArrayList<String> can't accidentally hold integers.
Exceptions are runtime errors that disrupt normal flow. Java forces you to handle checked exceptions (like IOException) with try-catch blocks or declare them with throws. Unchecked exceptions (like NullPointerException) inherit from RuntimeException and don't require explicit handling.
javaimport java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class FileReader { public static void readFile(String filename) { try { File file = new File(filename); Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { System.out.println(scanner.nextLine()); } scanner.close(); } catch (FileNotFoundException e) { System.out.println("Error: File not found - " + filename); } finally { System.out.println("Cleanup code runs regardless"); } } }
The finally block always executes, making it perfect for closing resources. Modern Java (7+) offers try-with-resources that auto-closes resources: try (Scanner sc = new Scanner(file)) { ... }.
Java 8 introduced Streams API for functional-style data processing and lambda expressions for concise anonymous functions. Streams let you filter, map, and reduce collections without explicit loops.
javaimport java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class StreamExample { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // Filter even numbers, square them, collect to list List<Integer> evenSquares = numbers.stream() .filter(n -> n % 2 == 0) .map(n -> n * n) .collect(Collectors.toList()); System.out.println(evenSquares); // [4, 16, 36, 64, 100] // Sum with reduce int sum = numbers.stream() .reduce(0, (a, b) -> a + b); System.out.println("Sum: " + sum); // 55 } }
The arrow -> defines lambdas: n -> n % 2 == 0 is shorthand for "take n, return true if even." Streams are lazy—operations don't execute until you call a terminal operation like collect().
| Need | Reach For |
|---|---|
| Store ordered items | ArrayList<T> |
| Ensure uniqueness | HashSet<T> |
| Key-value lookup | HashMap<K, V> |
| Handle errors | try-catch or throws |
| Process collections functionally | Streams + lambdas |
| Read/write files | java.nio.file.Files |
| Build web APIs | Spring Boot framework |
| Connect to databases | JDBC or Hibernate ORM |
| Multi-threading | ExecutorService or CompletableFuture |
- Forgetting
newfor objects: WritingScanner scanner = Scanner(System.in);instead ofnew Scanner(System.in)causes compile errors. Primitives don't neednew, but objects do. - Comparing strings with
==: This checks reference equality, not content. Always use.equals()for string comparison:if (name.equals("Alice")). - Not closing resources: Forgetting to close
Scanner,FileReader, or database connections causes memory leaks. Use try-with-resources to auto-close. - Mutating during iteration: Modifying an
ArrayListwhile looping withfor-eachthrowsConcurrentModificationException. Use an iterator orremoveIf(). - Ignoring null checks: Calling methods on
nullreferences triggersNullPointerException. Useif (obj != null)or Java 8'sOptional<T>. - Mixing static and instance contexts: Trying to access instance variables from
staticmethods fails because static belongs to the class, not objects. Either make the method non-static or the variable static.
💡 Think Like a Programmer: Java's verbosity teaches you discipline—explicit types, checked exceptions, and OOP structure force you to plan before coding. Once you master Java's patterns, other languages feel like dialects of the same core concepts.
Keep Reading
Search Engine Working: Crawler, Sitemap & robots.txt
Read on to explore search engine working: crawler, sitemap & robots.txt — a beginner-friendly walkthrough by Codekilla.
VS Code Shortcut Keys (Complete List)
Read on to explore vs code shortcut keys (complete list) — a beginner-friendly walkthrough by Codekilla.
What is Elementor? Complete Beginner Guide
Read on to explore what is elementor? complete beginner guide — a beginner-friendly walkthrough by Codekilla.
