githubEdit

Java OOPs

Here is a Java OOPs Revision Guide: Part 1 focused on the absolute fundamentals: Syntax, Classes, and Objects.

Since you are new to Java, think of this as your "Cheat Sheet" to understand how a Java file is structured and how to bring your code to life.

Part 1


1. The Core Concept: Class vs. Object

Before writing code, you must understand the mental model.

  • Class (The Blueprint): A logical template. It defines what data and actions an entity will have, but it doesn't occupy memory for data yet.

  • Object (The House): A physical instance of the class. It occupies memory and holds actual data. You can build thousands of objects from one class.

Analogy:

  • Class: The recipe for a Chocolate Cake.

  • Object: The actual cake sitting on your table.


2. The Anatomy of a Java Class

Every Java class follows a specific structure. Here is the skeleton syntax you need to memorize.

Java

// 1. Package Declaration (Optional but recommended)
package com.myapp.basics; 

// 2. Imports (Bringing in other tools)
import java.util.Scanner; 

// 3. Class Declaration (PascalCase)
public class Student { 

    // 4. Fields / Attributes (State) -> camelCase
    String name;  
    int age;      

    // 5. Methods (Behavior) -> camelCase
    public void study() {
        System.out.println(name + " is studying.");
    }
}

3. Constructors: The "Setup" Method

When you create an object, you often want to set it up immediately (e.g., giving a Student a name). This is done using a Constructor.

  • Rule 1: Must have the exact same name as the class.

  • Rule 2: Must not have a return type (not even void).

  • Rule 3: It runs automatically when you use the new keyword.

Java


4. The this Keyword

This is a reference variable that points to the current object. It is mostly used to resolve naming conflicts when your parameter name is the same as your field name.

Java


5. Creating Objects (The new Keyword)

To use a class, you must instantiate it in a main method.

Syntax:

ClassName objectName = new Constructor();

  • ClassName: The type of variable.

  • objectName: The reference variable name (like a remote control).

  • =: Assignment operator.

  • new: The magic keyword that allocates memory in the heap.

  • Constructor(): Initializes the object.


6. Static vs. Non-Static (Instance)

This is often the most confusing part for beginners.

  • Instance (Non-Static): Belongs to the Object. Every object has its own copy.

    • Example: eyeColor. Your eye color is unique to you.

  • Static: Belongs to the Class. All objects share one single copy.

    • Example: populationCount. If a baby is born, the count goes up for everyone.

Java


7. Putting It All Together: A "SmartPhone" Example

Here is a complete, runnable code block combining everything above.

Java

Quick Syntax Cheat Sheet

Action

Syntax

Define Class

class Name { ... }

Create Object

Name obj = new Name();

Constructor

public Name() { ... } (No return type!)

Access Method

obj.methodName();

Access Field

obj.fieldName;

Refer to self

this.variableName

Shared Data

static int variableName

Part 2

These are often where beginners face their first "gotchas" (like index errors or string comparison issues), so I will highlight those specifically.


1. Java Arrays

"The Fixed Container"

An Array is a container object that holds a fixed number of values of a single type. Once you create an array with a specific size (e.g., 5 slots), you cannot change its size.

  • Key Characteristic: Fixed Size.

  • Indexing: Starts at 0 (not 1). The last index is length - 1.

  • Performance: Very fast access if you know the index.

A. Syntax & Creation

There are two main ways to create an array.

Method 1: Declaration + Memory Allocation (Empty)

Use this when you know how many items you need, but not what they are yet.

Java

Method 2: Initialization (Filled)

Use this when you already know the values.

Java

B. Iterating (Looping)

You will almost always use a loop to go through an array.

Java

C. The "Gotcha": ArrayIndexOutOfBoundsException

This is the most common error. It happens if you try to access a slot that doesn't exist.

Java


2. Java Strings

"The Immutable Text"

In Java, a String is an Object, not a primitive type (like int or char). This means it has methods you can call.

  • Key Characteristic: Immutability. Once a String object is created, it cannot be changed. If you "modify" a string, Java actually creates a generic new string in memory and discards the old one.

A. Creation: Literal vs. New

How you create a string matters for memory.

  1. String Literal (Recommended): Uses the "String Constant Pool" to save memory. If you write "Hello" twice, Java reuses the same object.

    Java

  2. New Keyword: Forces a new object in Heap memory every time.

    Java

B. The Comparison Trap (== vs .equals())

This is the #1 interview question for beginners.

  • ==: Compares references (memory addresses). "Are these the exact same object?"

  • .equals(): Compares content (values). "Do these hold the same text?"

Java

C. Essential String Methods

You don't need to memorize all of them, but these 5 are essential:

  1. length(): Returns the count of characters.

  2. charAt(index): Returns the character at a specific position.

  3. substring(start, end): Extracts a portion of the text.

  4. toLowerCase() / toUpperCase(): Changes case.

  5. trim(): Removes whitespace from start and end.


3. Practical Revision: A "Student Database" Code

Here is a single program combining Arrays and Strings to simulate a mini-database.

Java

Quick Syntax Cheat Sheet

Action

Syntax/Method

Note

Create Array

int[] arr = new int[5];

Size is fixed at 5.

Get Array Size

arr.length

It's a property (no parenthesis).

Get String Size

str.length()

It's a method (needs parenthesis).

Compare Strings

str1.equals(str2)

NEVER use == for text content.

Get Char

str.charAt(0)

Gets the first letter.

Get Substring

str.substring(0, 3)

Gets index 0, 1, and 2 (3 is exclusive).

Part 3

Here is Java OOPs Revision Guide: Part 3, covering Methods (the behavior) and Control Flow (the logic).

This is where your static code starts to actually do things.


1. Java Methods

"The Verbs"

A method is a block of code that runs only when it is called. You use methods to break a complex problem into small, manageable chunks (like "login", "calculateTotal", "printReceipt").

A. The Anatomy of a Method

You need to memorize this signature structure:

AccessModifier ReturnType MethodName(Parameters) { Body }

  • Access Modifier: public (everyone can see), private (only this class), etc.

  • Return Type: The data type the method gives back (e.g., int, String). Use void if it gives back nothing.

  • Method Name: camelCase (e.g., calculateTax).

  • Parameters: Inputs inside the parentheses (type name).

B. Return Types vs. Void

This is a common point of confusion.

  • void: Performs an action but returns no value. (e.g., Printing to console, saving to DB).

  • Data Type (int, String, etc.): Calculates and returns a value to the caller.

Java

C. Method Overloading

This is a core OOP concept (Compile-time Polymorphism). You can have multiple methods with the same name as long as their parameters are different.

Java


2. Control Flow statements

"The Logic / The Brain"

Control flow dictates the order in which statements are executed. Without this, your code just reads from top to bottom like a book.

A. Conditional Logic (If / Else / Switch)

Use If/Else for ranges or complex conditions. Use Switch for specific fixed values.

Java

B. Loops (For, While, Do-While)

Loops allow you to repeat code.

  • for loop: Use when you know exactly how many times to loop (e.g., "Run 10 times").

  • while loop: Use when you don't know the number of iterations (e.g., "Run until user types 'exit'").

  • do-while loop: Guaranteed to run at least once (e.g., "Show menu, then ask to continue").

Java


3. Combined Practice: A "Mini ATM" Class

Here is how Methods and Control Flow work together in a real object.

Java

Quick Syntax Cheat Sheet

Keyword

Purpose

Example

void

Method returns nothing

public void run() { ... }

return

Exits method & sends data back

return a + b;

break

Exits a loop or switch case

break;

continue

Skips current loop iteration

continue;

if (x == y)

Checks equality

if (age == 18) { ... }

!=

Checks "Not Equal"

if (age != 0) { ... }

&& / ||

Logical AND / OR

if (age > 18 && hasID)


Part 4


1. Constructors

"The Birth of an Object"

A constructor is a special method that is called automatically when you create an object (using new). Its main job is to initialize the object's fields.

  • Rule: It must have the exact same name as the class and no return type.

A. Default vs. Parameterized

  • Default Constructor: Has no arguments. Java provides an invisible one if you don't write any constructor.

  • Parameterized Constructor: Takes arguments to set specific values during creation.

Java

B. Constructor Overloading

Just like methods, you can have multiple constructors as long as their parameters are different. This gives users flexibility in how they create objects.

Java


2. Static vs. Instance

"Shared vs. Unique"

This is the most critical memory concept in Java.

  • Instance (Non-Static): Belongs to the Object. Each object has its own copy.

    • Analogy: Your Toothbrush. Everyone has their own.

  • Static: Belongs to the Class. There is only one copy shared by all objects.

    • Analogy: The Bathroom Light. Everyone shares the same one.

A. The static Keyword

Use static for properties that should be common to all objects (like a counter or a constant).

Java

B. Static Methods

Static methods can be called without creating an object. They are utility functions (like Math.sqrt()).

  • Restriction: A static method cannot access instance variables (because it doesn't know which object you are talking about).


3. Access Modifiers

"The Security Guards"

Access modifiers determine which other classes can see and use your variables and methods.

Modifier

Keyword

Visibility

Analogy

Public

public

Everywhere (Global)

Public Park (Anyone can enter)

Private

private

Only inside the Same Class

Your Diary (Only you can read)

Protected

protected

Same Package + Subclasses

Family Money (Family + Kids inherit)

Default

(no keyword)

Only inside the Same Package

Office Water Cooler (Only coworkers)

Best Practice: Encapsulation

Always make your fields private and your methods public (unless they are internal helper methods).

Java


4. Combined Revision Code

Here is a School system combining Constructors, Static logic, and Modifiers.

Java

Quick Syntax Cheat Sheet

Feature

Syntax

When to use?

Constructor

public ClassName() { }

To setup default values.

Static Variable

static int count;

For shared data (counters, constants).

Static Method

static void run()

For utility tools (Math, Converters).

Private

private int age;

ALWAYS for class fields (attributes).

Public

public void getAge()

For methods meant for the outside world.

Access Static

ClassName.variable

Don't use object names (e.g., s1.count).

Last updated