Java Core Bhejb Jwiwj
Java Core Bhejb Jwiwj
1. OOP Principles
Encapsulation
- Bundling data (fields) and methods (functions) that operate on the data into a single unit
(class).
- Access to the data is controlled via access modifiers (`private`, `public`, etc.) and
getter/setter methods.
Example:
```java
class Employee {
private int id;
private String name;
Inheritance
- A mechanism where one class (child) inherits properties and methods from another class
(parent).
- Promotes code reusability.
Example:
```java
class Animal {
void eat() { System.out.println("Eating..."); }
}
Polymorphism
- Ability to take many forms.
- Compile-time Polymorphism (Method Overloading): Multiple methods with the same
name but different parameters.
- Runtime Polymorphism (Method Overriding): A child class modifies the behavior of a
parent class method.
Example:
```java
// Overloading
class Calculator {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
}
```
Abstraction
- Hiding implementation details and showing only functionality to the user.
- Achieved using abstract classes or interfaces.
Example:
```java
abstract class Shape {
abstract void draw();
}
2. Exception Handling
- Mechanism to handle runtime errors and maintain the program flow.
- Uses `try`, `catch`, `finally`, `throw`, and `throws`.
- Checked Exceptions: Must be handled (e.g., IOException).
- Unchecked Exceptions: Occur during runtime (e.g., NullPointerException).
Example:
```java
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
} finally {
System.out.println("Execution completed.");
}
```
3. Multithreading
- Simultaneous execution of multiple threads to maximize CPU usage.
- Thread Class: Extend `Thread` class.
- Runnable Interface: Implement `Runnable` interface.
Example:
```java
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running.");
}
}
new MyThread().start();
```
4. Input/Output Streams
- Used to read/write data to files, console, or network.
- Byte Streams: Read/write byte data (`FileInputStream`, `FileOutputStream`).
- Character Streams: Read/write character data (`FileReader`, `FileWriter`).
Example:
```java
FileWriter writer = new FileWriter("output.txt");
writer.write("Hello, World!");
writer.close();
```
5. String Manipulations
- String is immutable; operations return a new object.
- Common Methods: `charAt()`, `substring()`, `length()`, `replace()`, `toLowerCase()`,
`toUpperCase()`.
- StringBuilder/StringBuffer: Mutable string operations for better performance.
Example:
```java
String str = "Hello";
System.out.println(str.toUpperCase()); // Output: HELLO