0% found this document useful (0 votes)
3 views35 pages

Java Study Guide

This document is a comprehensive study guide for Java programming, aimed at beginners to intermediate learners, covering core topics such as variables, data types, control flow, loops, arrays, and methods. It explains the fundamentals of Java, including its history, setup, and syntax, while providing practical examples and tips. The guide emphasizes Java's versatility and its importance in the job market, making it a valuable resource for students and professionals alike.

Uploaded by

a.cayal03
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views35 pages

Java Study Guide

This document is a comprehensive study guide for Java programming, aimed at beginners to intermediate learners, covering core topics such as variables, data types, control flow, loops, arrays, and methods. It explains the fundamentals of Java, including its history, setup, and syntax, while providing practical examples and tips. The guide emphasizes Java's versatility and its importance in the job market, making it a valuable resource for students and professionals alike.

Uploaded by

a.cayal03
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JAVA PROGRAMMING
Complete Beginner-to-Intermediate Study Guide

For College Students • Career Changers • IT Professionals

Covers all core topics to get you writing Java code with confidence
1. Introduction to Java

What is Java?
Java is a high-level, object-oriented programming language created by James Gosling at Sun
Microsystems in 1995. Today it is maintained by Oracle. It is one of the most widely used
programming languages in the world, powering Android apps, enterprise software, web
backends, and much more.

💡 TIP Java follows the principle: "Write Once, Run Anywhere" (WORA). This means code you write
on one computer can run on any device that has Java installed.

Why Learn Java?


• One of the top 3 most in-demand programming languages for jobs
• Powers over 3 billion devices worldwide
• Used by Amazon, Google, Netflix, LinkedIn, and most banks
• Strong foundation that makes learning other languages easier
• Massive community and huge library of free tools

How Java Works


Unlike languages like C++, Java does not compile directly into machine code for a specific
computer. Instead, it compiles into a special intermediate format called bytecode. This bytecode
runs inside a program called the Java Virtual Machine (JVM), which translates it for whatever
computer you are on.

Step What Happens File Type


1. You write code Type your program in a .java file .java
2. Compile javac converts it to bytecode .class
3. Run JVM reads bytecode and Runs on JVM
executes it

Setting Up Java
Step 1 – Install the JDK
The Java Development Kit (JDK) includes everything you need: a compiler, the JVM, and
standard libraries.
1. Go to [Link] or use OpenJDK (free)
2. Download and install version 17 or higher (LTS = Long Term Support, most stable)
3. Verify installation — open your terminal and type:
java -version

Step 2 – Choose an Editor / IDE


Tool Best For Cost
VS Code + Extension Pack Beginners, lightweight Free
IntelliJ IDEA Community Most professionals use this Free
Eclipse Common in corporate Free
environments
Notepad++ / TextEdit Quick edits, not recommended for Free
learning

Your First Java Program


Every Java journey starts with Hello World. Here is what it looks like:

// File: [Link]
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}

Part What It Means


public class HelloWorld Declares a class. Every Java program lives inside a
class. The filename must match.
public static void main(String[] args) The entry point. Java always starts running from
main().
[Link](...) Prints a line to the screen.
// comment A single-line comment. Java ignores this — it is for
humans to read.

📝 Java is case-sensitive. 'Main' and 'main' are completely different. Always match
NOTE uppercase/lowercase exactly.
2. Variables and Data Types

What is a Variable?
A variable is a named container that stores a value in memory. Think of it like a labeled box: you
put something inside, give it a name, and use that name whenever you need the value.

int age = 25; // stores a whole number


double price = 9.99; // stores a decimal number
String name = "Alice"; // stores text
boolean isLoggedIn = true; // stores true or false

Primitive Data Types


Java has 8 built-in primitive types. These are the basic building blocks for all data.

Type Stores Size Example


byte Whole numbers −128 to 1 byte byte b = 100;
127
short Whole numbers −32,768 2 bytes short s = 5000;
to 32,767
int Whole numbers (most 4 bytes int x = 42;
common)
long Very large whole 8 bytes long l = 9876543210L;
numbers
float Decimal numbers (less 4 bytes float f = 3.14f;
precise)
double Decimal numbers (most 8 bytes double d = 3.14159;
common)
char A single character 2 bytes char c = 'A';
boolean True or false only 1 bit boolean flag = true;

💡 TIP When in doubt, use int for whole numbers and double for decimals. These are the most
common choices.

Declaring and Initializing Variables


// Declaration only (no value yet)
int score;

// Declaration + initialization (gives it a value right away)


int score = 100;
// You can change the value later
score = 200;

The String Type


String is not a primitive — it is a class. But it is so commonly used that Java gives it special
syntax. A String stores a sequence of characters (text).

String greeting = "Hello";


String name = "Java";

// Combine strings with the + operator (called concatenation)


String message = greeting + ", " + name + "!";
[Link](message); // prints: Hello, Java!

Constants with final


Use the final keyword to create a value that can never change. By convention, constants are
written in ALL_CAPS.

final double PI = 3.14159;


final int MAX_SCORE = 100;

// PI = 3.0; // ERROR! Cannot change a final variable

Type Casting
Sometimes you need to convert a value from one type to another. This is called casting.

// Widening (automatic — no data lost)


int myInt = 9;
double myDouble = myInt; // 9 becomes 9.0 automatically

// Narrowing (manual — you might lose data!)


double pi = 3.99;
int piInt = (int) pi; // becomes 3, decimal part is dropped

⚠️ Narrowing cast (e.g., double to int) simply cuts off the decimal — it does NOT round. 3.99
WAR becomes 3, not 4.
N
User Input with Scanner
To read input from the keyboard, use the Scanner class from Java's built-in library.

import [Link]; // import at the top of your file

public class InputExample {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter your name: ");


String name = [Link]();

[Link]("Enter your age: ");


int age = [Link]();

[Link]("Hello, " + name + "! You are " + age + " years old.");
[Link]();
}
}

Scanner Method Reads


[Link]() A full line of text
[Link]() One word (stops at space)
[Link]() A whole number
[Link]() A decimal number
[Link]() A boolean (true/false)
3. Operators

Arithmetic Operators
Used to perform math calculations.

Operator Name Example Result


+ Addition 5+3 8
- Subtraction 5-3 2
* Multiplication 5*3 15
/ Division 10 / 3 3 (integer division!)
% Modulus (remainder) 10 % 3 1
++ Increment x++ adds 1 to x
-- Decrement x-- subtracts 1 from x

📝 Integer division in Java drops the decimal. 10 / 3 = 3, not 3.33. To get 3.33, at least one
NOTE number must be a double: 10.0 / 3 = 3.33.

Comparison (Relational) Operators


These return true or false and are used in conditions.

Operator Meaning Example Result


== Equal to 5 == 5 true
!= Not equal to 5 != 3 true
> Greater than 7>3 true
< Less than 2<5 true
>= Greater than or equal to 5 >= 5 true
<= Less than or equal to 3 <= 4 true

⚠️ Use == to compare primitive types (int, boolean, etc.). For Strings and objects, use .equals()
WAR instead: [Link]("Alice")
N

Logical Operators
Combine multiple conditions together.
Operator Name Meaning Example
&& AND Both conditions must be age > 18 && hasID ==
true true
|| OR At least one must be isAdmin || isModerator
true
! NOT Reverses the boolean !isLoggedIn
result

int age = 20;


boolean hasTicket = true;

if (age >= 18 && hasTicket) {


[Link]("Welcome in!");
}

Assignment Operators
Operator Same As Example Meaning
= — x=5 Assign 5 to x
+= x=x+n x += 3 Add 3 to x
-= x=x-n x -= 2 Subtract 2 from x
*= x=x*n x *= 4 Multiply x by 4
/= x=x/n x /= 2 Divide x by 2
%= x=x%n x %= 3 Remainder of x / 3
4. Control Flow — Making Decisions

if / else if / else
Use if statements to run code only when certain conditions are true.

int score = 85;

if (score >= 90) {


[Link]("Grade: A");
} else if (score >= 80) {
[Link]("Grade: B");
} else if (score >= 70) {
[Link]("Grade: C");
} else {
[Link]("Grade: F");
}

switch Statement
When you need to compare a single value against many specific options, switch is cleaner than
many if-else chains.

int day = 3;

switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
default:
[Link]("Other day");
}

⚠️ Always add break; at the end of each case, or execution will "fall through" and run the next
WAR case too.
N
Ternary Operator
A shorthand for simple if-else statements on one line.

// Syntax: condition ? valueIfTrue : valueIfFalse


int age = 20;
String status = (age >= 18) ? "Adult" : "Minor";
[Link](status); // prints: Adult
5. Loops — Repeating Actions
Loops let you repeat a block of code multiple times without rewriting it. There are three main
types in Java.

for Loop
Use when you know exactly how many times to repeat something.

// Syntax: for (start; condition; update)


for (int i = 1; i <= 5; i++) {
[Link]("Count: " + i);
}
// Output: Count: 1, Count: 2, Count: 3, Count: 4, Count: 5

Part Meaning
int i = 1 Start: create a counter variable and set it to 1
i <= 5 Condition: keep looping while i is 5 or less
i++ Update: after each loop, add 1 to i

while Loop
Use when you do not know in advance how many times to repeat — you keep looping until a
condition becomes false.

int count = 1;

while (count <= 5) {


[Link]("Count: " + count);
count++; // important! without this, infinite loop
}

do-while Loop
Like while, but it always runs the code at least once before checking the condition.

int number;
Scanner sc = new Scanner([Link]);

do {
[Link]("Enter a positive number: ");
number = [Link]();
} while (number <= 0); // repeats until user enters a positive number

[Link]("You entered: " + number);

Loop Control: break and continue


Keyword What it does
break Exits the loop immediately
continue Skips the rest of the current iteration, moves to the
next

for (int i = 1; i <= 10; i++) {


if (i == 5) continue; // skip 5
if (i == 8) break; // stop at 8
[Link](i + " ");
}
// Output: 1 2 3 4 6 7

Nested Loops
You can put loops inside other loops. This is common for working with grids, tables, and multi-
dimensional data.

for (int row = 1; row <= 3; row++) {


for (int col = 1; col <= 3; col++) {
[Link](row + "," + col + " ");
}
[Link](); // new line after each row
}
// Output:
// 1,1 1,2 1,3
// 2,1 2,2 2,3
// 3,1 3,2 3,3
6. Arrays

What is an Array?
An array is a container that holds a fixed number of values of the same type. Instead of creating
ten separate variables for ten scores, you create one array that holds all ten.

// Declare and initialize an array of 5 integers


int[] scores = {90, 85, 78, 92, 88};

// Access elements using index (starts at 0!)


[Link](scores[0]); // 90
[Link](scores[4]); // 88

// Change a value
scores[2] = 95;

// Get the length of the array


[Link]([Link]); // 5

⚠️ Array indexes start at 0, not 1. An array of size 5 has indexes 0, 1, 2, 3, 4. Accessing index 5
WAR causes an ArrayIndexOutOfBoundsException.
N

Looping Through Arrays


String[] fruits = {"Apple", "Banana", "Cherry"};

// Using a traditional for loop


for (int i = 0; i < [Link]; i++) {
[Link](fruits[i]);
}

// Using an enhanced for loop (for-each) — simpler!


for (String fruit : fruits) {
[Link](fruit);
}

2D Arrays
A 2D array is an array of arrays — think of it like a table with rows and columns.
int[][] grid = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

[Link](grid[1][2]); // row 1, column 2 = 6

// Loop through all elements


for (int row = 0; row < [Link]; row++) {
for (int col = 0; col < grid[row].length; col++) {
[Link](grid[row][col] + " ");
}
[Link]();
}

Useful Array Operations


import [Link];

int[] nums = {5, 2, 8, 1, 9, 3};

[Link](nums); // sorts in ascending order


[Link]([Link](nums)); // prints: [1, 2, 3, 5, 8, 9]

int[] copy = [Link](nums, [Link]); // makes a copy


7. Methods (Functions)

What is a Method?
A method is a reusable block of code that performs a specific task. Instead of writing the same
code over and over, you define it once as a method and call it whenever you need it.

Anatomy of a Method
// access return name parameters
public int add (int a, int b) {
return a + b; // return sends a value back to the caller
}

Part Meaning
public Access modifier — who can use this method
int Return type — what kind of value it sends back (use
void if nothing)
add Method name — use camelCase by convention
(int a, int b) Parameters — inputs the method receives
return a + b Returns the result to wherever the method was
called

void Methods
Use void when the method does something (like printing) but does not return a value.

public static void greet(String name) {


[Link]("Hello, " + name + "!");
}

// Calling the method:


greet("Alice"); // prints: Hello, Alice!
greet("Bob"); // prints: Hello, Bob!

Methods with Return Values


public static int multiply(int x, int y) {
return x * y;
}
public static double circleArea(double radius) {
return [Link] * radius * radius;
}

// Using the return values:


int result = multiply(4, 5); // result = 20
double area = circleArea(3.0); // area ≈ 28.27

Method Overloading
You can have multiple methods with the same name, as long as they have different parameters.
Java picks the right one automatically.

public static int add(int a, int b) {


return a + b;
}

public static double add(double a, double b) {


return a + b;
}

public static int add(int a, int b, int c) {


return a + b + c;
}

[Link](add(2, 3)); // uses first: 5


[Link](add(2.5, 3.1)); // uses second: 5.6
[Link](add(1, 2, 3)); // uses third: 6

Scope
Variables declared inside a method only exist inside that method. This is called local scope.
They disappear when the method ends.

public static void exampleScope() {


int localVar = 10; // only exists inside this method
[Link](localVar);
}

// [Link](localVar); // ERROR! localVar doesn't exist here

💡 TIP Keep methods short and focused on doing ONE thing. If a method is getting very long, break
it into smaller helper methods.
8. Object-Oriented Programming (OOP)

What is OOP?
Object-Oriented Programming is a way of writing programs by modeling real-world things as
"objects". Each object has data (attributes/fields) and behaviors (methods). Java is built around
OOP — everything in Java lives inside a class.

Real World In Java


Blueprint / Template Class
A specific thing Object (instance)
Properties of a thing Fields (variables inside the class)
What a thing can do Methods (functions inside the class)

Classes and Objects


// Define the class (blueprint)
public class Car {
// Fields (attributes)
String brand;
String color;
int year;

// Constructor — runs when you create a new Car


public Car(String brand, String color, int year) {
[Link] = brand;
[Link] = color;
[Link] = year;
}

// Method (behavior)
public void describe() {
[Link](year + " " + color + " " + brand);
}
}

// Create objects from the class


Car myCar = new Car("Toyota", "Blue", 2022);
Car yourCar = new Car("Honda", "Red", 2020);

[Link](); // 2022 Blue Toyota


[Link](); // 2020 Red Honda
The Four Pillars of OOP

1. Encapsulation
Keep data private and only allow access through methods. This protects your data from being
changed in unexpected ways.

public class BankAccount {


private double balance; // private = only this class can touch it

public BankAccount(double initialBalance) {


[Link] = initialBalance;
}

public void deposit(double amount) {


if (amount > 0) balance += amount;
}

public double getBalance() { // getter


return balance;
}
}

2. Inheritance
A child class can inherit fields and methods from a parent class. This promotes code reuse. Use
the extends keyword.

// Parent class
public class Animal {
String name;
public void eat() {
[Link](name + " is eating.");
}
}

// Child class inherits from Animal


public class Dog extends Animal {
public void bark() {
[Link](name + " says: Woof!");
}
}
Dog dog = new Dog();
[Link] = "Rex";
[Link](); // inherited from Animal: Rex is eating.
[Link](); // Dog's own method: Rex says: Woof!

3. Polymorphism
One interface, many forms. A child class can override a parent method to provide its own
specific behavior. Java automatically calls the right version.

public class Shape {


public void draw() {
[Link]("Drawing a shape");
}
}

public class Circle extends Shape {


@Override
public void draw() {
[Link]("Drawing a circle");
}
}

public class Square extends Shape {


@Override
public void draw() {
[Link]("Drawing a square");
}
}

Shape s1 = new Circle();


Shape s2 = new Square();
[Link](); // Drawing a circle
[Link](); // Drawing a square

4. Abstraction
Hide the complex implementation details and show only what is necessary. Use abstract
classes or interfaces.

// Abstract class — cannot be instantiated directly


public abstract class Vehicle {
public abstract void move(); // must be implemented by subclasses
public void stop() {
[Link]("Stopping...");
}
}

public class Bicycle extends Vehicle {


@Override
public void move() {
[Link]("Pedaling forward");
}
}

Interfaces
An interface is a contract. It defines what methods a class must have, but not how they work. A
class implements an interface using the implements keyword.

public interface Flyable {


void fly(); // no body — just the contract
}

public class Bird implements Flyable {


@Override
public void fly() {
[Link]("Bird flapping wings");
}
}

public class Airplane implements Flyable {


@Override
public void fly() {
[Link]("Airplane using jet engines");
}
}

💡 TIP Difference: A class can only extend ONE class (single inheritance), but it can implement
MULTIPLE interfaces. Use interfaces when unrelated classes share a capability.
9. Working with Strings

Common String Methods


The String class comes with many built-in methods. Here are the most useful ones:

String s = "Hello, Java World!";

[Link]() // 18
[Link]() // HELLO, JAVA WORLD!
[Link]() // hello, java world!
[Link]() // removes leading/trailing spaces
[Link](0) // 'H' — character at index 0
[Link]("Java") // 7 — position where 'Java' starts
[Link]("World") // true
[Link]("Hello") // true
[Link]("!") // true
[Link](7, 11) // "Java" — from index 7 to 11 (exclusive)
[Link]("Java", "Python") // "Hello, Python World!"
[Link](", ") // ["Hello", "Java World!"]

String Comparison
String a = "hello";
String b = "hello";
String c = "HELLO";

// == compares references (memory location) — can give wrong results for Strings
[Link](a == b); // might be true or false!

// .equals() compares actual content — always use this


[Link]([Link](b)); // true
[Link]([Link](c)); // true (ignores case)
[Link]([Link](b)); // 0 (equal)

StringBuilder — Efficient String Building


If you need to build a string piece by piece in a loop, use StringBuilder instead of regular String
concatenation. It is much faster.

StringBuilder sb = new StringBuilder();


for (int i = 1; i <= 5; i++) {
[Link]("Item ").append(i).append("\n");
}

[Link]([Link]());
// Item 1
// Item 2 ... etc.

String Formatting
String name = "Alice";
int age = 25;
double gpa = 3.85;

// [Link]() — like a template


String info = [Link]("Name: %s, Age: %d, GPA: %.2f", name, age, gpa);
[Link](info); // Name: Alice, Age: 25, GPA: 3.85

// Shortcut: printf prints directly


[Link]("Name: %s, Age: %d%n", name, age);

Format Code Stands For Example Output


%s String Alice
%d Integer (decimal) 25
%f Float/Double 3.850000
%.2f 2 decimal places 3.85
%n New line (line break)
%10s Right-align, 10 wide Alice
10. Collections (ArrayList, HashMap & More)

Why Collections?
Arrays have a fixed size — you must decide upfront how many elements to store. Collections
solve this by being resizable and offering many built-in operations. They live in the [Link]
package.

ArrayList
An ArrayList is like an array but it grows and shrinks automatically. It stores objects, not
primitives (use Integer instead of int, Double instead of double, etc.).

import [Link];

ArrayList<String> names = new ArrayList<>();

[Link]("Alice"); // add to end


[Link]("Bob");
[Link]("Charlie");
[Link](1, "Dave"); // add at index 1

[Link](names); // [Alice, Dave, Bob, Charlie]


[Link]([Link](0)); // Alice
[Link]([Link]()); // 4
[Link]([Link]("Bob")); // true

[Link]("Bob"); // remove by value


[Link](0); // remove by index

// Loop through
for (String name : names) {
[Link](name);
}

HashMap
A HashMap stores key-value pairs, like a dictionary. You look up a value by its key. Keys must
be unique.

import [Link];
HashMap<String, Integer> scores = new HashMap<>();

[Link]("Alice", 95);
[Link]("Bob", 88);
[Link]("Carol", 91);

[Link]([Link]("Alice")); // 95
[Link]([Link]("Bob")); // true
[Link]([Link]()); // 3

[Link]("Bob");

// Loop through all entries


for (String key : [Link]()) {
[Link](key + ": " + [Link](key));
}

Quick Comparison of Common Collections


Collection Ordered? Duplicates? Key-Value? Use When...
ArrayList Yes Yes No You need an
ordered, resizable
list
LinkedList Yes Yes No Frequent
add/remove at
beginning
HashSet No No No You need unique
values, fast lookup
HashMap No Keys unique Yes You need fast
lookup by key
TreeMap Yes (sorted) Keys unique Yes You need keys in
sorted order

Sorting Collections
import [Link];

ArrayList<Integer> nums = new ArrayList<>();


[Link](5); [Link](1); [Link](3);

[Link](nums); // [1, 3, 5]
[Link](nums, [Link]()); // [5, 3, 1]
[Link](nums); // random order
11. Exception Handling

What is an Exception?
An exception is an error that occurs while your program is running — not during compilation. If
not handled, it crashes your program. Java gives you tools to catch these errors gracefully and
respond to them.

Common Exception When it Happens


NullPointerException You use an object that has not been created (is null)
ArrayIndexOutOfBoundsException You access an array index that does not exist
NumberFormatException You try to convert a non-number String to a number
ArithmeticException Math error like dividing by zero
ClassCastException Invalid type conversion at runtime
StackOverflowError Infinite recursion (method calls itself forever)

try-catch-finally
Wrap risky code in a try block. If an exception occurs, Java jumps to the catch block. The finally
block always runs, whether there was an error or not.

try {
int result = 10 / 0; // ArithmeticException!
[Link](result);
} catch (ArithmeticException e) {
[Link]("Error: " + [Link]());
} finally {
[Link]("This always runs.");
}

// Output:
// Error: / by zero
// This always runs.

Multiple catch Blocks


public static void riskyMethod(String input) {
try {
int number = [Link](input); // might throw NumberFormatException
int result = 100 / number; // might throw ArithmeticException
[Link]("Result: " + result);
} catch (NumberFormatException e) {
[Link]("Not a valid number: " + input);
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero!");
} catch (Exception e) {
[Link]("Unknown error: " + [Link]());
}
}

Throwing Exceptions
You can also throw your own exceptions to signal that something is wrong.

public static void setAge(int age) {


if (age < 0 || age > 150) {
throw new IllegalArgumentException("Age must be between 0 and 150");
}
[Link]("Age set to: " + age);
}

setAge(25); // Age set to: 25


setAge(-5); // throws IllegalArgumentException

💡 TIP Rule of thumb: catch exceptions you can actually handle and recover from. Let unexpected
ones propagate so you can see what went wrong.
12. File Input & Output

Reading a File
Java provides several ways to read files. The most straightforward for beginners is
BufferedReader with FileReader.

import [Link].*;

public class ReadFile {


public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new
FileReader("[Link]"))) {
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
} catch (IOException e) {
[Link]("Error reading file: " + [Link]());
}
}
}

Writing to a File
import [Link].*;

public class WriteFile {


public static void main(String[] args) {
try (BufferedWriter writer = new BufferedWriter(new
FileWriter("[Link]"))) {
[Link]("Hello from Java!");
[Link]();
[Link]("Second line here.");
} catch (IOException e) {
[Link]("Error writing file: " + [Link]());
}
}
}

// To APPEND to an existing file (instead of overwriting), pass true:


new FileWriter("[Link]", true)
📝 The try-with-resources syntax (try (...) { }) automatically closes the file when done. Always use
NOTE this — forgetting to close files causes bugs.

Modern Way: Files Class (Java 7+)


import [Link].*;
import [Link];

// Read all lines at once


List<String> lines = [Link]([Link]("[Link]"));
for (String line : lines) {
[Link](line);
}

// Write all lines at once


List<String> content = [Link]("Line 1", "Line 2", "Line 3");
[Link]([Link]("[Link]"), content);
13. Generics, Enums & Records

Generics
Generics let you write code that works with any data type while still being type-safe. You have
already used them with ArrayList<String> and HashMap<String, Integer>.

// A generic method that works with any type T


public static <T> void printArray(T[] array) {
for (T element : array) {
[Link](element + " ");
}
[Link]();
}

Integer[] ints = {1, 2, 3};


String[] strings = {"A", "B", "C"};

printArray(ints); // 1 2 3
printArray(strings); // A B C

Enums (Enumerations)
An enum is a special type for a fixed set of named constants. They make your code more
readable and prevent invalid values.

public enum Day {


MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

Day today = [Link];

if (today == [Link] || today == [Link]) {


[Link]("It is the weekend!");
} else {
[Link]("It is a weekday.");
}

// Enums work great in switch


switch (today) {
case MONDAY: [Link]("Start of the week"); break;
case FRIDAY: [Link]("TGIF!"); break;
default: [Link]("Midweek");
}

Records (Java 14+)


Records are a quick way to create simple data-holding classes. Java automatically generates
the constructor, getters, equals(), hashCode(), and toString() for you.

// Old way — lots of boilerplate


// public class Point { private int x; private int y; getX()... getY()... }

// New way — record does it all


public record Point(int x, int y) {}

Point p = new Point(3, 7);


[Link](p.x()); // 3
[Link](p.y()); // 7
[Link](p); // Point[x=3, y=7]
14. Coding Best Practices & Style Guide

Naming Conventions
What Convention Example
Class names PascalCase BankAccount, StudentRecord
Method names camelCase calculateTotal(), getName()
Variable names camelCase totalScore, firstName
Constants UPPER_SNAKE MAX_SIZE,
DEFAULT_TAX_RATE
Package names all lowercase [Link]

Key Rules for Clean Code


• Write code that reads like plain English — names should explain what they do
• One method should do one thing — if a method is very long, break it up
• Avoid "magic numbers" — use named constants instead of random numbers in code
• Handle exceptions — never let your program crash without a reason
• Comment the WHY, not the WHAT — good code is self-explanatory; comments explain
reasoning
• Keep nesting shallow — deeply nested if/loop structures are hard to read

// BAD — magic number, unclear name


if (x > 86400) { reward(); }

// GOOD — clear constant, readable condition


final int SECONDS_PER_DAY = 86400;
if (elapsedSeconds > SECONDS_PER_DAY) {
giveDaily Reward();
}

The DRY Principle


DRY = Don't Repeat Yourself. If you write the same code in two places, pull it out into a method.
This makes bugs easier to fix — you only need to fix it in one place.

Debugging Tips
• Read the error message carefully — it tells you the exception type and line number
• Use [Link]() to print variable values and trace your program's flow
• Use your IDE's built-in debugger — set breakpoints and step through code line by line
• Isolate the problem — comment out sections to find the one that is failing
• Search the exact error message online — you are never the first person to see it

Java Project Structure


MyProject/
├── src/
│ └── com/
│ └── myapp/
│ ├── [Link] (entry point)
│ ├── models/
│ │ └── [Link]
│ └── utils/
│ └── [Link]
├── test/
│ └── com/
│ └── myapp/
│ └── [Link]
└── [Link]
15. What to Learn Next

Immediate Next Steps (Weeks 2–4)


4. Practice every topic in this guide by writing small programs from scratch
5. Solve problems on [Link] (Java track) or LeetCode (Easy level)
6. Build a small project: a calculator, a to-do list app, or a simple quiz game
7. Learn how to use Git for version control (industry essential)

Intermediate Topics (Months 1–3)


Topic What it Adds
Lambda expressions Write shorter, functional-style code (Java 8+)
Streams API Process collections in a powerful, concise way
Maven / Gradle Build tools for managing your project and
dependencies
Unit testing (JUnit 5) Write tests so your code does not break
unexpectedly
Java Optional Safely handle null values without
NullPointerException
Concurrency / Threads Write programs that do multiple things at the same
time

Career Paths Using Java


Career Java's Role Related Technologies
Backend Web Developer Spring Boot, REST APIs SQL, Docker, AWS
Android Developer Android SDK / Kotlin XML layouts, Firebase
Enterprise Software Engineer Spring, microservices Kubernetes, Kafka
Data Engineer Spark, Hadoop Python, SQL, Scala
DevOps / Cloud Engineer Build tools, automation Jenkins, Terraform

Recommended Free Resources


• Official Java Tutorial — [Link]/javase/tutorial
• W3Schools Java — [Link]/java (quick reference)
• Codecademy Java course — [Link] (interactive)
• Java Brains (YouTube) — deep dives into OOP and Spring
• "Head First Java" by Kathy Sierra — best beginner book
• "Clean Code" by Robert C. Martin — essential for professionals
💡 TIP The most important step is to WRITE CODE every day. Even 30 minutes of practice is more
valuable than hours of reading. Build projects you actually care about — you will learn much
faster.

Happy coding! ☕

You might also like