ADVANCED JAVA NOTES WITH EXAMPLES
1. Encapsulation (With Example)
Encapsulation means binding data and methods together and hiding data using private access
modifier.
Example:
class Student { private int id; public void setId(int i){ id=i; } public int getId(){ return id; }}
2. Inheritance (With Example)
Inheritance allows one class to acquire properties of another class using extends keyword.
Example:
class A { int x=10; } class B extends A { void show(){ [Link](x); }}
3. Polymorphism
Polymorphism means one method behaving differently. Overloading is compile-time, overriding is
runtime.
Example:
class Test { void add(int a,int b){} void add(int a,int b,int c){} }
4. Abstraction
Abstraction hides implementation and shows only functionality using abstract classes or interfaces.
Example:
abstract class Shape { abstract void draw(); }
5. String vs StringBuilder vs StringBuffer
String is immutable. StringBuilder is mutable and fast. StringBuffer is mutable and thread-safe.
Example:
StringBuilder sb=new StringBuilder("Hi"); [Link](" Java");
6. Exception Handling
Exceptions are runtime errors handled using try-catch.
Example:
try{ int a=10/0; }catch(Exception e){ [Link](e); }
7. Collections Example
ArrayList allows duplicates. HashSet removes duplicates. HashMap stores key-value.
Example:
ArrayList l=new ArrayList<>(); [Link](10);
8. Multithreading
Thread allows concurrent execution.
Example:
class MyThread extends Thread { public void run(){ [Link]("Run"); }}
9. Java 8 Lambda
Lambda provides concise code.
Example:
Runnable r=()->[Link]("Hello");