Fundamentals of Object-Oriented Java
In object‑oriented programming, a class serves as a blueprint for objects. The two fundamental components of a class are attributes (also called fields) and methods .

Given a class Car with fields int speed and String brand, which constructor correctly initializes both fields?
What will be the output of the following code? int[] a = {2,4,6}; System.out.println(a[1]);
Which access modifier allows a field to be visible only within its own class and subclasses?
In Java, which of the following is a correct way to read an integer from standard input?
Which of the following best explains why Java does not have destructors?
What is the result of the expression 7 % 3 in Java?
Which statement about method overloading is true in Java?
If a class implements no constructors, what does Java provide automatically?
Which of the following best describes the purpose of a package in Java?
Consider the following loop: for (int i = 0; i < 5; i++) { System.out.print(i); } What is the printed output?
Which of the following statements about the toString() method is correct?
What will happen if you try to assign a double value to an int variable without casting?
Which control structure is most appropriate to replace multiple if‑else statements that test the same variable against constant values?
In the context of OOP, what does encapsulation primarily achieve?
Which of the following is a true statement about Java's primitive type 'char'?
What is the effect of declaring a field as 'static' in a Java class?
Which of the following best describes the role of the 'main' method in a Java program?
If a method is declared as 'public void accelerate(int v){ speed = speed + v; }', what is the method's return type?
Which of the following statements about Java arrays is false?
In a Java class, which of the following is the correct order of elements according to typical conventions?
Understanding Attributes and Methods in Java Classes
In object‑oriented programming, a class serves as a blueprint for objects. The two fundamental components of a class are attributes (also called fields) and methods.
- Attributes store object state: they hold data that describes the object's current condition, such as
int speedorString brandin aCarclass. - Methods define behavior: they are blocks of code that operate on the attributes or perform actions, like
accelerate()ordisplayInfo().
Remember the simple rule: attributes = nouns (state), methods = verbs (behavior). This distinction is essential for designing clean, maintainable Java code.
Constructors: Initializing Objects Correctly
A constructor is a special method that runs when an object is created. Its primary purpose is to set up the initial state of the object by assigning values to its attributes.
Typical Constructor Syntax
For a class named Car with two fields, int speed and String brand, the correct constructor looks like this:
public Car(int s, String b) {
speed = s;
brand = b;
}
Key points to note:
- The constructor name must match the class name exactly.
- It has no return type—not even
void. - Parameters provide the values that will be assigned to the fields.
Using this pattern ensures that every Car object starts with a defined speed and brand, preventing null or uninitialized values.
Arrays and Zero‑Based Indexing
Java arrays are fixed‑size collections that store elements of the same type. The first element of any array is accessed with index 0. This zero‑based indexing is a core concept that often trips up beginners.
Example
int[] a = {2, 4, 6};
System.out.println(a[1]);
The output is 4 because:
a[0]holds2a[1]holds4a[2]holds6
Think of the array like a row of seats numbered from zero; the second seat (1) contains the value 4. This mental model helps avoid the common ArrayIndexOutOfBoundsException error.
Access Modifiers: Controlling Visibility
Java provides four access modifiers that determine where a class member can be accessed:
- public: visible everywhere.
- private: visible only within the declaring class.
- protected: visible within the declaring class, its subclasses, and other classes in the same package.
- default (package‑private): visible only within the same package.
When you need a field to be accessible to subclasses but hidden from unrelated classes, protected is the appropriate choice.
Reading Input with the Scanner Class
Interacting with users via the console is straightforward using java.util.Scanner. The most common pattern for reading an integer is:
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
This code creates a Scanner object linked to System.in (standard input) and then calls nextInt() to retrieve the next integer token.
Common pitfalls include forgetting to import java.util.Scanner or using non‑existent methods like readInt(). Always remember to close the scanner when finished to free system resources:
sc.close();
Memory Management: Why Java Lacks Destructors
Unlike languages such as C++, Java does not provide explicit destructors. The reason is the presence of an automatic garbage collector that reclaims memory for objects that are no longer reachable.
Key advantages of this approach:
- Reduces the risk of memory leaks caused by forgotten
free()calls. - Eliminates the need for developers to manually track object lifetimes.
- Improves program stability, especially in large, complex applications.
Although Java once offered a finalize() method, it is deprecated and should not be relied upon for resource cleanup. Instead, use try‑with‑resources or explicit close methods.
Arithmetic Operators: The Modulo Operator (%)
The modulo operator returns the remainder after division. In Java, the expression 7 % 3 evaluates to 1 because 7 divided by 3 equals 2 with a remainder of 1.
Modulo is frequently used for:
- Determining even or odd numbers (
n % 2 == 0). - Cycling through array indices.
- Implementing hash functions.
Method Overloading: Defining Multiple Behaviors
Method overloading allows a class to have more than one method with the same name, provided they differ in parameter type, number, or order. This enables intuitive APIs such as println() methods that accept int, String, or double arguments.
Rules for Overloading
- The method name must be identical.
- Parameter lists must differ in type, number, or both.
- Return type alone does not constitute a difference.
- Access modifiers (public, private, etc.) and static/non‑static qualifiers are irrelevant to the overload decision.
Example:
public void display(int value) { ... }
public void display(String text) { ... }
public void display(int value, String label) { ... }
Each display method serves a distinct purpose while sharing a common semantic name.
Putting It All Together: A Mini Project
To reinforce the concepts covered, create a simple Car class that demonstrates attributes, methods, constructors, access modifiers, and input handling.
import java.util.Scanner;
public class Car {
protected String brand; // visible to subclasses
private int speed; // encapsulated within Car
// Constructor initializing both fields
public Car(int speed, String brand) {
this.speed = speed;
this.brand = brand;
}
// Overloaded method to set speed
public void setSpeed(int speed) {
this.speed = speed;
}
public void setSpeed(int speed, boolean accelerate) {
this.speed = accelerate ? speed + 10 : speed;
}
public void displayInfo() {
System.out.println("Brand: " + brand + ", Speed: " + speed);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter brand: ");
String b = sc.nextLine();
System.out.print("Enter speed: ");
int s = sc.nextInt();
Car myCar = new Car(s, b);
myCar.displayInfo();
sc.close();
}
}
This example showcases:
- Attributes (
brand,speed) and their visibility. - A constructor that sets both fields.
- Method overloading with two
setSpeedvariants. - Reading user input using
Scanner. - Automatic memory cleanup via the garbage collector.
Compile and run the program to see the concepts in action. Experiment by adding more overloaded methods or changing the access modifiers to observe their effects.
Key Takeaways
- Attributes hold state; methods define behavior.
- Constructors initialize objects; they must match the class name and lack a return type.
- Java arrays start at index 0; always remember the zero‑based rule.
- Use protected for subclass visibility, private for encapsulation.
- Read integers from the console with
Scanner.nextInt(). - Java’s garbage collector eliminates the need for destructors.
- The modulo operator (%) returns the remainder of division.
- Method overloading requires different parameter lists, not just different return types.
Mastering these fundamentals will give you a solid foundation for advanced Java programming and object‑oriented design.
