Java Basics and Object-Oriented Programming (OOP)
Learn Java OOP core. Master variables, classes, inheritance, method overriding, interfaces, abstract classes, and encapsulation.
Downloaded from PrepIQ (https://prepiq.online)
Q1. What is Java and what are its main features?
Java is a high-level, object-oriented, platform-independent programming language developed by Sun Microsystems (now Oracle). It follows the principle 'Write Once, Run Anywhere' (WORA).
| Feature | Description |
|---|---|
| Platform-Independent | Runs on any platform with JVM installed |
| Object-Oriented | Everything is an object, supports OOP principles |
| Secure | Built-in security features and bytecode verification |
| Robust | Strong type checking, exception handling, memory management |
| Multi-threaded | Built-in support for concurrent programming |
| Portable | Compiled code can run on any platform |
| High Performance | JIT compilation, garbage collection optimization |
| Distributed | Support for network programming and RMI |
// Java Program Structure
public class HelloWorld {
public static void main(String[] args) {
System.out.println('Hello, Java!');
}
}
// Key Points:
// 1. Java is compiled to bytecode (.class files)
// 2. Bytecode runs on JVM (Java Virtual Machine)
// 3. One compile, run anywhere principle
// 4. Garbage collection automatically manages memory
// 5. Strong type system ensures type safety
// 6. Exception handling for error management
// 7. Multi-threading support for concurrent execution
// 8. Rich standard library (Java API)
Q2. What is the difference between JVM, JDK, and JRE?
| Component | JVM (Java Virtual Machine) | JRE (Java Runtime Environment) | JDK (Java Development Kit) |
|---|---|---|---|
| Purpose | Executes Java bytecode | Runtime environment for Java apps | Complete development environment |
| Contains | Only bytecode execution | JVM + libraries + tools for running | JRE + compiler + debugger + tools |
| Use Case | Execute compiled bytecode | Run Java applications | Develop Java applications |
| Compilation | N/A | Not needed | Includes javac compiler |
| Size | Smallest | Medium | Largest |
| Users | End users | End users (users running apps) | Developers |
// Compilation Process
// 1. Developer writes .java files
// 2. javac (in JDK) compiles to .class bytecode
// 3. JVM (in JRE) executes the .class files
// Example:
// javac HelloWorld.java // JDK compiler
// java HelloWorld // JVM execution
// Relationship:
// JDK = JRE + Development Tools
// JRE = JVM + Libraries
// JVM = Bytecode Execution Engine
// Installation:
// To run Java apps: Install JRE only
// To develop Java apps: Install JDK (which includes JRE)
Q3. What are variables and data types in Java?
Variables are named memory locations that store values. Data types define the type of data a variable can hold.
| Data Type | Size | Range | Example |
|---|---|---|---|
| byte | 1 byte | -128 to 127 | byte b = 10; |
| short | 2 bytes | -32,768 to 32,767 | short s = 1000; |
| int | 4 bytes | -2^31 to 2^31-1 | int i = 100000; |
| long | 8 bytes | -2^63 to 2^63-1 | long l = 10000000000L; |
| float | 4 bytes | Single precision | float f = 3.14f; |
| double | 8 bytes | Double precision | double d = 3.14; |
| char | 2 bytes | Unicode (0 to 65,535) | char c = 'A'; |
| boolean | 1 bit | true or false | boolean flag = true; |
// Primitive Data Types
public class DataTypes {
public static void main(String[] args) {
// Numeric types
byte age = 25;
short distance = 5000;
int salary = 50000;
long population = 1000000000L;
// Decimal types
float price = 19.99f;
double pi = 3.14159265;
// Character type
char gender = 'M';
// Boolean type
boolean isActive = true;
// Reference Types (Non-primitive)
String name = 'John';
int[] numbers = {1, 2, 3, 4, 5};
}
}
// Type Casting
int a = 10;
long b = (long) a; // Implicit casting (widening)
double x = 10.5;
int y = (int) x; // Explicit casting (narrowing)
Q4. What are Object-Oriented Programming (OOP) principles?
OOP is a programming paradigm based on objects and classes. It follows four main principles: Encapsulation, Inheritance, Polymorphism, and Abstraction.
| Principle | Description | Example |
|---|---|---|
| Encapsulation | Bundling data and methods, hiding implementation details | Private variables with getter/setter |
| Inheritance | A class inherits properties from another class | Child extends Parent |
| Polymorphism | Objects can take many forms, same method different behavior | Method overriding, overloading |
| Abstraction | Hiding complex details, showing only essential features | Abstract classes, interfaces |
// OOP Example
public class Animal {
// Encapsulation - private data
private String name;
private int age;
// Constructor
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
// Method
public void sound() {
System.out.println('Making sound');
}
}
// Inheritance - Dog inherits from Animal
public class Dog extends Animal {
// Polymorphism - overriding parent method
@Override
public void sound() {
System.out.println('Dog barks');
}
}
// Usage
Animal dog = new Dog('Buddy', 3);
dog.sound(); // Prints: Dog barks
Q5. What are Classes and Objects in Java?
// Class Definition
public class Student {
// Attributes (Member Variables)
private String name;
private int rollNumber;
private double gpa;
// Constructor
public Student(String name, int rollNumber) {
this.name = name;
this.rollNumber = rollNumber;
this.gpa = 0.0;
}
// Methods
public void study() {
System.out.println(name + ' is studying');
}
public void setGPA(double gpa) {
this.gpa = gpa;
}
public double getGPA() {
return gpa;
}
}
// Creating Objects (Instances)
public class Main {
public static void main(String[] args) {
// Object creation
Student student1 = new Student('John', 101);
Student student2 = new Student('Jane', 102);
// Using objects
student1.study();
student1.setGPA(3.8);
System.out.println('GPA: ' + student1.getGPA());
}
}
// Key Differences:
// Class: Blueprint, template, logical entity
// Object: Instance of class, physical entity created in memory
// One class can have multiple objects
// Objects consume memory, class does not
Q6. What is Inheritance and how does it work in Java?
Inheritance is a mechanism where a child class inherits properties and methods from a parent class. It promotes code reusability and establishes a relationship between classes.
// Parent Class
public class Vehicle {
protected String color;
protected int speed;
public void start() {
System.out.println('Vehicle started');
}
public void stop() {
System.out.println('Vehicle stopped');
}
}
// Child Class (inherits from Vehicle)
public class Car extends Vehicle {
private int numberOfDoors;
public Car(String color, int speed, int doors) {
this.color = color;
this.speed = speed;
this.numberOfDoors = doors;
}
// Overriding parent method
@Override
public void start() {
System.out.println('Car engine started');
}
public void displayDoors() {
System.out.println('Number of doors: ' + numberOfDoors);
}
}
// Another Child Class
public class Bike extends Vehicle {
private boolean hasHelmet;
public void wheelie() {
System.out.println('Bike doing wheelie');
}
}
// Using Inheritance
public class Main {
public static void main(String[] args) {
Car car = new Car('Red', 100, 4);
car.start(); // Calls overridden method
car.displayDoors();
Bike bike = new Bike();
bike.start(); // Calls parent method
bike.wheelie();
}
}
// Types of Inheritance:
// 1. Single Inheritance: Child extends one Parent
// 2. Multilevel Inheritance: A extends B, B extends C
// 3. Hierarchical Inheritance: Multiple children extend one parent
// 4. Multiple Inheritance: Not directly supported (use interfaces)
Q7. What is Polymorphism in Java? Explain Method Overloading and Overriding.
Polymorphism means 'many forms'. In Java, it allows objects to take multiple forms and methods to behave differently based on context.
// Method Overloading (Compile-time Polymorphism)
public class Calculator {
// Overloaded add methods
public int add(int a, int b) {
return a + b;
}
public double add(double a, double b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}
// Different parameter types
public String add(String a, String b) {
return a + b; // String concatenation
}
}
// Method Overriding (Runtime Polymorphism)
public class Animal {
public void sound() {
System.out.println('Animal makes sound');
}
}
public class Dog extends Animal {
@Override
public void sound() {
System.out.println('Dog barks');
}
}
public class Cat extends Animal {
@Override
public void sound() {
System.out.println('Cat meows');
}
}
// Usage
public class Main {
public static void main(String[] args) {
// Method Overloading
Calculator calc = new Calculator();
System.out.println(calc.add(5, 10)); // 15
System.out.println(calc.add(5.5, 10.5)); // 16.0
System.out.println(calc.add(5, 10, 15)); // 30
// Method Overriding (Runtime Polymorphism)
Animal dog = new Dog();
Animal cat = new Cat();
dog.sound(); // Dog barks
cat.sound(); // Cat meows
}
}
Q8. What is Encapsulation in Java? How do you implement it?
Encapsulation is bundling data (variables) and methods that operate on that data into a single unit (class), and hiding the implementation details. It provides data security and control.
// Encapsulation Example
public class BankAccount {
// Private variables (data hiding)
private String accountNumber;
private double balance;
private String accountHolder;
// Constructor
public BankAccount(String accountNumber, String accountHolder, double initialBalance) {
this.accountNumber = accountNumber;
this.accountHolder = accountHolder;
this.balance = initialBalance;
}
// Getter methods
public String getAccountNumber() {
return accountNumber;
}
public double getBalance() {
return balance;
}
public String getAccountHolder() {
return accountHolder;
}
// Setter methods with validation
public void setBalance(double balance) {
if (balance >= 0) {
this.balance = balance;
} else {
System.out.println('Balance cannot be negative');
}
}
// Business logic methods
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println('Deposited: ' + amount);
}
}
public boolean withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println('Withdrawn: ' + amount);
return true;
}
System.out.println('Insufficient balance');
return false;
}
}
// Usage
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount('ACC001', 'John', 5000);
// Cannot access private variables directly
// account.balance = -1000; // ERROR
// Must use public methods
account.deposit(1000);
account.withdraw(2000);
System.out.println('Balance: ' + account.getBalance());
}
}
// Benefits of Encapsulation:
// 1. Data Security: Can't access directly
// 2. Validation: Setter can validate data
// 3. Maintainability: Can change implementation without affecting external code
// 4. Flexibility: Can make fields read-only or write-only
// 5. Control: Full control over what data is exposed
Q9. What is Abstraction in Java? Abstract Classes and Interfaces.
Abstraction is a process of hiding complex implementation details and showing only the essential features. It's achieved through abstract classes and interfaces.
// Abstract Class
public abstract class Shape {
// Abstract method (no implementation)
public abstract double calculateArea();
public abstract double calculatePerimeter();
// Concrete method
public void displayInfo() {
System.out.println('This is a shape');
}
}
// Concrete implementations
public class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
@Override
public double calculatePerimeter() {
return 2 * Math.PI * radius;
}
}
public class Rectangle extends Shape {
private double length, width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double calculateArea() {
return length * width;
}
@Override
public double calculatePerimeter() {
return 2 * (length + width);
}
}
// Interface
public interface Drawable {
void draw(); // Implicitly abstract
void erase();
}
public class Drawing implements Drawable {
@Override
public void draw() {
System.out.println('Drawing...');
}
@Override
public void erase() {
System.out.println('Erasing...');
}
}
// Usage
public class Main {
public static void main(String[] args) {
Shape circle = new Circle(5);
Shape rect = new Rectangle(4, 6);
System.out.println('Circle Area: ' + circle.calculateArea());
System.out.println('Rectangle Area: ' + rect.calculateArea());
}
}
// Abstract Class vs Interface:
// Abstract Class: Can have state (variables), constructors, private methods
// Interface: Only behavior contract, no state (until Java 8, default methods)
// Abstract Class: 'is-a' relationship
// Interface: 'can-do' capability
Q10. What are Access Modifiers in Java?
Access modifiers control the visibility and accessibility of classes, methods, and variables. Java has four access levels: public, protected, default (package-private), and private.
| Modifier | Same Class | Same Package | Different Package (Subclass) | Different Package (Other) |
|---|---|---|---|---|
| public | ✓ | ✓ | ✓ | ✓ |
| protected | ✓ | ✓ | ✓ | ✗ |
| default (no modifier) | ✓ | ✓ | ✗ | ✗ |
| private | ✓ | ✗ | ✗ | ✗ |
// Access Modifiers Example
public class AccessModifierDemo {
// Public - accessible everywhere
public int publicVar = 10;
public void publicMethod() {
System.out.println('Public method');
}
// Protected - accessible in same package and subclasses
protected int protectedVar = 20;
protected void protectedMethod() {
System.out.println('Protected method');
}
// Default (package-private) - accessible in same package only
int defaultVar = 30;
void defaultMethod() {
System.out.println('Default method');
}
// Private - accessible only in same class
private int privateVar = 40;
private void privateMethod() {
System.out.println('Private method');
}
}
// Same package, different class
public class SamePackage {
public static void main(String[] args) {
AccessModifierDemo obj = new AccessModifierDemo();
obj.publicVar; // ✓ Accessible
obj.publicMethod(); // ✓ Accessible
obj.protectedVar; // ✓ Accessible
obj.protectedMethod(); // ✓ Accessible
obj.defaultVar; // ✓ Accessible
obj.defaultMethod(); // ✓ Accessible
// obj.privateVar; // ✗ Compile Error
// obj.privateMethod(); // ✗ Compile Error
}
}
// Different package
public class DifferentPackage {
public static void main(String[] args) {
AccessModifierDemo obj = new AccessModifierDemo();
obj.publicVar; // ✓ Accessible
obj.publicMethod(); // ✓ Accessible
// obj.protectedVar; // ✗ Compile Error (unless subclass)
// obj.defaultVar; // ✗ Compile Error
// obj.privateVar; // ✗ Compile Error
}
}
// Best Practices:
// 1. Use private for data members (encapsulation)
// 2. Use public for public API methods
// 3. Use protected for methods meant for subclasses
// 4. Use default only when intentional (package-level access)
Java Basics and Object-Oriented Programming (OOP)
Learn Java OOP core. Master variables, classes, inheritance, method overriding, interfaces, abstract classes, and encapsulation.
What is Java and what are its main features?
Java is a high-level, object-oriented, platform-independent programming language developed by Sun Microsystems...
What is the difference between JVM, JDK, and JRE?
ComponentJVM (Java Virtual Machine)JRE (Java Runtime Environment)JDK (Java Development Kit)PurposeExecutes Jav...
What are variables and data types in Java?
Variables are named memory locations that store values. Data types define the type of data a variable can hold...
What are Object-Oriented Programming (OOP) principles?
OOP is a programming paradigm based on objects and classes. It follows four main principles: Encapsulation, In...
What are Classes and Objects in Java?
// Class Definition public class Student { // Attributes (Member Variables) private String name; p...
What is Inheritance and how does it work in Java?
Inheritance is a mechanism where a child class inherits properties and methods from a parent class. It promote...
What is Polymorphism in Java? Explain Method Overloading and Overriding.
Polymorphism means 'many forms'. In Java, it allows objects to take multiple forms and methods to behave diffe...
What is Encapsulation in Java? How do you implement it?
Encapsulation is bundling data (variables) and methods that operate on that data into a single unit (class), a...
What is Abstraction in Java? Abstract Classes and Interfaces.
Abstraction is a process of hiding complex implementation details and showing only the essential features. It'...
What are Access Modifiers in Java?
Access modifiers control the visibility and accessibility of classes, methods, and variables. Java has four ac...