# Document 1: Java Notes
## Introduction to Java
Java is a high-level, class-based, object-oriented programming language designed to have as few
implementation dependencies as possible. It is a general-purpose programming language intended
to let programmers write once, run anywhere (WORA), meaning compiled Java code can run on all
platforms that support Java without recompilation.
### Key Features of Java
- **Platform Independence**: Java bytecode runs on any device with a Java Virtual Machine (JVM).
- **Object-Oriented**: Supports encapsulation, inheritance, polymorphism, and abstraction.
- **Robust**: Strong memory management, exception handling, and type checking.
- **Secure**: Sandboxing and bytecode verification.
- **Multithreaded**: Built-in support for concurrent programming.
- **High Performance**: Just-In-Time (JIT) compiler optimizes code at runtime.
### Java History
- Developed by James Gosling at Sun Microsystems in 1995.
- Released publicly in 1996.
- Acquired by Oracle in 2010.
- Current version as of October 2025: Java 23 (LTS versions: 8, 11, 17, 21).
## Java Basics
### Data Types
Java has two categories: Primitive and Non-Primitive.
| Type | Size (bits) | Range/Example |
|------------|-------------|--------------------------------|
| byte |8 | -128 to 127 |
| short | 16 | -32,768 to 32,767 |
| int | 32 | -2^31 to 2^31 - 1 |
| long | 64 | -2^63 to 2^63 - 1 |
| float | 32 | 3.4e-38 to 3.4e+38 |
| double | 64 | 1.7e-308 to 1.7e+308 |
| char | 16 | Unicode characters |
| boolean | 1 | true/false |
Non-primitive: Strings, Arrays, Classes.
### Variables and Operators
- **Declaration**: `int age = 25;`
- **Operators**: Arithmetic (+, -, *, /, %), Relational (==, !=, >, <), Logical (&&, ||, !), Assignment (=,
+=, etc.).
### Control Structures
- **If-Else**:
```
if (condition) {
// code
} else {
// code
```
- **Switch**:
```
switch (day) {
case 1: System.out.println("Monday"); break;
default: System.out.println("Invalid");
```
- **Loops**: for, while, do-while, enhanced for.
## Object-Oriented Programming in Java
### Classes and Objects
- **Class**: Blueprint. `class Car { String model; void drive() { ... } }`
- **Object**: Instance. `Car myCar = new Car();`
- **Constructors**: Default or parameterized. `public Car(String m) { model = m; }`
- **this Keyword**: Refers to current object.
### Inheritance
- Extends keyword: `class SportsCar extends Car { ... }`
- Types: Single, Multilevel, Hierarchical. (No multiple inheritance for classes, but interfaces allow it.)
### Polymorphism
- **Method Overloading**: Same name, different parameters.
- **Method Overriding**: Subclass redefines superclass method. `@Override` annotation.
### Abstraction
- **Abstract Classes**: Cannot instantiate, may have abstract methods.
```
abstract class Shape { abstract void draw(); }
```
- **Interfaces**: Pure abstraction. `interface Drawable { void draw(); }` (From Java 8: default/static
methods.)
### Encapsulation
- Access modifiers: private, default, protected, public.
- Getters/Setters for data hiding.
## Exception Handling
- **Checked vs Unchecked**: Compile-time (IOException) vs Runtime (NullPointerException).
- **try-catch-finally**:
```
try {
// risky code
} catch (Exception e) {
// handle
} finally {
// always execute
```
- **throw/throws**: Manual throw, method declaration.
## Java Collections Framework
- **List**: ArrayList (dynamic array), LinkedList (doubly-linked).
- **Set**: HashSet (no order), TreeSet (sorted).
- **Map**: HashMap (key-value), TreeMap (sorted keys).
- **Queue**: PriorityQueue.
Example:
```
List<String> list = new ArrayList<>();
list.add("Java");
Iterator<String> it = list.iterator();
while (it.hasNext()) { System.out.println(it.next()); }
```
## Input/Output in Java
- **File Handling**: File class, FileReader/Writer, BufferedReader.
```
File file = new File("example.txt");
FileWriter fw = new FileWriter(file);
fw.write("Hello Java");
fw.close();
```
- **Streams**: Byte (InputStream/OutputStream), Character (Reader/Writer).
## Multithreading
- **Thread Class**: `class MyThread extends Thread { public void run() { ... } }`
- **Runnable Interface**: `class MyRunnable implements Runnable { public void run() { ... } }`
- **Synchronization**: `synchronized` keyword for thread safety.
- **Lifecycle**: New, Runnable, Running, Blocked, Dead.
## Java 8+ Features
- **Lambda Expressions**: `(a, b) -> a + b`
- **Stream API**: `list.stream().filter(n -> n > 5).map(n -> n*2).collect(Collectors.toList());`
- **Optional**: Avoid NullPointer. `Optional<String> opt = Optional.ofNullable(str);`
- **Date/Time API**: LocalDate, LocalTime, ZonedDateTime.
## Best Practices
- Use meaningful variable names.
- Follow naming conventions: camelCase for methods/variables, PascalCase for classes.
- Handle exceptions appropriately.
- Use enums for constants.
- Avoid magic numbers; use constants.
## Sample Project: Simple Calculator
```
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter two numbers: ");
double a = sc.nextDouble(), b = sc.nextDouble();
System.out.print("Enter operator (+,-,*,/): ");
char op = sc.next().charAt(0);
switch (op) {
case '+': System.out.println(a + b); break;
// similar for others
default: System.out.println("Invalid");
sc.close();
```