Java Fundamentals
1. Object-Oriented Programming (OOP)
Java is fundamentally an Object-Oriented Programming (OOP) language. OOP is a programming paradigm that organizes software design around objects, which are instances of classes. Key concepts in OOP include:
1.1 Classes and Objects
A class is a blueprint for creating objects. It defines the properties and behaviors that the objects of its type support. An object is an instance of a class, created at runtime.
Example: Consider a class Car
with attributes like color
and model
, and methods like startEngine()
and stopEngine()
. An object myCar
of type Car
can be created to represent a specific car.
1.2 Encapsulation
Encapsulation is the bundling of data (attributes) and methods (functions) that operate on the data into a single unit, i.e., a class. It also refers to the practice of keeping the internal state of an object private, exposing only necessary information through public methods.
Example: In a BankAccount
class, the balance should be private, and methods like deposit()
and withdraw()
should be public to ensure that the balance is modified only through these methods.
1.3 Inheritance
Inheritance allows a class to inherit properties and methods from another class. The class that inherits is called the subclass (or derived class), and the class from which it inherits is called the superclass (or base class).
Example: A Vehicle
class can have a subclass Car
. The Car
class inherits attributes like numberOfWheels
and methods like drive()
from the Vehicle
class.
1.4 Polymorphism
Polymorphism allows objects of different classes to be treated as objects of a common superclass. It enables methods to be written that can work with objects of multiple types.
Example: A method displayVehicleInfo()
can accept any object of type Vehicle
, whether it is a Car
, Truck
, or Motorcycle
.
2. Java Syntax and Structure
Java syntax is the set of rules that define how Java programs are written. Understanding Java syntax is crucial for writing correct and efficient code.
2.1 Basic Syntax
Java programs are composed of classes, methods, and statements. A class is the outermost structure, containing methods, which in turn contain statements.
Example: A simple Java program might look like this:
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } }
2.2 Data Types and Variables
Java supports various data types, including primitive types (like int
, float
, boolean
) and reference types (like String
, Array
). Variables are used to store data of specific types.
Example: Declaring and initializing variables:
int age = 25; float height = 5.9f; String name = "John Doe";
2.3 Control Flow Statements
Control flow statements determine the order in which statements are executed in a program. Key control flow statements include if-else
, switch
, for
, while
, and do-while
.
Example: Using a for
loop to print numbers from 1 to 5:
for (int i = 1; i <= 5; i++) { System.out.println(i); }
3. Exception Handling
Exception handling is a mechanism to handle runtime errors in Java. It allows the program to continue execution even after an error occurs.
3.1 Try-Catch Block
The try
block contains the code that might throw an exception. The catch
block handles the exception if it occurs.
Example: Handling a FileNotFoundException
:
try { FileReader file = new FileReader("file.txt"); } catch (FileNotFoundException e) { System.out.println("File not found."); }
3.2 Finally Block
The finally
block contains code that will be executed regardless of whether an exception occurs or not. It is often used to release resources.
Example: Closing a file in the finally
block:
FileReader file = null; try { file = new FileReader("file.txt"); } catch (FileNotFoundException e) { System.out.println("File not found."); } finally { if (file != null) { file.close(); } }
4. Collections Framework
The Java Collections Framework provides a set of classes and interfaces for storing and manipulating groups of objects. Key collections include List
, Set
, and Map
.
4.1 List
A List
is an ordered collection that allows duplicate elements. Common implementations include ArrayList
and LinkedList
.
Example: Creating and manipulating an ArrayList
:
Listnames = new ArrayList<>(); names.add("Alice"); names.add("Bob"); System.out.println(names);
4.2 Set
A Set
is a collection that does not allow duplicate elements. Common implementations include HashSet
and TreeSet
.
Example: Creating and manipulating a HashSet
:
Setnumbers = new HashSet<>(); numbers.add(1); numbers.add(2); numbers.add(2); // Duplicate, will not be added System.out.println(numbers);
4.3 Map
A Map
is a collection that stores key-value pairs. Each key is unique. Common implementations include HashMap
and TreeMap
.
Example: Creating and manipulating a HashMap
:
Mapages = new HashMap<>(); ages.put("Alice", 25); ages.put("Bob", 30); System.out.println(ages.get("Alice"));