Records: Simplifies creating immutable data classes. Automatically generates constructors, equals, hashCode, and toString.Example: record Person(String name, int age) {}Person p = new Person("Alice", 25);System.out.println(p.name() + ", " + p.age());
Pattern Matching: Simplifies conditional code by type-checking in expressions.Example: Object obj = "Hello";if (obj instanceof String str) { System.out.println(str.toUpperCase());}
Object-Oriented Programming (OOP): Java follows OOP principles: Encapsulation, Inheritance, Polymorphism, and Abstraction. These principles help in building modular, scalable, and maintainable applications.
Encapsulation: Restricting direct access to object data and methods by using private access modifiers and providing public getters and setters.Example: class Employee { private String name; private int id; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int […]
Inheritance: Enables one class to acquire the properties and behavior of another class using the extends keyword.Example: class Animal { void eat() { System.out.println("This animal eats food."); }}class Dog extends Animal { void bark() { System.out.println("Dog barks."); }}Dog myDog = new Dog();myDog.eat();myDog.bark();
Polymorphism: The ability of a method to perform different tasks based on its parameters or the object it is called on. Types: Method Overloading and Method Overriding.Example:Overloading: class MathOps { int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; }}MathOps ops = new […]
Abstraction: Hiding implementation details and showing only essential features using abstract classes or interfaces.Example:Abstract Class: abstract class Shape { abstract void draw();}class Circle extends Shape { void draw() { System.out.println("Drawing Circle"); }}Shape s = new Circle();s.draw(); Interface: interface Animal { void sound();}class Cat implements Animal { public void sound() { System.out.println("Meow"); }}Animal a = new […]
For-Each Loop: Used to iterate over arrays or collections.Example: int[] numbers = {1, 2, 3, 4, 5};for (int num : numbers) { System.out.println(num);}
Sum of array elements:Example: int[] numbers = {1, 2, 3, 4, 5};int sum = 0;for (int num : numbers) { sum += num;}System.out.println("Total: " + sum);
Loops are control flow statements that repeat code execution until a specified condition is met. Types of loops include For, While, Do-While, and For-Each. Each has specific use cases.