├── README.md └── src ├── solid ├── l │ ├── Bicycle.java │ ├── MotorCycle.java │ ├── Vehicle.java │ ├── MotorVehicles.java │ ├── Car.java │ └── VehicleApplication.java ├── i │ ├── BearCleaner.java │ ├── BearFeeder.java │ ├── BearPetter.java │ ├── BearKeeper.java │ ├── CrazyPerson.java │ ├── BearCarer.java │ └── Person.java ├── d │ ├── Monitor.java │ ├── StandardKeyboard.java │ ├── AppleComputer.java │ └── BuyComputerApp.java ├── s │ ├── BookPrinter.java │ ├── FilterBooks.java │ ├── BookApplication.java │ └── Book.java └── o │ ├── GuitarApplication.java │ ├── SuperCoolGuitarsWithFlames.java │ └── Guitar.java ├── RecordsDemo ├── Student.java └── RecordsDemo.java ├── FunctionalInterface ├── Operation.java └── FunctionalInterfaceDemo.java ├── InstagramAccount.java ├── abstractinterface ├── Drawable.java ├── TestClass.java ├── Animal.java └── PartitioningByExample.java ├── Anagram ├── Demo.java └── AnagramDemo.java ├── Lambda ├── InheritanceExample.java └── FilterExample.java ├── FinalFinallyFinalize ├── FinalizeExample.java ├── FinalExample.java └── FinallyExample.java ├── Generics ├── Generic.java └── GenericsInJava.java ├── ThreadLifeCycle ├── NEW.java ├── TerminatedState.java ├── TimedWaitingState.java ├── BlockedState.java └── WaitingState.java ├── ConstructorFinal ├── Demo.java └── Parent.java ├── DemoM.java ├── Streams ├── ParallelStreamExample.java ├── CountExample.java ├── ReduceExample.java ├── LimitExample.java ├── AnyMatchExample.java ├── SumExample.java ├── DistinctExample.java ├── FilterExample.java ├── MapExample.java ├── MinMaxExample.java ├── SkipExample.java ├── PeekExample.java ├── FindFirstExample.java ├── CollectExample.java ├── FlatMapExample.java ├── ConvertToStreams.java └── SortedExample.java ├── MainClass.java ├── VisibilityProblem ├── SharedFlag.java └── Volatile.java ├── EnumDemo └── EnumDemo.java ├── SwapNumbers └── SwapTwoNumbers.java ├── Shortcuts ├── IntelliJVariableExtraction.java └── IntellijMethodExtraction.java ├── VarKeyword └── VarKeywordDemo.java ├── VarArgs └── Sum.java ├── StreamAnymatch ├── Order.java └── AnyMatchExample.java ├── StreamAllMatch ├── Employee.java └── AllMatchExample.java ├── Multicatch └── MultiCatch.java ├── ZeroOneSum └── ZeroOne.java ├── Stream └── FilterExample.java ├── MainMethodOverloading.java ├── OptionalDemo └── OptionalDemo.java ├── FailFastFailSafe ├── FailFast.java └── FailSafe.java ├── StringAndStringBuilder └── StringAndStringBuilder.java ├── Constr └── Main.java ├── Collections ├── Iterator │ └── IteratorDemo.java └── List │ ├── PriorityQueueDemo.java │ ├── StackDemo.java │ ├── VectorDemo.java │ ├── ArrayListDemo.java │ ├── QueueDemo.java │ ├── DequeueDemo.java │ └── LinkedListDemo.java ├── Quiz.java ├── Predicate └── PredicateInterfaceExample.java ├── Atomicity ├── SharedCounter.java └── Atomic.java ├── MethodReferences └── MethodReference.java ├── HashmapDemo └── HashMapDemo.java ├── Thread ├── PrintEvenOdd.java └── EvenOddRunnable.java ├── CompareEnums.java ├── CreateStreamFromArray └── CreateStreamFromArray.java ├── ArrayVSArraylist ├── ArrayExample.java └── ArrayListExample.java ├── StreamProblems ├── WordFrequency.java ├── PersonSortingExample.java └── TransactionsProblem.java ├── Optional └── OptionalClassDemo.java ├── Code └── CleanCode.java ├── PrePostfix └── PrePostFixDemo.java ├── Palindrome ├── NumberPalindrome.java └── StringPalindrome.java ├── NextCharConverter.java ├── AbstractInterface.java ├── BoundedTypeDemo └── BoundedTypeDemo.java ├── groupingby ├── Employee.java ├── GroupingByDemo.java └── Student.java ├── SortUsingStreams.java ├── MyClass.java ├── AutoAndUnboxingDemo └── AutoboxingUnboxingExample.java ├── StringBufferVsStringBuilder └── StringBufferVsBuilder.java ├── completableFuture ├── OnlineOrderingSystem.java └── WeatherApplication.java ├── Demo.java ├── Set └── SetDemo.java ├── SUMOFDIGITS └── SumOfDigits.java ├── DefaultDemo └── DefaultMethodExample.java ├── BalancedBraces └── BalancedParentheses.java ├── ComparableVsComparator ├── PersonCompare.java └── Person.java ├── FunctionInterfaceDemo └── FunctionExample.java ├── HashMapVsConCurrentHashMap └── HashMapExample.java ├── FascinaingNumber └── FascinatingNumber.java ├── parallelAndSequentialStreams ├── ParallelAndSequentialStreams.java └── FactorialParallelAndSequentialStreams.java ├── MapAndFlatMap └── MapAndFlatMap.java ├── PangramString └── PangramString.java ├── JVM └── Test.java ├── ShallowVsDeepCopy └── Person.java ├── ReverseString └── ReverseString.java ├── ThreadPoolExecutorExample └── ThreadPoolExecutorExample.java ├── SerializationInJava └── SerializationExample.java ├── RotateArrays.java ├── ListComparison.java └── InstanceOfDemo └── MessageProcessor.java /README.md: -------------------------------------------------------------------------------- 1 | # CodeSnippet 2 | -------------------------------------------------------------------------------- /src/solid/l/Bicycle.java: -------------------------------------------------------------------------------- 1 | package solid.l; 2 | 3 | public class Bicycle extends Vehicle{ 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/RecordsDemo/Student.java: -------------------------------------------------------------------------------- 1 | package RecordsDemo; 2 | public record Student(String name, int age, String grade) {} 3 | -------------------------------------------------------------------------------- /src/solid/l/MotorCycle.java: -------------------------------------------------------------------------------- 1 | package solid.l; 2 | 3 | public class MotorCycle extends MotorVehicles{ 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/solid/i/BearCleaner.java: -------------------------------------------------------------------------------- 1 | package solid.i; 2 | 3 | public interface BearCleaner { 4 | void washTheBear(); 5 | } 6 | -------------------------------------------------------------------------------- /src/solid/i/BearFeeder.java: -------------------------------------------------------------------------------- 1 | package solid.i; 2 | 3 | public interface BearFeeder { 4 | void feedTheBear(); 5 | } 6 | -------------------------------------------------------------------------------- /src/solid/i/BearPetter.java: -------------------------------------------------------------------------------- 1 | package solid.i; 2 | 3 | public interface BearPetter { 4 | void petTheBear(); 5 | } 6 | 7 | -------------------------------------------------------------------------------- /src/FunctionalInterface/Operation.java: -------------------------------------------------------------------------------- 1 | package FunctionalInterface; 2 | 3 | public interface Operation { 4 | int operate(int a,int b); 5 | } 6 | -------------------------------------------------------------------------------- /src/InstagramAccount.java: -------------------------------------------------------------------------------- 1 | public abstract class InstagramAccount{ 2 | public String getAccount(){ 3 | return "Creators"; 4 | }; 5 | } 6 | -------------------------------------------------------------------------------- /src/abstractinterface/Drawable.java: -------------------------------------------------------------------------------- 1 | package abstractinterface; 2 | 3 | public interface Drawable { 4 | String name = ""; 5 | void draw(); 6 | } 7 | -------------------------------------------------------------------------------- /src/solid/l/Vehicle.java: -------------------------------------------------------------------------------- 1 | package solid.l; 2 | 3 | public class Vehicle { 4 | public Integer hasNumberOfWheels(){ 5 | return 2; 6 | } 7 | 8 | } 9 | -------------------------------------------------------------------------------- /src/abstractinterface/TestClass.java: -------------------------------------------------------------------------------- 1 | package abstractinterface; 2 | 3 | public class TestClass { 4 | public static void main(String[] args) { 5 | 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/solid/i/BearKeeper.java: -------------------------------------------------------------------------------- 1 | package solid.i; 2 | 3 | public interface BearKeeper { 4 | void washTheBear(); 5 | void feedTheBear(); 6 | void petTheBear(); 7 | } 8 | -------------------------------------------------------------------------------- /src/solid/l/MotorVehicles.java: -------------------------------------------------------------------------------- 1 | package solid.l; 2 | 3 | public class MotorVehicles extends Vehicle { 4 | public Integer enginePower(){ 5 | return 150; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/Anagram/Demo.java: -------------------------------------------------------------------------------- 1 | package Anagram; 2 | 3 | public class Demo { 4 | static public void main(String[] args) { 5 | System.out.println("CodeSnippet"); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/solid/i/CrazyPerson.java: -------------------------------------------------------------------------------- 1 | package solid.i; 2 | 3 | public class CrazyPerson implements BearPetter{ 4 | @Override 5 | public void petTheBear() { 6 | //Good luck with that 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/Lambda/InheritanceExample.java: -------------------------------------------------------------------------------- 1 | package Lambda; 2 | 3 | public class InheritanceExample { 4 | public static void main(String[] args) { 5 | Parent p = new Child(); 6 | p.display(); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/FinalFinallyFinalize/FinalizeExample.java: -------------------------------------------------------------------------------- 1 | package FinalFinallyFinalize; 2 | 3 | public class FinalizeExample { 4 | @Override 5 | protected void finalize() throws Throwable { 6 | // Cleanup operations or resource release 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/Generics/Generic.java: -------------------------------------------------------------------------------- 1 | package Generics; 2 | 3 | public class Generic { 4 | private T item; 5 | public T getItem() { 6 | return item; 7 | } 8 | public void setItem(T item) { 9 | this.item = item; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/ThreadLifeCycle/NEW.java: -------------------------------------------------------------------------------- 1 | package ThreadLifeCycle; 2 | 3 | public class NEW { 4 | public static void main(String[] args) { 5 | Thread t = new Thread(); 6 | t.start(); 7 | System.out.println(t.getState()); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/FinalFinallyFinalize/FinalExample.java: -------------------------------------------------------------------------------- 1 | package FinalFinallyFinalize; 2 | 3 | final public class FinalExample { 4 | final int MAX_VALUE = 100; 5 | final double PI = 3.14; 6 | 7 | final void display() { 8 | // Method implementation 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/ConstructorFinal/Demo.java: -------------------------------------------------------------------------------- 1 | package ConstructorFinal; 2 | 3 | public class Demo{ 4 | public static void main(String[] args) { 5 | int x = 5; 6 | System.out.println(x > 5 ? 7 | "Big" : 8 | "Small"); 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/DemoM.java: -------------------------------------------------------------------------------- 1 | public class DemoM extends Thread{ 2 | 3 | 4 | public static void main(String[] args) { 5 | Thread t = new Thread(()->{ 6 | System.out.println(Thread.currentThread().getName()); 7 | }); 8 | t.start(); 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/solid/d/Monitor.java: -------------------------------------------------------------------------------- 1 | package solid.d; 2 | 3 | public class Monitor { 4 | String brand = "Apple"; 5 | 6 | public String getBrand() { 7 | return brand; 8 | } 9 | 10 | public void setBrand(String brand) { 11 | this.brand = brand; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/solid/l/Car.java: -------------------------------------------------------------------------------- 1 | package solid.l; 2 | 3 | public class Car extends MotorVehicles{ 4 | @Override 5 | public Integer hasNumberOfWheels() { 6 | return 4; 7 | } 8 | 9 | @Override 10 | public Integer enginePower() { 11 | return 1200; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/solid/d/StandardKeyboard.java: -------------------------------------------------------------------------------- 1 | package solid.d; 2 | 3 | public class StandardKeyboard { 4 | String brand="Apple"; 5 | 6 | public String getBrand() { 7 | return brand; 8 | } 9 | 10 | public void setBrand(String brand) { 11 | this.brand = brand; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/solid/s/BookPrinter.java: -------------------------------------------------------------------------------- 1 | package solid.s; 2 | 3 | public class BookPrinter { 4 | void printTextToConsole(Book book){ 5 | System.out.println(book.getText()); 6 | } 7 | void printTextToAnotherMedium(Book book){ 8 | System.out.println(book.getText()); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/Streams/ParallelStreamExample.java: -------------------------------------------------------------------------------- 1 | package Streams; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public class ParallelStreamExample { 7 | public static void main(String[] args) { 8 | List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); 9 | 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/solid/i/BearCarer.java: -------------------------------------------------------------------------------- 1 | package solid.i; 2 | 3 | public class BearCarer implements BearCleaner,BearFeeder{ 4 | @Override 5 | public void washTheBear() { 6 | //Did we miss the spot 7 | } 8 | 9 | @Override 10 | public void feedTheBear() { 11 | // Friday Fish 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/solid/i/Person.java: -------------------------------------------------------------------------------- 1 | package solid.i; 2 | 3 | public class Person implements BearKeeper { 4 | @Override 5 | public void washTheBear() { 6 | 7 | } 8 | 9 | @Override 10 | public void feedTheBear() { 11 | 12 | } 13 | 14 | @Override 15 | public void petTheBear() { 16 | 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/MainClass.java: -------------------------------------------------------------------------------- 1 | public class MainClass extends InstagramAccount { 2 | 3 | @Override 4 | public String getAccount() { 5 | return "CodeSnippet"; 6 | } 7 | public static void main(String[] args) { 8 | MainClass obj = new MainClass(); 9 | System.out.println(obj.getAccount()); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/solid/d/AppleComputer.java: -------------------------------------------------------------------------------- 1 | package solid.d; 2 | 3 | public class AppleComputer { 4 | private StandardKeyboard keyboard; 5 | private Monitor monitor; 6 | 7 | public AppleComputer(StandardKeyboard keyboard, Monitor monitor) { 8 | this.keyboard = keyboard; 9 | this.monitor = monitor; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/VisibilityProblem/SharedFlag.java: -------------------------------------------------------------------------------- 1 | package VisibilityProblem; 2 | 3 | public class SharedFlag { 4 | 5 | private boolean flag = false; 6 | 7 | public synchronized boolean isFlag() { 8 | return flag; 9 | } 10 | 11 | public synchronized void setFlag(boolean flag) { 12 | this.flag = flag; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/abstractinterface/Animal.java: -------------------------------------------------------------------------------- 1 | package abstractinterface; 2 | 3 | abstract class Animal { 4 | String name; 5 | 6 | Animal(String name) { 7 | this.name = name; 8 | } 9 | 10 | abstract void sound(); 11 | 12 | void sleep() { 13 | System.out.println 14 | (name + " is sleeping."); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/Generics/GenericsInJava.java: -------------------------------------------------------------------------------- 1 | package Generics; 2 | 3 | 4 | public class GenericsInJava { 5 | public static void main(String[] args) { 6 | Generic genericInteger = new Generic(); 7 | genericInteger.setItem(1); 8 | 9 | int item = genericInteger.getItem(); 10 | System.out.println(item); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/ConstructorFinal/Parent.java: -------------------------------------------------------------------------------- 1 | package ConstructorFinal; 2 | 3 | public class Parent { 4 | public Parent() { 5 | } 6 | final public void method(){ 7 | System.out.println 8 | ("Method in Parent"); 9 | } 10 | 11 | public static void main(String[] args) { 12 | System.out.println("parent"); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/RecordsDemo/RecordsDemo.java: -------------------------------------------------------------------------------- 1 | package RecordsDemo; 2 | 3 | public class RecordsDemo { 4 | 5 | public static void main(String[] args) { 6 | Student s1 = new Student("John",20,"A"); 7 | Student s2 = new Student("Paul",25,"B"); 8 | 9 | System.out.println(s1.toString()); 10 | System.out.println(s2.name()); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/EnumDemo/EnumDemo.java: -------------------------------------------------------------------------------- 1 | package EnumDemo; 2 | enum Day { 3 | SUNDAY, 4 | MONDAY, 5 | TUESDAY, 6 | WEDNESDAY, 7 | THURSDAY, 8 | FRIDAY, 9 | SATURDAY; 10 | } 11 | public class EnumDemo { 12 | public static void main(String[] args) { 13 | String monday = Day.MONDAY.toString(); 14 | System.out.println(monday); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/SwapNumbers/SwapTwoNumbers.java: -------------------------------------------------------------------------------- 1 | package SwapNumbers; 2 | 3 | public class SwapTwoNumbers { 4 | public static void main(String[] args) { 5 | int a = 5; 6 | int b = 9; 7 | // Bitwise XOR 8 | a=a^b; 9 | b=a^b; 10 | a=a^b; 11 | System.out.println(a +" " +b); 12 | 13 | 14 | 15 | } 16 | 17 | 18 | 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/Shortcuts/IntelliJVariableExtraction.java: -------------------------------------------------------------------------------- 1 | package Shortcuts; 2 | 3 | public class IntelliJVariableExtraction { 4 | public static void main(String[] args) { 5 | final String name = "John"; 6 | final int age = 10; 7 | String greeting = "Hello, " + name + "! You are " + age + " years old."; 8 | System.out.println(greeting); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/solid/s/FilterBooks.java: -------------------------------------------------------------------------------- 1 | package solid.s; 2 | 3 | public class FilterBooks { 4 | 5 | public Boolean checkBookGenres(Book book,String genre){ 6 | return book.isWordInText(genre); 7 | } 8 | 9 | public Book FilterBookByGenres(String genre){ 10 | //filter books according to genre 11 | return new Book(null,null,null); 12 | } 13 | 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/VarKeyword/VarKeywordDemo.java: -------------------------------------------------------------------------------- 1 | package VarKeyword; 2 | 3 | public class VarKeywordDemo { 4 | public static void main(String[] args) { 5 | var name = "CodeSnippet"; 6 | var count = 0; 7 | for (int i = 1; i < 5; i++) { 8 | ++count; 9 | } 10 | System.out.println("Count: " + count); 11 | System.out.println(name); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/Streams/CountExample.java: -------------------------------------------------------------------------------- 1 | package Streams; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public class CountExample { 7 | public static void main(String[] args) { 8 | List numbers = Arrays.asList(1, 2, 3, 4, 5); 9 | 10 | final long count = numbers.stream() 11 | .count(); 12 | 13 | System.out.println(count); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/Streams/ReduceExample.java: -------------------------------------------------------------------------------- 1 | package Streams; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public class ReduceExample { 7 | public static void main(String[] args) { 8 | List list = Arrays.asList(1,2,3,4,5); 9 | 10 | final Integer sum = list.stream() 11 | .reduce(0, (a, b) -> a + b); 12 | System.out.println(sum); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/FunctionalInterface/FunctionalInterfaceDemo.java: -------------------------------------------------------------------------------- 1 | package FunctionalInterface; 2 | 3 | public class FunctionalInterfaceDemo { 4 | public static void main(String[] args) { 5 | Operation addition = (a, b) -> a + b; 6 | Operation subtraction = (a, b) -> a - b; 7 | 8 | System.out.println(addition.operate(2,3)); 9 | System.out.println(subtraction.operate(3,2)); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/VarArgs/Sum.java: -------------------------------------------------------------------------------- 1 | package VarArgs; 2 | 3 | public class Sum { 4 | public static int sum( int... numbers) { 5 | int sum = 0; 6 | for (int num : numbers) { 7 | sum += num; 8 | } 9 | return sum; 10 | } 11 | public static void main(String[] args) { 12 | System.out.println(sum(1,2)); 13 | System.out.println(sum(1,2,3,4,5)); 14 | } 15 | } 16 | 17 | -------------------------------------------------------------------------------- /src/Streams/LimitExample.java: -------------------------------------------------------------------------------- 1 | package Streams; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.stream.Collectors; 6 | 7 | public class LimitExample { 8 | public static void main(String[] args) { 9 | List numbers = Arrays.asList(1, 2, 3, 4, 5); 10 | numbers.stream() 11 | .limit(3) 12 | .forEach(System.out::println); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/solid/d/BuyComputerApp.java: -------------------------------------------------------------------------------- 1 | package solid.d; 2 | 3 | public class BuyComputerApp { 4 | public static void main(String[] args) { 5 | StandardKeyboard keyboard = new StandardKeyboard(); 6 | keyboard.setBrand("HP"); 7 | Monitor monitor = new Monitor(); 8 | monitor.setBrand("Dell"); 9 | AppleComputer computer = 10 | new AppleComputer(keyboard,monitor); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/FinalFinallyFinalize/FinallyExample.java: -------------------------------------------------------------------------------- 1 | package FinalFinallyFinalize; 2 | 3 | public class FinallyExample { 4 | public static void main(String[] args) { 5 | try { 6 | String str = null; 7 | System.out.println(str.length()); 8 | } catch (NullPointerException | ArithmeticException ex) { 9 | System.out.println(ex.getClass().getSimpleName()); 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/Streams/AnyMatchExample.java: -------------------------------------------------------------------------------- 1 | package Streams; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public class AnyMatchExample { 7 | public static void main(String[] args) { 8 | List numbers = Arrays.asList(1, 3, 5); 9 | 10 | final boolean b = numbers.stream() 11 | .anyMatch(number -> number % 2 == 0); 12 | 13 | System.out.println(b); 14 | 15 | } 16 | } 17 | 18 | -------------------------------------------------------------------------------- /src/Streams/SumExample.java: -------------------------------------------------------------------------------- 1 | package Streams; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public class SumExample { 7 | public static void main(String[] args) { 8 | List numbers = Arrays.asList(1, 2, 3, 4, 5); 9 | 10 | final int sum = numbers.stream() 11 | .mapToInt(Integer::intValue) 12 | .sum(); 13 | System.out.println(sum ); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/StreamAnymatch/Order.java: -------------------------------------------------------------------------------- 1 | package StreamAnymatch; 2 | 3 | public class Order { 4 | private int orderId; 5 | private double amount; 6 | 7 | public Order(int orderId, double amount) { 8 | this.orderId = orderId; 9 | this.amount = amount; 10 | } 11 | 12 | public int getOrderId() { 13 | return orderId; 14 | } 15 | 16 | public double getAmount() { 17 | return amount; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/Streams/DistinctExample.java: -------------------------------------------------------------------------------- 1 | package Streams; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.stream.Collectors; 6 | 7 | public class DistinctExample { 8 | public static void main(String[] args) { 9 | List numbers = Arrays.asList(1, 2, 2, 3, 4, 4, 5); 10 | 11 | numbers.stream() 12 | .distinct() 13 | .forEach(System.out::println); 14 | } 15 | } 16 | 17 | -------------------------------------------------------------------------------- /src/Streams/FilterExample.java: -------------------------------------------------------------------------------- 1 | package Streams; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.stream.Collectors; 6 | 7 | public class FilterExample { 8 | public static void main(String[] args) { 9 | List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); 10 | 11 | numbers.stream() 12 | .filter(n -> n%2 ==0) 13 | .forEach(System.out::println); 14 | 15 | } 16 | } 17 | 18 | -------------------------------------------------------------------------------- /src/Streams/MapExample.java: -------------------------------------------------------------------------------- 1 | package Streams; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.stream.Collectors; 6 | 7 | public class MapExample { 8 | public static void main(String[] args) { 9 | List names = Arrays.asList("alice", "bob", "charlie"); 10 | 11 | names.stream() 12 | .map(String::toUpperCase) 13 | .forEach(System.out::println); 14 | 15 | } 16 | } 17 | 18 | -------------------------------------------------------------------------------- /src/StreamAllMatch/Employee.java: -------------------------------------------------------------------------------- 1 | package StreamAllMatch; 2 | 3 | public class Employee { 4 | private int employeeId; 5 | private double salary; 6 | 7 | public Employee(int employeeId, double salary) { 8 | this.employeeId = employeeId; 9 | this.salary = salary; 10 | } 11 | 12 | public int getEmployeeId() { 13 | return employeeId; 14 | } 15 | 16 | public double getSalary() { 17 | return salary; 18 | } 19 | } 20 | 21 | -------------------------------------------------------------------------------- /src/Multicatch/MultiCatch.java: -------------------------------------------------------------------------------- 1 | package Multicatch; 2 | 3 | public class MultiCatch { 4 | public static void main(String[] args) { 5 | try{ 6 | int a[] = new int [5]; 7 | a[5]= 30; 8 | }catch (ArithmeticException 9 | | ArrayIndexOutOfBoundsException e){ 10 | System.out.println("ArithmeticException"); 11 | }catch (Exception e){ 12 | System.out.println("Exception"); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/Streams/MinMaxExample.java: -------------------------------------------------------------------------------- 1 | package Streams; 2 | 3 | import java.util.Arrays; 4 | import java.util.Comparator; 5 | import java.util.List; 6 | import java.util.Optional; 7 | 8 | public class MinMaxExample { 9 | public static void main(String[] args) { 10 | List numbers = Arrays.asList(1, 2, 3, 4, 5); 11 | final Optional min = 12 | numbers.stream().max(Comparator.naturalOrder()); 13 | 14 | System.out.println(min.get()); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/ZeroOneSum/ZeroOne.java: -------------------------------------------------------------------------------- 1 | package ZeroOneSum; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.concurrent.atomic.AtomicInteger; 6 | 7 | public class ZeroOne { 8 | public static void main(String[] args) { 9 | List list = 10 | Arrays.asList(0,1,1,0,0,1,0,0,1,1,1); 11 | final Integer sum = list.stream() 12 | .reduce(0, Integer::sum); 13 | System.out.println(sum); 14 | 15 | 16 | 17 | 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/Streams/SkipExample.java: -------------------------------------------------------------------------------- 1 | package Streams; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.stream.Collectors; 6 | 7 | public class SkipExample { 8 | public static void main(String[] args) { 9 | List numbers = Arrays.asList(1, 2, 3, 4, 5); 10 | final List listAfterSkip = numbers.stream() 11 | .skip(2) 12 | .collect(Collectors.toList()); 13 | System.out.println(listAfterSkip); 14 | } 15 | } 16 | 17 | -------------------------------------------------------------------------------- /src/Stream/FilterExample.java: -------------------------------------------------------------------------------- 1 | package Stream; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public class FilterExample { 7 | public static void main(String[] args) { 8 | // Create a list of ages 9 | List ages = 10 | Arrays.asList(15, 20, 25, 30, 16, 18, 22); 11 | 12 | final List adults = ages.stream() 13 | .filter(n -> n >= 18) 14 | .toList(); 15 | System.out.println(adults); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/solid/s/BookApplication.java: -------------------------------------------------------------------------------- 1 | package solid.s; 2 | 3 | public class BookApplication { 4 | public static void main(String[] args) { 5 | Book conjuring = 6 | new Book("Conjuring", 7 | "Author", 8 | "A horror book"); 9 | 10 | FilterBooks bookFilter = new FilterBooks(); 11 | if( bookFilter.checkBookGenres(conjuring,"horror")){ 12 | System.out.println("conjuring is horror book"); 13 | } 14 | 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/MainMethodOverloading.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | public class MainMethodOverloading { 4 | 5 | public static void main(String... args) { 6 | System.out.println 7 | ("Main method with String[] args"); 8 | } 9 | 10 | public static void main() { 11 | System.out.println 12 | ("Main method without arguments"); 13 | } 14 | 15 | public static void main(int x) { 16 | System.out.println 17 | ("Main method with int argument: " + x); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/OptionalDemo/OptionalDemo.java: -------------------------------------------------------------------------------- 1 | package OptionalDemo; 2 | 3 | import java.util.Optional; 4 | 5 | public class OptionalDemo { 6 | public static void main(String[] args) { 7 | String str = "follow"; 8 | Optional optionalString = Optional.ofNullable(str); 9 | 10 | if (optionalString.isPresent()) { 11 | System.out.println("Value is present: " + optionalString.get()); 12 | } else { 13 | System.out.println("Value is absent"); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/Streams/PeekExample.java: -------------------------------------------------------------------------------- 1 | package Streams; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.stream.Collectors; 6 | 7 | public class PeekExample { 8 | public static void main(String[] args) { 9 | List numbers = Arrays.asList(1, 2, 3, 4, 5); 10 | final List sqaredList = numbers.stream() 11 | .map(n -> n * n) 12 | .peek(System.out::println) 13 | .collect(Collectors.toList()); 14 | 15 | 16 | } 17 | } 18 | 19 | -------------------------------------------------------------------------------- /src/FailFastFailSafe/FailFast.java: -------------------------------------------------------------------------------- 1 | package FailFastFailSafe; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class FailFast { 6 | public static void main(String[] args) { 7 | //FailFastFailSafe.FailFast - ArrayList ,HashMap 8 | ArrayList list = new ArrayList<>(); 9 | list.add(100); 10 | list.add(200); 11 | list.add(300); 12 | 13 | list.forEach(item-> { 14 | System.out.println(item); 15 | list.add(400); 16 | }); 17 | 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/Streams/FindFirstExample.java: -------------------------------------------------------------------------------- 1 | package Streams; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.Optional; 6 | 7 | public class FindFirstExample { 8 | public static void main(String[] args) { 9 | List numbers = Arrays.asList(1, 2, 3, 4, 5); 10 | 11 | final Optional first = numbers.stream() 12 | .filter(number -> number % 2 == 0) 13 | .findFirst(); 14 | 15 | System.out.println(first.get()); 16 | 17 | } 18 | } 19 | 20 | -------------------------------------------------------------------------------- /src/StringAndStringBuilder/StringAndStringBuilder.java: -------------------------------------------------------------------------------- 1 | package StringAndStringBuilder; 2 | 3 | public class StringAndStringBuilder { 4 | public static void main(String[] args) { 5 | String str = "Apple"; 6 | System.out.println(str+":"+str.hashCode()); 7 | str=str.concat("pie"); 8 | System.out.println(str+":"+str.hashCode()); 9 | 10 | StringBuilder stringBuilder = new StringBuilder("Apple"); 11 | stringBuilder.append("pie"); 12 | System.out.println(stringBuilder); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/solid/l/VehicleApplication.java: -------------------------------------------------------------------------------- 1 | package solid.l; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class VehicleApplication { 7 | public static void main(String[] args) { 8 | List vehicles = new ArrayList<>(); 9 | vehicles.add(new MotorCycle()); 10 | vehicles.add(new Car()); 11 | 12 | 13 | vehicles.forEach(vehicle -> { 14 | System.out.println( 15 | vehicle.enginePower() 16 | ); 17 | }); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/Constr/Main.java: -------------------------------------------------------------------------------- 1 | package Constr; 2 | 3 | class Parent { 4 | Parent() { 5 | System.out.println 6 | ("Parent constructor called"); 7 | } 8 | } 9 | 10 | class Child extends Parent { 11 | Child() { 12 | //super(); // Explicit call to the superclass constructor 13 | System.out.println 14 | ("Child constructor called"); 15 | } 16 | } 17 | 18 | public class Main { 19 | public static void main(String[] args) { 20 | Child child = new Child(); 21 | } 22 | } 23 | 24 | -------------------------------------------------------------------------------- /src/Collections/Iterator/IteratorDemo.java: -------------------------------------------------------------------------------- 1 | package Collections.Iterator; 2 | 3 | import java.util.Arrays; 4 | import java.util.Iterator; 5 | import java.util.List; 6 | 7 | public class IteratorDemo { 8 | public static void main(String[] args) { 9 | List list = 10 | Arrays.asList(1,2,3,4,5); 11 | 12 | Iterator iterator = 13 | list.iterator(); 14 | 15 | while (iterator.hasNext()){ 16 | System.out.println(iterator.next()); 17 | } 18 | 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Quiz.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.Iterator; 3 | import java.util.List; 4 | import java.util.concurrent.CopyOnWriteArrayList; 5 | 6 | public class Quiz { 7 | public static void main(String[] args) { 8 | List numbers = Arrays.asList(1, 2, 3); 9 | Iterator iterator = numbers.iterator(); 10 | while (iterator.hasNext()) { 11 | int number = iterator.next(); 12 | numbers.remove(number); 13 | } 14 | System.out.println(numbers); 15 | } 16 | } 17 | 18 | -------------------------------------------------------------------------------- /src/Shortcuts/IntellijMethodExtraction.java: -------------------------------------------------------------------------------- 1 | package Shortcuts; 2 | 3 | public class IntellijMethodExtraction { 4 | 5 | public static void main(String[] args) { 6 | // Original code 7 | String firstName = "John"; 8 | String lastName = "Cena"; 9 | String fullName = getFullName(firstName, lastName); 10 | System.out.println("Full Name: " + fullName); 11 | } 12 | 13 | private static String getFullName(String firstName, String lastName) { 14 | return firstName + " " + lastName; 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/Predicate/PredicateInterfaceExample.java: -------------------------------------------------------------------------------- 1 | package Predicate; 2 | 3 | import java.util.function.Predicate; 4 | 5 | public class PredicateInterfaceExample { 6 | public static void main(String[] args) 7 | { 8 | // Creating predicate 9 | Predicate lesserThan 10 | = i -> (i < 18); 11 | Predicate greaterThanTen 12 | = (i) -> i > 10; 13 | // Calling Predicate method 14 | System.out.println 15 | (greaterThanTen.and(lesserThan).test(9)); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Atomicity/SharedCounter.java: -------------------------------------------------------------------------------- 1 | package Atomicity; 2 | 3 | import java.util.concurrent.atomic.AtomicInteger; 4 | 5 | public class SharedCounter { 6 | //Code without Atomic 7 | /* private int count=0; 8 | public void increment(){ 9 | count++; 10 | } 11 | public int getCount() { 12 | return count; 13 | }*/ 14 | private AtomicInteger count= new AtomicInteger(0); 15 | public void increment(){ 16 | count.incrementAndGet(); 17 | } 18 | public int getCount() { 19 | return count.get(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/Streams/CollectExample.java: -------------------------------------------------------------------------------- 1 | package Streams; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.stream.Collectors; 6 | 7 | public class CollectExample { 8 | public static void main(String[] args) { 9 | List list = Arrays.asList(1,2,3,4,5,6,7); 10 | final List evenSquredList = list.stream() 11 | .filter(x -> x % 2 == 0) 12 | .map(x -> x * x) 13 | .collect(Collectors.toList()); 14 | 15 | System.out.println(evenSquredList); 16 | 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/Collections/List/PriorityQueueDemo.java: -------------------------------------------------------------------------------- 1 | package Collections.List; 2 | 3 | import java.util.PriorityQueue; 4 | 5 | public class PriorityQueueDemo { 6 | public static void main(String[] args) { 7 | PriorityQueue pq = 8 | new PriorityQueue<>(); 9 | pq.add(6); 10 | pq.add(1); 11 | pq.add(3); 12 | pq.add(4); 13 | pq.add(8); 14 | pq.add(9); 15 | pq.add(2); 16 | 17 | 18 | System.out.println(pq); 19 | 20 | pq.poll(); 21 | System.out.println(pq); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/ThreadLifeCycle/TerminatedState.java: -------------------------------------------------------------------------------- 1 | package ThreadLifeCycle; 2 | 3 | public class TerminatedState implements Runnable { 4 | public static void main(String[] args) throws InterruptedException { 5 | Thread t1 = new Thread(new TerminatedState()); 6 | t1.start(); 7 | // The following sleep method will give enough time for 8 | // thread t1 to complete 9 | Thread.sleep(1000); 10 | System.out.println(t1.getState()); 11 | } 12 | 13 | @Override 14 | public void run() { 15 | // No processing in this block 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/MethodReferences/MethodReference.java: -------------------------------------------------------------------------------- 1 | package MethodReferences; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | import java.util.stream.Collectors; 7 | 8 | public class MethodReference{ 9 | 10 | public static void main(String[] args) { 11 | List integers = 12 | Arrays.asList(4,9,16,25,64); 13 | 14 | final List sqRootList = integers.stream() 15 | .map( Math::sqrt) 16 | .collect(Collectors.toList()); 17 | System.out.println(sqRootList); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/solid/o/GuitarApplication.java: -------------------------------------------------------------------------------- 1 | package solid.o; 2 | 3 | public class GuitarApplication { 4 | public static void main(String[] args) { 5 | Guitar guitar = 6 | new Guitar("Maker", 7 | "Model", 8 | 10); 9 | SuperCoolGuitarsWithFlames guitarsWithFlames 10 | = new SuperCoolGuitarsWithFlames("Maker", 11 | "Model", 12 | 10,"yellowFlames"); 13 | System.out.println(guitar.getMake()); 14 | System.out.println(guitarsWithFlames.getFlameColor()); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/HashmapDemo/HashMapDemo.java: -------------------------------------------------------------------------------- 1 | package HashmapDemo; 2 | 3 | import java.util.HashMap; 4 | 5 | public class HashMapDemo { 6 | public static void main(String[] args) { 7 | HashMap map = new HashMap<>(); 8 | map.put("Sachin",30); 9 | //index = hashCode(key) & (n-1). 10 | 11 | /* { 12 | int hash = 115 13 | Key key = {"sachin"} 14 | Integer value = 30 15 | Node next = null 16 | }*/ 17 | 18 | map.put("Vishal",20); 19 | map.put("Vaibhav",20); 20 | 21 | System.out.println(map); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/Thread/PrintEvenOdd.java: -------------------------------------------------------------------------------- 1 | package Thread; 2 | 3 | public class PrintEvenOdd { 4 | public static void main(String[] args) { 5 | int MAX=10; 6 | 7 | // create instances of EvenOddRunnable classes 8 | EvenOddRunnable runnable1 = new EvenOddRunnable(1, MAX ); 9 | EvenOddRunnable runnable2 = new EvenOddRunnable(0, MAX); 10 | // create thread1 and thread2 11 | Thread thread1 = new Thread(runnable1,"Odd"); 12 | Thread thread2 = new Thread(runnable2,"Even"); 13 | // use start() method to start thread1 and thread2 14 | thread1.start(); 15 | thread2.start(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Streams/FlatMapExample.java: -------------------------------------------------------------------------------- 1 | package Streams; 2 | 3 | 4 | import java.util.Arrays; 5 | import java.util.Collection; 6 | import java.util.List; 7 | import java.util.stream.Collectors; 8 | 9 | public class FlatMapExample { 10 | public static void main(String[] args) { 11 | List> listOfLists = Arrays.asList( 12 | Arrays.asList("a", "b"), 13 | Arrays.asList("c", "d"), 14 | Arrays.asList("e", "f") 15 | ); 16 | listOfLists.stream() 17 | .flatMap(Collection::stream) 18 | .map(String::toUpperCase) 19 | .forEach(System.out::println); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/solid/o/SuperCoolGuitarsWithFlames.java: -------------------------------------------------------------------------------- 1 | package solid.o; 2 | 3 | public class SuperCoolGuitarsWithFlames extends Guitar{ 4 | private String flameColor; 5 | 6 | public SuperCoolGuitarsWithFlames(String make, 7 | String model, 8 | int volume, 9 | String flameColor) { 10 | super(make, model, volume); 11 | this.flameColor=flameColor; 12 | } 13 | 14 | public String getFlameColor() { 15 | return flameColor; 16 | } 17 | 18 | public void setFlameColor(String flameColor) { 19 | this.flameColor = flameColor; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/CompareEnums.java: -------------------------------------------------------------------------------- 1 | public class CompareEnums { 2 | public enum DayOfWeek { 3 | MONDAY, 4 | TUESDAY, 5 | WEDNESDAY, 6 | THURSDAY, 7 | FRIDAY, 8 | SATURDAY, 9 | SUNDAY 10 | } 11 | public static void main(String[] args) { 12 | DayOfWeek enum1 = DayOfWeek.MONDAY; 13 | DayOfWeek enum2 = DayOfWeek.MONDAY; 14 | 15 | if(enum1==enum2){ 16 | System.out.println("=="); 17 | } 18 | 19 | } 20 | 21 | /* public static int sum(int... numbers) { 22 | int sum = 0; 23 | for (int num : numbers) { 24 | sum += num; 25 | } 26 | return sum; 27 | }*/ 28 | } 29 | -------------------------------------------------------------------------------- /src/FailFastFailSafe/FailSafe.java: -------------------------------------------------------------------------------- 1 | package FailFastFailSafe; 2 | 3 | import java.util.List; 4 | import java.util.concurrent.CopyOnWriteArrayList; 5 | 6 | public class FailSafe { 7 | 8 | public static void main(String[] args) { 9 | //FailFastFailSafe.FailSafe - CopyOnWriteArrayList , ConcurrentHashMap 10 | List list = new CopyOnWriteArrayList<>(); 11 | list.add(100); 12 | list.add(200); 13 | list.add(300); 14 | 15 | list.forEach(item-> { 16 | System.out.println(item); 17 | list.add(400); 18 | }); 19 | list.forEach(item-> { 20 | System.out.println(item); 21 | }); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/CreateStreamFromArray/CreateStreamFromArray.java: -------------------------------------------------------------------------------- 1 | package CreateStreamFromArray; 2 | 3 | import java.util.Arrays; 4 | import java.util.stream.IntStream; 5 | import java.util.stream.Stream; 6 | 7 | public class CreateStreamFromArray { 8 | public static void main(String[] args) { 9 | //Primitive Array 10 | int[] intArray = {1,2,3,4}; 11 | //Object Arrays 12 | Integer[] integerArray = {1,2,3,4}; 13 | 14 | final IntStream stream = Arrays.stream(intArray); 15 | stream.forEach(System.out::println); 16 | 17 | final Stream integerArrayObject = Stream.of(integerArray); 18 | 19 | integerArrayObject.forEach(System.out::println); 20 | 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/ArrayVSArraylist/ArrayExample.java: -------------------------------------------------------------------------------- 1 | package ArrayVSArraylist; 2 | 3 | public class ArrayExample { 4 | public static void main(String[] args) { 5 | // Declare and initialize an array of integers 6 | int[] numbers = new int[5]; 7 | numbers[0] = 1; 8 | numbers[1] = 2; 9 | numbers[2] = 3; 10 | numbers[3] = 4; 11 | numbers[4] = 5; 12 | 13 | // Access elements in the array 14 | System.out.println("Array elements:"); 15 | for (int i = 0; i < numbers.length; i++) { 16 | System.out.println(numbers[i]); 17 | } 18 | 19 | // Size of the array is fixed 20 | System.out.println("Array size: " + numbers.length); 21 | } 22 | } 23 | 24 | -------------------------------------------------------------------------------- /src/StreamProblems/WordFrequency.java: -------------------------------------------------------------------------------- 1 | package StreamProblems; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.Map; 6 | import java.util.stream.Collectors; 7 | 8 | public class WordFrequency { 9 | public static void main(String[] args) { 10 | List words = Arrays.asList( 11 | "apple", "banana", "apple", 12 | "orange", "banana", "pear", 13 | "apple", "banana"); 14 | 15 | Map wordFrequency = words.stream() 16 | .collect(Collectors.groupingBy 17 | (word -> word, Collectors.counting())); 18 | 19 | System.out.println("Word frequency: " + wordFrequency); 20 | } 21 | } 22 | 23 | -------------------------------------------------------------------------------- /src/Optional/OptionalClassDemo.java: -------------------------------------------------------------------------------- 1 | package Optional; 2 | 3 | import java.util.Optional; 4 | 5 | public class OptionalClassDemo { 6 | private Optional getUserName(int id){ 7 | if(id==0){ 8 | return Optional.ofNullable(null); 9 | }else { 10 | return Optional.ofNullable("FollowCodeSnippet"); 11 | } 12 | } 13 | public static void main(String[] args) { 14 | OptionalClassDemo optionalClassDemo = new OptionalClassDemo(); 15 | Optional userName = optionalClassDemo.getUserName(1); 16 | 17 | userName.ifPresentOrElse( 18 | (uName) -> System.out.println("username "+uName), 19 | ()-> System.out.println("username not found") 20 | ); 21 | 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/Code/CleanCode.java: -------------------------------------------------------------------------------- 1 | package Code; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public class CleanCode { 7 | public static void main(String[] args) { 8 | List list 9 | = Arrays.asList(1,2,3,4,5,6,7,8,9,10); 10 | final List output = list.stream() 11 | .filter(CleanCode::checkValidation) 12 | .toList(); 13 | System.out.println(output); 14 | 15 | } 16 | 17 | private static boolean checkValidation(Integer x) { 18 | boolean isEven = x % 2 == 0; 19 | boolean isGreaterThanFive = x > 5; 20 | boolean isDivisibleByThree = x % 3 == 0; 21 | return isEven && 22 | isGreaterThanFive && 23 | isDivisibleByThree; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/PrePostfix/PrePostFixDemo.java: -------------------------------------------------------------------------------- 1 | package PrePostfix; 2 | 3 | public class PrePostFixDemo { 4 | public static void main(String[] args) { 5 | int x = 5; 6 | // Prefix Increment (++x): The value of the variable is incremented by one before it is used in an expression. 7 | //int y = ++x; 8 | 9 | //Prefix Decrement (--x): 10 | //int y = --x; 11 | 12 | //Postfix Increment (x++) The current value of the variable is used in the expression, and then it is incremented by one. 13 | //int y = x++; 14 | 15 | //Postfix Decrement (x--): 16 | int y = x--; 17 | 18 | System.out.println("x : "+ x ); 19 | System.out.println("y : "+ y ); 20 | 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/solid/o/Guitar.java: -------------------------------------------------------------------------------- 1 | package solid.o; 2 | 3 | public class Guitar { 4 | private String make; 5 | private String model; 6 | private int volume; 7 | 8 | public Guitar(String make, String model, int volume) { 9 | this.make = make; 10 | this.model = model; 11 | this.volume = volume; 12 | } 13 | 14 | public String getMake() { 15 | return make; 16 | } 17 | 18 | public void setMake(String make) { 19 | this.make = make; 20 | } 21 | 22 | public String getModel() { 23 | return model; 24 | } 25 | 26 | public void setModel(String model) { 27 | this.model = model; 28 | } 29 | 30 | public int getVolume() { 31 | return volume; 32 | } 33 | 34 | public void setVolume(int volume) { 35 | this.volume = volume; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/Streams/ConvertToStreams.java: -------------------------------------------------------------------------------- 1 | package Streams; 2 | 3 | 4 | import java.util.Arrays; 5 | import java.util.List; 6 | import java.util.stream.IntStream; 7 | import java.util.stream.Stream; 8 | 9 | public class ConvertToStreams { 10 | public static void main(String[] args) { 11 | //Primitive Array 12 | int[] premitiveArray = {1,2,3,4}; 13 | //Object Arrays 14 | Integer[] objectArray = {1,2,3,4}; 15 | 16 | final IntStream intStream = Arrays.stream(premitiveArray); 17 | intStream.forEach(System.out::println); 18 | 19 | final Stream integerStream = Stream.of(objectArray); 20 | integerStream.forEach(System.out::println); 21 | 22 | List integerList = Arrays.asList(1,2,3,4); 23 | integerList.stream() 24 | .forEach(System.out::println); 25 | 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/Streams/SortedExample.java: -------------------------------------------------------------------------------- 1 | package Streams; 2 | 3 | import java.util.Arrays; 4 | import java.util.Comparator; 5 | import java.util.List; 6 | import java.util.stream.Collectors; 7 | 8 | public class SortedExample { 9 | public static void main(String[] args) { 10 | List numbers = Arrays.asList(5, 3, 1, 4, 2); 11 | 12 | numbers.stream(). 13 | sorted(Comparator.reverseOrder()). 14 | forEach(System.out::println); 15 | 16 | List words = 17 | Arrays.asList("apple", "banana", "kiwi", "cherry"); 18 | 19 | List sortedWordsByLength = words.stream() 20 | .sorted(Comparator.comparingInt(String::length) 21 | .reversed()) 22 | .toList(); 23 | sortedWordsByLength.forEach(System.out::println); 24 | 25 | } 26 | } 27 | 28 | -------------------------------------------------------------------------------- /src/ThreadLifeCycle/TimedWaitingState.java: -------------------------------------------------------------------------------- 1 | package ThreadLifeCycle; 2 | 3 | public class TimedWaitingState { 4 | public static void main(String[] args) throws InterruptedException { 5 | DemoTimeWaitingRunnable runnable= new DemoTimeWaitingRunnable(); 6 | Thread t1 = new Thread(runnable); 7 | t1.start(); 8 | 9 | // The following sleep will give enough time for ThreadScheduler 10 | // to start processing of thread t1 11 | Thread.sleep(1000); 12 | System.out.println(t1.getState()); 13 | } 14 | } 15 | 16 | class DemoTimeWaitingRunnable implements Runnable { 17 | @Override 18 | public void run() { 19 | try { 20 | Thread.sleep(5000); 21 | } catch (InterruptedException e) { 22 | Thread.currentThread().interrupt(); 23 | e.printStackTrace(); 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /src/Collections/List/StackDemo.java: -------------------------------------------------------------------------------- 1 | package Collections.List; 2 | 3 | import java.util.Stack; 4 | 5 | public class StackDemo { 6 | public static void main(String[] args) { 7 | // Creating an empty Stack 8 | Stack stack = new Stack(); 9 | 10 | // Use push() to add elements into the Stack 11 | stack.push("Follow"); 12 | stack.push("code"); 13 | stack.push("Snippet"); 14 | stack.push("Now"); 15 | 16 | // Displaying the Stack 17 | System.out.println("Initial Stack: " + stack); 18 | 19 | // Fetching the element at the head of the Stack 20 | System.out.println("The element at the top of the" 21 | + " stack is: " + stack.peek()); 22 | 23 | stack.pop(); 24 | // Displaying the Stack after the Operation 25 | System.out.println("Final Stack: " + stack); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/ThreadLifeCycle/BlockedState.java: -------------------------------------------------------------------------------- 1 | package ThreadLifeCycle; 2 | 3 | public class BlockedState { 4 | public static void main(String[] args) throws InterruptedException { 5 | Thread t1 = new Thread(new DemoBlockedRunnable()); 6 | Thread t2 = new Thread(new DemoBlockedRunnable()); 7 | 8 | t1.start(); 9 | t2.start(); 10 | 11 | Thread.sleep(1000); 12 | 13 | System.out.println(t2.getState()); 14 | System.exit(0); 15 | } 16 | } 17 | 18 | class DemoBlockedRunnable implements Runnable { 19 | @Override 20 | public void run() { 21 | commonResource(); 22 | } 23 | 24 | public static synchronized void commonResource() { 25 | while(true) { 26 | // Infinite loop to mimic heavy processing 27 | // 't1' won't leave this method 28 | // when 't2' try to enter this 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /src/Palindrome/NumberPalindrome.java: -------------------------------------------------------------------------------- 1 | package Palindrome; 2 | 3 | public class NumberPalindrome { 4 | public static void main(String[] args) { 5 | int r,sum=0,temp; 6 | int n=252;//It is the number variable to be checked for palindrome 7 | 8 | temp=n; 9 | while(n>0){ 10 | r=n%10; //getting remainder 11 | sum=(sum*10)+r; 12 | n=n/10; 13 | } 14 | //1 15 | // r= 252%10 = 2 16 | // sum= (0*10)+r = 2 17 | // n = 25 18 | 19 | //2 20 | //r = 25%10 = 5 21 | // sum = (2*10)+5 = 25 22 | // n = 2 23 | 24 | //3 25 | // r = 2%10 =2 26 | // sum = (25*10)+2 = 252 27 | //n=0 28 | 29 | if(temp==sum) 30 | System.out.println("palindrome number "); 31 | else 32 | System.out.println("not palindrome"); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/NextCharConverter.java: -------------------------------------------------------------------------------- 1 | public class NextCharConverter { 2 | public static void main(String[] args) { 3 | String input = "abcd"; //bcde 4 | String output = convertString(input); 5 | System.out.println("Input: " + input); 6 | System.out.println("Output: " + output); 7 | } 8 | 9 | public static String convertString(String input) { 10 | String result = ""; 11 | 12 | for (char c : input.toCharArray()) { 13 | if (Character.isLetter(c)) { 14 | if (c == 'z') { 15 | result += 'a'; 16 | } else if (c == 'Z') { 17 | result += 'A'; 18 | } else { 19 | result += (char) (c + 1); 20 | } 21 | } else { 22 | result += c; 23 | } 24 | } 25 | 26 | return result; 27 | } 28 | } 29 | 30 | -------------------------------------------------------------------------------- /src/AbstractInterface.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | public class AbstractInterface { 4 | } 5 | 6 | //defining a skill or behaviour 7 | 8 | interface programmable { 9 | void programming(); 10 | } 11 | interface Drivable { 12 | void start(); 13 | void stop(); 14 | void honk(); 15 | } 16 | 17 | //group of related classes 18 | //inheritance //hierarchy 19 | abstract class Vehicle { 20 | protected int fuelLevel; 21 | protected int speed; 22 | 23 | public Vehicle(int fuelLevel) { 24 | this.fuelLevel = fuelLevel; 25 | this.speed = 0; 26 | } 27 | 28 | public void refuel(int amount) { 29 | this.fuelLevel += amount; 30 | } 31 | 32 | public void accelerate(int increment) { 33 | this.speed += increment; 34 | } 35 | 36 | public void brake(int decrement) { 37 | this.speed -= decrement; 38 | } 39 | 40 | public abstract void drive(); 41 | } 42 | 43 | 44 | -------------------------------------------------------------------------------- /src/BoundedTypeDemo/BoundedTypeDemo.java: -------------------------------------------------------------------------------- 1 | package BoundedTypeDemo; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public class BoundedTypeDemo { 7 | 8 | public static void main(String[] args) { 9 | List integerList = Arrays.asList(1,2,4,5); 10 | findMax(integerList); 11 | 12 | List doubleList = Arrays.asList(1.0,2.1,8.1); 13 | findMax(doubleList); 14 | } 15 | 16 | private static > void findMax(List list) { 17 | if(list==null || list.isEmpty()) { 18 | throw new IllegalArgumentException("Empty list"); 19 | } 20 | T max = list.get(0); 21 | for (int i =0 ; i< list.size();i++){ 22 | T curr = list.get(i); 23 | if(curr.compareTo(max) == 1){ 24 | max = curr; 25 | } 26 | } 27 | System.out.println("Maximum Element is : "+ max); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/groupingby/Employee.java: -------------------------------------------------------------------------------- 1 | package groupingby; 2 | 3 | public class Employee { 4 | String name; 5 | String department; 6 | Integer salary; 7 | public Employee(String name, String department, Integer salary) { 8 | this.name = name; 9 | this.department = department; 10 | this.salary = salary; 11 | } 12 | 13 | public String getName() { 14 | return name; 15 | } 16 | 17 | public void setName(String name) { 18 | this.name = name; 19 | } 20 | 21 | public String getDepartment() { 22 | return department; 23 | } 24 | 25 | public Integer getSalary() { 26 | return salary; 27 | } 28 | 29 | @Override 30 | public String toString() { 31 | return "Employee{" + 32 | "name='" + name + '\'' + 33 | ", department='" + department + '\'' + 34 | ", salary=" + salary + 35 | '}'; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/StreamAnymatch/AnyMatchExample.java: -------------------------------------------------------------------------------- 1 | package StreamAnymatch; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public class AnyMatchExample { 7 | public static void main(String[] args) { 8 | List orders = Arrays.asList( 9 | new Order(1, 250.0), 10 | new Order(2, 450.0), 11 | new Order(3, 150.0), 12 | new Order(4, 350.0), 13 | new Order(5, 50.0) 14 | ); 15 | 16 | double highValueThreshold = 400.0; 17 | 18 | boolean hasHighValueOrder = orders.stream() 19 | .anyMatch(order -> order.getAmount() > highValueThreshold); 20 | 21 | if (hasHighValueOrder) { 22 | System.out.println 23 | ("There is at least one high-value order."); 24 | } else { 25 | System.out.println 26 | ("There are no high-value orders."); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/ThreadLifeCycle/WaitingState.java: -------------------------------------------------------------------------------- 1 | package ThreadLifeCycle; 2 | 3 | public class WaitingState implements Runnable { 4 | public static Thread t1; 5 | 6 | public static void main(String[] args) { 7 | t1 = new Thread(new WaitingState()); 8 | t1.start(); 9 | } 10 | 11 | public void run() { 12 | Thread t2 = new Thread(new DemoWaitingStateRunnable()); 13 | t2.start(); 14 | 15 | try { 16 | t2.join(); 17 | } catch (InterruptedException e) { 18 | Thread.currentThread().interrupt(); 19 | e.printStackTrace(); 20 | } 21 | } 22 | } 23 | 24 | class DemoWaitingStateRunnable implements Runnable { 25 | public void run() { 26 | try { 27 | Thread.sleep(1000); 28 | } catch (InterruptedException e) { 29 | Thread.currentThread().interrupt(); 30 | e.printStackTrace(); 31 | } 32 | 33 | System.out.println(WaitingState.t1.getState()); 34 | } 35 | } -------------------------------------------------------------------------------- /src/Collections/List/VectorDemo.java: -------------------------------------------------------------------------------- 1 | package Collections.List; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collection; 5 | import java.util.Vector; 6 | 7 | public class VectorDemo { 8 | public static void main(String[] args) { 9 | //1 10 | Vector v = 11 | new Vector(); 12 | //2 13 | Vector vSize = 14 | new Vector(15); 15 | //3 16 | Vector vInc = 17 | new Vector(15, 18 | 5); 19 | //4 20 | Collection collection = new ArrayList<>(); 21 | Vector vCollection = 22 | new Vector(collection); 23 | 24 | v.add(1); 25 | v.add(2); 26 | System.out.println(v); 27 | v.remove(1); 28 | System.out.println(v); 29 | 30 | 31 | //Synchronization 32 | //Dynamic Size 33 | 34 | //Disadvantage 35 | //Performance 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/SortUsingStreams.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.Comparator; 3 | import java.util.List; 4 | import java.util.stream.Collectors; 5 | 6 | public class SortUsingStreams { 7 | public static void main(String[] args) { 8 | List numbers = 9 | Arrays.asList(5, 3, 9, 1, 6, 2); 10 | 11 | List sortedNumbersDesc = 12 | numbers.stream() 13 | .sorted(Comparator.reverseOrder()) 14 | .toList(); 15 | 16 | System.out.println("Sorted numbers in descending order: " + 17 | "" + sortedNumbersDesc); 18 | 19 | List words = 20 | Arrays.asList("apple", "banana", "kiwi", "cherry"); 21 | 22 | List sortedWordsByLength = words.stream() 23 | .sorted(Comparator.comparingInt(String::length).reversed()) 24 | .toList(); 25 | 26 | System.out.println("Sorted words by length: " 27 | + sortedWordsByLength); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/VisibilityProblem/Volatile.java: -------------------------------------------------------------------------------- 1 | package VisibilityProblem; 2 | 3 | import VisibilityProblem.SharedFlag; 4 | 5 | public class Volatile{ 6 | 7 | public static void main(String[] args) { 8 | SharedFlag flag = new SharedFlag(); 9 | //Thread 1 10 | new Thread(() -> { 11 | try { 12 | System.out.println("Thread 1 started"); 13 | Thread.sleep(1000); 14 | flag.setFlag(true); 15 | System.out.println("Flag set to True by thread 1 "); 16 | System.out.println("Thread 1 Completed"); 17 | }catch (InterruptedException e){ 18 | e.printStackTrace(); 19 | } 20 | }).start(); 21 | 22 | //Thread 2 23 | new Thread(() -> { 24 | System.out.println("Thread 2 started"); 25 | while(!flag.isFlag()) { 26 | //some processing 27 | } 28 | System.out.println("Thread 2 Completed"); 29 | }).start(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/MyClass.java: -------------------------------------------------------------------------------- 1 | interface MyInterface { 2 | void method(); 3 | // Default method 4 | default void defaultMethod() { 5 | System.out.println("Default method implementation"); 6 | } 7 | 8 | // Static method 9 | static void staticMethod() { 10 | System.out.println("Static method implementation"); 11 | } 12 | } 13 | 14 | class MyClass implements MyInterface { 15 | // No need to override defaultMethod() as it has a default implementation 16 | 17 | 18 | @Override 19 | public void defaultMethod() { 20 | System.out.println("custom implementation"); 21 | } 22 | 23 | public static void main(String[] args) { 24 | MyClass obj = new MyClass(); 25 | 26 | // Calling default method 27 | obj.defaultMethod(); // Output: Default method implementation 28 | 29 | // Calling static method 30 | MyInterface.staticMethod(); // Output: Static method implementation 31 | } 32 | 33 | @Override 34 | public void method() { 35 | 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/AutoAndUnboxingDemo/AutoboxingUnboxingExample.java: -------------------------------------------------------------------------------- 1 | package AutoAndUnboxingDemo; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class AutoboxingUnboxingExample { 7 | public static void main(String[] args) { 8 | // Create a list of integers 9 | List integerList = new ArrayList<>(); 10 | 11 | // Autoboxing: Converting primitive int to Integer object 12 | int num1 = 10; 13 | Integer numObject1 = num1; // Autoboxing 14 | 15 | // Add the Integer object to the list 16 | integerList.add(numObject1); 17 | 18 | // Unboxing: Converting Integer object to primitive int 19 | Integer numObject2 = integerList.get(0); 20 | int num2 = numObject2; // Unboxing 21 | 22 | // Print the values 23 | System.out.println 24 | ("Autoboxing: Primitive int to Integer object: " + numObject1); 25 | System.out.println 26 | ("Unboxing: Integer object to primitive int: " + num2); 27 | } 28 | } 29 | 30 | -------------------------------------------------------------------------------- /src/StringBufferVsStringBuilder/StringBufferVsBuilder.java: -------------------------------------------------------------------------------- 1 | package StringBufferVsStringBuilder; 2 | 3 | public class StringBufferVsBuilder { 4 | public static void main(String[] args) { 5 | StringBuffer string = new StringBuffer(); 6 | //Thread 1 7 | Thread thread1 = new Thread(() -> { 8 | for (int i = 0; i < 1000; i++) { 9 | string.append("A"); 10 | } 11 | }); 12 | //Thread 2 13 | Thread thread2 = new Thread(() -> { 14 | for (int i =0;i<1000;i++){ 15 | string.append("B"); 16 | } 17 | }); 18 | //Start Threads 19 | thread1.start(); 20 | thread2.start(); 21 | //Wait for threads to complete 22 | try { 23 | thread1.join(); 24 | thread2.join(); 25 | }catch (InterruptedException e){ 26 | e.printStackTrace(); 27 | } 28 | 29 | System.out.println("Result : " 30 | + string.toString().length()); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/completableFuture/OnlineOrderingSystem.java: -------------------------------------------------------------------------------- 1 | package completableFuture; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | 5 | public class OnlineOrderingSystem { 6 | public static void main(String[] args) { 7 | // Task 1: Notify Kitchen Staff 8 | CompletableFuture notifyKitchenTask = CompletableFuture.runAsync(() -> { 9 | // Simulate notifying kitchen staff 10 | System.out.println("Order notification sent to kitchen staff"); 11 | }); 12 | 13 | // Task 2: Send Confirmation Email 14 | CompletableFuture sendEmailTask = CompletableFuture.runAsync(() -> { 15 | // Simulate sending confirmation email 16 | System.out.println("Confirmation email sent to customer"); 17 | }); 18 | 19 | // Wait for all tasks to complete 20 | CompletableFuture allTasks = CompletableFuture.allOf(notifyKitchenTask, sendEmailTask); 21 | allTasks.join(); 22 | 23 | System.out.println("Order processing completed"); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/Lambda/FilterExample.java: -------------------------------------------------------------------------------- 1 | package Lambda; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.function.Function; 6 | import java.util.function.Predicate; 7 | 8 | public class FilterExample { 9 | public static void main(String[] args) { 10 | List numbers = new ArrayList<>(); 11 | numbers.add(1); 12 | numbers.add(2); 13 | numbers.add(3); 14 | numbers.add(4); 15 | numbers.add(5); 16 | 17 | // Using anonymous inner class 18 | numbers.removeIf(integer -> integer % 2 == 0); 19 | 20 | // Print the filtered list 21 | StringBuffer sb = new StringBuffer("Code"); 22 | sb.append("Snippet"); 23 | sb.insert(4, " "); 24 | 25 | System.out.println(sb); 26 | } 27 | } 28 | class Parent { 29 | public void display() { 30 | System.out.println("Parent class"); 31 | } 32 | } 33 | 34 | class Child extends Parent { 35 | public void display() { 36 | System.out.println("Child class"); 37 | } 38 | } 39 | 40 | -------------------------------------------------------------------------------- /src/groupingby/GroupingByDemo.java: -------------------------------------------------------------------------------- 1 | package groupingby; 2 | 3 | import java.util.*; 4 | import java.util.stream.Collectors; 5 | 6 | public class GroupingByDemo { 7 | public static void main(String[] args) { 8 | List employees = Arrays.asList( 9 | new Employee("Alice", "HR", 3000), 10 | new Employee("Bob", "IT", 4000), 11 | new Employee("Charlie", "HR", 3500), 12 | new Employee("Dave", "IT", 4500), 13 | new Employee("Eve", "Finance", 5000) 14 | ); 15 | 16 | // Group employees by department 17 | Map> employeesByDepartment = 18 | employees.stream() 19 | .collect(Collectors.groupingBy(Employee::getDepartment)); 20 | 21 | // Print the grouped employees 22 | employeesByDepartment.forEach((department, employeeList) -> { 23 | System.out.println("Department: " + department); 24 | employeeList.forEach(System.out::println); 25 | }); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/Collections/List/ArrayListDemo.java: -------------------------------------------------------------------------------- 1 | package Collections.List; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collection; 5 | 6 | public class ArrayListDemo { 7 | public static void main(String[] args) { 8 | //3 ways to initialize arraylist 9 | //1 10 | ArrayList arr = 11 | new ArrayList(); 12 | //2 13 | Collection collection = new ArrayList<>(); 14 | 15 | ArrayList arrWithCollection 16 | = new ArrayList(collection); 17 | //3 18 | ArrayList arrWithSize = 19 | new ArrayList(15); 20 | 21 | arr.add(1); 22 | arr.add(2); 23 | arr.forEach(System.out::println); 24 | 25 | //Details: 26 | 27 | //ArrayList is Underlined 28 | // data Structure Resizable Array . 29 | 30 | //ArrayList Duplicates Are Allowed. 31 | // Insertion Order is Preserved. 32 | // Heterogeneous objects are allowed. 33 | // Null insertion is possible. 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/StreamAllMatch/AllMatchExample.java: -------------------------------------------------------------------------------- 1 | package StreamAllMatch; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public class AllMatchExample { 7 | public static void main(String[] args) { 8 | List employees = Arrays.asList( 9 | new Employee(1, 55000.0), 10 | new Employee(2, 75000.0), 11 | new Employee(3, 80000.0), 12 | new Employee(4, 60000.0), 13 | new Employee(5, 90000.0) 14 | ); 15 | 16 | double salaryThreshold = 50000.0; 17 | 18 | boolean allEmployeesAboveThreshold = employees.stream() 19 | .allMatch(employee -> 20 | employee.getSalary() > salaryThreshold); 21 | 22 | if (allEmployeesAboveThreshold) { 23 | System.out.println 24 | ("All employees have salaries above the threshold."); 25 | } else { 26 | System.out.println 27 | ("Not all employees have salaries above the threshold."); 28 | } 29 | } 30 | } 31 | 32 | -------------------------------------------------------------------------------- /src/groupingby/Student.java: -------------------------------------------------------------------------------- 1 | package groupingby; 2 | 3 | import java.util.Objects; 4 | 5 | public class Student { 6 | String name; 7 | Integer marks; 8 | String division; 9 | public Student(String name, Integer marks, String division) { 10 | this.name = name; 11 | this.marks = marks; 12 | this.division = division; 13 | } 14 | public String getName() { 15 | return name; 16 | } 17 | public Integer getMarks() { 18 | return marks; 19 | } 20 | public String getDivision() { 21 | return division; 22 | } 23 | 24 | @Override 25 | public boolean equals(Object o) { 26 | if (this == o) return true; 27 | if (o == null || getClass() != o.getClass()) return false; 28 | Student student = (Student) o; 29 | return Objects.equals(name, student.name) && Objects.equals(marks, student.marks) && Objects.equals(division, student.division); 30 | } 31 | 32 | @Override 33 | public int hashCode() { 34 | return Objects.hash(name, marks, division); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/Demo.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.LinkedHashMap; 3 | import java.util.LinkedHashSet; 4 | 5 | public class Demo { 6 | public static void main(String[] args) { 7 | 8 | //JAVA 17 9 | ArrayList list = 10 | new ArrayList(); 11 | list.add(1); 12 | list.add(2); 13 | list.add(3); 14 | list.add(4); 15 | list.add(5); 16 | 17 | System.out.println 18 | (list.get(0)); 19 | System.out.println 20 | (list.get(list.size()-1)); 21 | 22 | LinkedHashSet set = new LinkedHashSet(); 23 | set.add(1); 24 | set.add(2); 25 | set.add(3); 26 | 27 | System.out.println( set.iterator().next()); 28 | 29 | LinkedHashMap map = new LinkedHashMap(); 30 | map.put(1, 1); 31 | map.put(2, 2); 32 | map.put(3, 3); 33 | 34 | map.get(1); 35 | 36 | int x = 5; 37 | x *= (3 + 7); 38 | System.out.println(x); 39 | //System.out.println(x); 40 | 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/Set/SetDemo.java: -------------------------------------------------------------------------------- 1 | package Set; 2 | 3 | import java.util.HashSet; 4 | import java.util.LinkedHashSet; 5 | import java.util.Set; 6 | import java.util.TreeSet; 7 | 8 | public class SetDemo { 9 | 10 | public static void main(String[] args) { 11 | HashSet hashSet = new HashSet<>(); 12 | hashSet.add(3); 13 | hashSet.add(10); 14 | hashSet.add(4); 15 | hashSet.add(20); 16 | hashSet.add(50); 17 | System.out.println("HashSet :"+hashSet); 18 | 19 | LinkedHashSet linkedHashSet = new LinkedHashSet<>(); 20 | linkedHashSet.add(3); 21 | linkedHashSet.add(1); 22 | linkedHashSet.add(4); 23 | linkedHashSet.add(2); 24 | linkedHashSet.add(5); 25 | System.out.println("LinkedHashSet :"+linkedHashSet); 26 | 27 | Set treeSet = new TreeSet<>(); 28 | treeSet.add(3); 29 | treeSet.add(1); 30 | treeSet.add(4); 31 | treeSet.add(2); 32 | treeSet.add(5); 33 | System.out.println("TreeSet :"+treeSet); 34 | 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/Atomicity/Atomic.java: -------------------------------------------------------------------------------- 1 | package Atomicity; 2 | 3 | public class Atomic { 4 | public static void main(String[] args) { 5 | SharedCounter sharedCounter = new SharedCounter(); 6 | //Thread 1 7 | new Thread(() -> { 8 | System.out.println("Thread 1 started"); 9 | for (int i = 0; i < 50000; i++) { 10 | sharedCounter.increment(); 11 | } 12 | System.out.println("Thread 1 Completed"); 13 | }).start(); 14 | 15 | //Thread 2 16 | new Thread(() -> { 17 | System.out.println("Thread 2 started"); 18 | for (int i = 0; i < 50000; i++) { 19 | sharedCounter.increment(); 20 | } 21 | System.out.println("Thread 2 Completed"); 22 | }).start(); 23 | 24 | //wait for both threads to complete 25 | try { 26 | Thread.sleep(2000); 27 | } catch (InterruptedException e) { 28 | e.printStackTrace(); 29 | } 30 | System.out.println("Final Count : " + sharedCounter.getCount()); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/Collections/List/QueueDemo.java: -------------------------------------------------------------------------------- 1 | package Collections.List; 2 | 3 | import java.util.LinkedList; 4 | import java.util.Queue; 5 | 6 | public class QueueDemo { 7 | public static void main(String[] args) { 8 | Queue q 9 | = new LinkedList<>(); 10 | 11 | // Elements {10, 20, 30, 40, 50} 12 | // are added to the queue 13 | for (int i = 10; i <= 50; i += 10) 14 | q.add(i); 15 | 16 | // Printing the contents of queue. 17 | System.out.println( 18 | "The Elements of the queue are : " 19 | + q); 20 | 21 | // Removing queue's head. 22 | int x = q.remove(); 23 | System.out.println("Removed element - " 24 | + x); 25 | 26 | System.out.println(q); 27 | 28 | // Viewing queue's head 29 | int head = q.peek(); 30 | System.out.println("Head of the queue - " 31 | + head); 32 | 33 | int size = q.size(); 34 | System.out.println("Size of the queue - " 35 | + size); 36 | 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/SUMOFDIGITS/SumOfDigits.java: -------------------------------------------------------------------------------- 1 | package SUMOFDIGITS; 2 | 3 | public class SumOfDigits { 4 | public static void main(String[] args) { 5 | int number = 12345; 6 | int sum = sumOfDigitsUsingStream(number); 7 | System.out.println 8 | ("Sum of digits of " + number + " is: " + sum); 9 | } 10 | 11 | public static int sumOfDigits(int number) { 12 | int sum = 0; 13 | while (number > 0) { 14 | // Add the last digit to the sum 15 | sum += number % 10; 16 | // Remove the last digit from the number 17 | number /= 10; 18 | } 19 | return sum; 20 | } 21 | 22 | 23 | public static int sumOfDigitsUsingStream(int number) { 24 | return String.valueOf(number) 25 | .chars() // Convert the number to a stream of characters 26 | .map(Character::getNumericValue) // Map each character to its integer value 27 | .sum(); // Calculate the sum of the integers 28 | } 29 | } 30 | 31 | -------------------------------------------------------------------------------- /src/Collections/List/DequeueDemo.java: -------------------------------------------------------------------------------- 1 | package Collections.List; 2 | 3 | import java.util.ArrayDeque; 4 | import java.util.Deque; 5 | import java.util.Iterator; 6 | 7 | public class DequeueDemo { 8 | public static void main(String[] args) { 9 | Deque deque 10 | = new ArrayDeque(); 11 | 12 | deque.add("Follow"); 13 | deque.add("Code"); 14 | deque.add("Snippet"); 15 | System.out.println(deque); 16 | 17 | deque.addFirst("Hello"); 18 | deque.addLast("Now"); 19 | System.out.println(deque); 20 | 21 | deque.removeFirst(); 22 | System.out.println(deque); 23 | deque.removeLast(); 24 | System.out.println(deque); 25 | 26 | 27 | for (Iterator itr = deque.iterator(); 28 | itr.hasNext();) { 29 | System.out.print(itr.next() + " "); 30 | } 31 | 32 | System.out.println(); 33 | 34 | for (Iterator itr = deque.descendingIterator(); 35 | itr.hasNext();) { 36 | System.out.print(itr.next() + " "); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/ArrayVSArraylist/ArrayListExample.java: -------------------------------------------------------------------------------- 1 | package ArrayVSArraylist; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class ArrayListExample { 6 | public static void main(String[] args) { 7 | // Declare and initialize an ArrayList of integers 8 | ArrayList numbers = new ArrayList<>(); 9 | numbers.add(1); 10 | numbers.add(2); 11 | numbers.add(3); 12 | numbers.add(4); 13 | numbers.add(5); 14 | 15 | // Access elements in the ArrayList 16 | System.out.println("ArrayList elements:"); 17 | for (int i = 0; i < numbers.size(); i++) { 18 | System.out.println(numbers.get(i)); 19 | } 20 | 21 | // Add a new element 22 | numbers.add(6); 23 | System.out.println("After adding an element: " + numbers); 24 | 25 | // Size of the ArrayList can grow dynamically 26 | System.out.println("ArrayList size: " + numbers.size()); 27 | 28 | // Removing an element 29 | numbers.remove(0); // Removes the element at index 0 30 | System.out.println("After removing an element: " + numbers); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/DefaultDemo/DefaultMethodExample.java: -------------------------------------------------------------------------------- 1 | package DefaultDemo; 2 | 3 | import java.util.function.Predicate; 4 | 5 | interface Vehicle { 6 | void start(); 7 | default void honk() { 8 | System.out.println("Beep beep!"); 9 | } 10 | } 11 | 12 | class Car implements Vehicle { 13 | @Override 14 | public void start() { 15 | System.out.println("Car started"); 16 | } 17 | 18 | } 19 | 20 | class Truck implements Vehicle { 21 | @Override 22 | public void start() { 23 | System.out.println("Truck started"); 24 | } 25 | 26 | } 27 | 28 | public class DefaultMethodExample { 29 | public static void main(String[] args) { 30 | Car car = new Car(); 31 | car.start(); 32 | car.honk(); 33 | 34 | 35 | Truck truck = new Truck(); 36 | truck.start(); 37 | 38 | Predicate startsWithA = str -> str.startsWith("A"); 39 | Predicate endsWithB = str -> str.endsWith("B"); 40 | String text = "Apple"; 41 | boolean result = startsWithA.and(endsWithB).test(text); 42 | System.out.println("Result: " + result); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/BalancedBraces/BalancedParentheses.java: -------------------------------------------------------------------------------- 1 | package BalancedBraces; 2 | 3 | import java.util.Stack; 4 | 5 | public class BalancedParentheses { 6 | public static boolean isValid(String s) { 7 | Stack stack = new Stack<>(); 8 | for (char ch : s.toCharArray()) { 9 | if (ch == '(' || ch == '{' || ch == '[') { 10 | stack.push(ch); 11 | } else if (ch == ')' && !stack.isEmpty() && stack.peek() == '(') { 12 | stack.pop(); 13 | } else if (ch == '}' && !stack.isEmpty() && stack.peek() == '{') { 14 | stack.pop(); 15 | } else if (ch == ']' && !stack.isEmpty() && stack.peek() == '[') { 16 | stack.pop(); 17 | } else { 18 | return false; // Invalid closing bracket or empty stack 19 | } 20 | } 21 | return stack.isEmpty(); // Stack should be empty if all brackets are balanced 22 | } 23 | 24 | public static void main(String[] args) { 25 | String s = "()[]{}"; 26 | System.out.println("Is '" + s + "' valid? " + isValid(s)); // Output: true 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/ComparableVsComparator/PersonCompare.java: -------------------------------------------------------------------------------- 1 | package ComparableVsComparator; 2 | 3 | import java.util.*; 4 | 5 | public class PersonCompare { 6 | 7 | public static void main(String[] args) { 8 | List people = new ArrayList<>(); 9 | people.add(new Person("Alice", 30)); 10 | people.add(new Person("Bob", 25)); 11 | people.add(new Person("Charlie", 35)); 12 | 13 | 14 | // Sort by name using Comparator 15 | people.sort(new Comparator() { 16 | @Override 17 | public int compare(Person p1, Person p2) { 18 | return p1.getName().compareTo(p2.getName()); 19 | } 20 | }); 21 | 22 | System.out.println("\nSorted by name:"); 23 | for (Person person : people) { 24 | System.out.println(person); 25 | } 26 | 27 | // Sort by name using Lambda 28 | people.sort(Comparator.comparing(Person::getAge).reversed()); 29 | 30 | System.out.println("\nSorted by name (using lambda):"); 31 | for (Person person : people) { 32 | System.out.println(person); 33 | } 34 | } 35 | } 36 | 37 | -------------------------------------------------------------------------------- /src/solid/s/Book.java: -------------------------------------------------------------------------------- 1 | package solid.s; 2 | 3 | public class Book { 4 | private String name; 5 | private String author; 6 | private String text; 7 | 8 | public Book(String name, String author, String text) { 9 | this.name = name; 10 | this.author = author; 11 | this.text = text; 12 | } 13 | 14 | public String getName() { 15 | return name; 16 | } 17 | 18 | public void setName(String name) { 19 | this.name = name; 20 | } 21 | 22 | public String getAuthor() { 23 | return author; 24 | } 25 | 26 | public void setAuthor(String author) { 27 | this.author = author; 28 | } 29 | 30 | public String getText() { 31 | return text; 32 | } 33 | 34 | public void setText(String text) { 35 | this.text = text; 36 | } 37 | 38 | // methods that directly relate to the book properties 39 | public String replaceWordInText(String word, String replacementWord){ 40 | return text.replaceAll(word, replacementWord); 41 | } 42 | 43 | public boolean isWordInText(String word){ 44 | return text.contains(word); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/Collections/List/LinkedListDemo.java: -------------------------------------------------------------------------------- 1 | package Collections.List; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collection; 5 | import java.util.LinkedList; 6 | 7 | public class LinkedListDemo { 8 | public static void main(String[] args) { 9 | //2 constructors 10 | //1 11 | LinkedList ll = 12 | new LinkedList<>(); 13 | 14 | //2 15 | Collection collection = new ArrayList<>(); 16 | LinkedList llc = 17 | new LinkedList(collection); 18 | 19 | // Adding elements to the linked list 20 | ll.add("A"); 21 | ll.add("B"); 22 | ll.addLast("C"); 23 | ll.addFirst("D"); 24 | ll.add(2, "E"); 25 | 26 | System.out.println(ll); 27 | 28 | ll.remove("B"); 29 | ll.remove(3); 30 | ll.removeFirst(); 31 | ll.removeLast(); 32 | 33 | System.out.println(ll); 34 | 35 | //Dynamic size 36 | //Efficient Insertions and Deletions 37 | //Flexible Iteration 38 | //not synchronized 39 | //duplicate elements 40 | //Maintain Insertion Order 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/FunctionInterfaceDemo/FunctionExample.java: -------------------------------------------------------------------------------- 1 | package FunctionInterfaceDemo; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.function.Function; 6 | 7 | public class FunctionExample { 8 | public static void main(String[] args) { 9 | // Define a function that converts a string to its length 10 | Function stringLengthFunction 11 | = String::length; 12 | 13 | // Apply the function to a string 14 | String input = "Code Snippet"; 15 | int length = stringLengthFunction.apply(input); 16 | 17 | // Print the result 18 | System.out.println 19 | ("Length of '" + input + "': " + length); 20 | 21 | List words = 22 | Arrays.asList("apple", "banana", "cherry"); 23 | 24 | String result = words.stream() 25 | .filter(s -> s.contains("e")) 26 | .map(String::toUpperCase) 27 | .findFirst() 28 | .orElse("No match"); 29 | 30 | System.out.println(result); 31 | 32 | 33 | int x = 5; 34 | System.out.println(x++ * ++x); 35 | 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/ComparableVsComparator/Person.java: -------------------------------------------------------------------------------- 1 | package ComparableVsComparator; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.List; 6 | 7 | public class Person implements Comparable { 8 | private String name; 9 | private int age; 10 | 11 | public Person(String name, int age) { 12 | this.name = name; 13 | this.age = age; 14 | } 15 | 16 | public String getName() { 17 | return name; 18 | } 19 | 20 | public int getAge() { 21 | return age; 22 | } 23 | 24 | 25 | @Override 26 | public String toString() { 27 | return name + " (" + age + ")"; 28 | } 29 | 30 | public static void main(String[] args) { 31 | List people = new ArrayList<>(); 32 | people.add(new Person("Alice", 30)); 33 | people.add(new Person("Bob", 25)); 34 | people.add(new Person("Charlie", 35)); 35 | 36 | Collections.sort(people); 37 | for (Person person : people) { 38 | System.out.println(person); 39 | } 40 | } 41 | 42 | @Override 43 | public int compareTo(Person o) { 44 | return this.name.compareTo(o.name); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/Anagram/AnagramDemo.java: -------------------------------------------------------------------------------- 1 | package Anagram; 2 | 3 | import java.util.Arrays; 4 | 5 | public class AnagramDemo { 6 | 7 | public static void main(String[] args) { 8 | String str1 = "listen"; 9 | String str2 = "silent"; 10 | 11 | boolean areAnagrams = checkAnagram(str1, str2); 12 | 13 | if (areAnagrams) { 14 | System.out.println 15 | (str1 + " and " + str2 + " are anagrams."); 16 | } else { 17 | System.out.println 18 | (str1 + " and " + str2 + " are not anagrams."); 19 | } 20 | } 21 | public static boolean checkAnagram(String str1, String str2) { 22 | if(str1.length() != str2.length()) return false; 23 | // Remove spaces and convert to lowercase for comparison 24 | str1 = str1.replaceAll 25 | ("\\s", "").toLowerCase(); 26 | str2 = str2.replaceAll 27 | ("\\s", "").toLowerCase(); 28 | 29 | // Convert strings to character arrays, sort them, and compare 30 | return Arrays.equals( 31 | str1.chars().sorted().toArray(), 32 | str2.chars().sorted().toArray() 33 | ); 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/Palindrome/StringPalindrome.java: -------------------------------------------------------------------------------- 1 | package Palindrome; 2 | 3 | public class StringPalindrome { 4 | static boolean isPalindrome(String str) 5 | { 6 | 7 | // Pointers pointing to the beginning 8 | // and the end of the string 9 | int i = 0, j = str.length() - 1; 10 | 11 | // While there are characters to compare 12 | while (i < j) { 13 | 14 | // If there is a mismatch 15 | if (str.charAt(i) != str.charAt(j)) 16 | return false; 17 | 18 | // Increment first pointer and 19 | // decrement the other 20 | i++; 21 | j--; 22 | } 23 | 24 | // Given string is a palindrome 25 | return true; 26 | } 27 | 28 | // Method 2 29 | // main driver method 30 | public static void main(String[] args) 31 | { 32 | // Input string 33 | String str = "racecar"; 34 | 35 | // Convert the string to lowercase 36 | str = str.toLowerCase(); 37 | // passing bool function till holding true 38 | if (isPalindrome(str)) 39 | System.out.print("Yes"); 40 | else 41 | System.out.print("No"); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/abstractinterface/PartitioningByExample.java: -------------------------------------------------------------------------------- 1 | package abstractinterface; 2 | 3 | import groupingby.Employee; 4 | 5 | import java.util.Arrays; 6 | import java.util.List; 7 | import java.util.Map; 8 | import java.util.stream.Collectors; 9 | 10 | public class PartitioningByExample { 11 | public static void main(String[] args) { 12 | List employees = Arrays.asList( 13 | new Employee("Alice", "HR", 30000), 14 | new Employee("Bob", "IT", 40000), 15 | new Employee("Charlie", "HR", 35000), 16 | new Employee("Dave", "IT", 65000), 17 | new Employee("Eve", "Finance", 80000) 18 | ); 19 | 20 | // Partition numbers into even and odd 21 | Map> partitionedBySalary = 22 | employees.stream() 23 | .collect(Collectors.partitioningBy(employee -> employee.getSalary()>50000)); 24 | 25 | System.out.println("Employees with salary > 50000:"); 26 | partitionedBySalary.get(true).forEach(System.out::println); 27 | 28 | System.out.println("\nEmployees with salary <= 50000:"); 29 | partitionedBySalary.get(false).forEach(System.out::println); 30 | } 31 | } 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /src/HashMapVsConCurrentHashMap/HashMapExample.java: -------------------------------------------------------------------------------- 1 | package HashMapVsConCurrentHashMap; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | import java.util.concurrent.ConcurrentHashMap; 6 | import java.util.concurrent.ExecutorService; 7 | import java.util.concurrent.Executors; 8 | 9 | public class HashMapExample { 10 | public static void main(String[] args) { 11 | Map map = new ConcurrentHashMap<>(); 12 | ExecutorService executorService 13 | = Executors.newFixedThreadPool(10); 14 | 15 | // Task to put values in the map 16 | Runnable task = () -> { 17 | for (int i = 0; i < 1000; i++) { 18 | map.put(i, "Value" + i); 19 | } 20 | }; 21 | 22 | // Submit multiple tasks to the executor service 23 | for (int i = 0; i < 10; i++) { 24 | executorService.submit(task); 25 | } 26 | 27 | // Shutdown the executor service 28 | executorService.shutdown(); 29 | 30 | // Wait for all tasks to finish 31 | while (!executorService.isTerminated()) { 32 | } 33 | 34 | // Print the size of the map 35 | System.out.println("HashMap Size: " + map.size()); 36 | } 37 | } 38 | 39 | -------------------------------------------------------------------------------- /src/Thread/EvenOddRunnable.java: -------------------------------------------------------------------------------- 1 | package Thread; 2 | 3 | public class EvenOddRunnable implements Runnable{ 4 | int MAX; 5 | static int counter = 1; 6 | int rem; 7 | static Object lock = new Object(); 8 | // parameterized constructor 9 | EvenOddRunnable(int rem, int MAX) 10 | { 11 | this.rem = rem; 12 | this.MAX = MAX; 13 | } 14 | // override run() method 15 | @Override 16 | public void run() { 17 | // use while loop to recursively execute steps until counter < MAX 18 | while (counter < MAX) { 19 | // synchronized block 20 | synchronized (lock) { 21 | while (counter % 2 != rem) { // wait for numbers other than remainder 22 | // use try-catch block to put lock in waiting state 23 | try { 24 | lock.wait(); 25 | } catch (InterruptedException e) { 26 | e.printStackTrace(); 27 | } 28 | } 29 | System.out.println(Thread.currentThread().getName() + " " + counter); 30 | //increment counter 31 | counter++; 32 | lock.notifyAll(); 33 | } 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /src/FascinaingNumber/FascinatingNumber.java: -------------------------------------------------------------------------------- 1 | package FascinaingNumber; 2 | 3 | public class FascinatingNumber { 4 | public static void main(String[] args) { 5 | int num =327, n2, n3; 6 | 7 | n2 = num * 2; 8 | n3 = num * 3; 9 | //concatenating num, n2, and n3 10 | String concatStr = num + "" + n2 + n3; 11 | boolean found = true; 12 | //checks all digits from 1 to 9 are present or not 13 | for(char c = '1'; c <= '9'; c++) 14 | { 15 | int count = 0; 16 | //loop counts the frequency of each digit 17 | for(int i = 0; i < concatStr.length(); i++) 18 | { 19 | char ch = concatStr.charAt(i); 20 | //compares the character of concatStr with i 21 | if(ch == c) 22 | //incerments the count by 1 if the specified condition returns true 23 | count++; 24 | } 25 | //returns true if any of the condition returns true 26 | if(count > 1 || count == 0) 27 | { 28 | found = false; 29 | break; 30 | } 31 | } 32 | if(found) 33 | System.out.println(num + " is a fascinating number."); 34 | else 35 | System.out.println(num + " is not a fascinating number."); 36 | } 37 | } 38 | 39 | -------------------------------------------------------------------------------- /src/parallelAndSequentialStreams/ParallelAndSequentialStreams.java: -------------------------------------------------------------------------------- 1 | package parallelAndSequentialStreams; 2 | 3 | 4 | import java.util.Arrays; 5 | 6 | 7 | public class ParallelAndSequentialStreams { 8 | public static void main(String[] args) { 9 | int[] intArray = new int[1000000]; 10 | Arrays.fill(intArray, 2); 11 | 12 | // Calculate sum of squares using sequential stream 13 | long startTime = System.currentTimeMillis(); 14 | final int sequentialSum = Arrays.stream(intArray) 15 | .map(n -> n * n) 16 | .sum(); 17 | long endTime = System.currentTimeMillis(); 18 | System.out.println("Sequential sum: " 19 | + sequentialSum); 20 | System.out.println("Time Taken by Sequential Stream: " 21 | + (endTime - startTime) + " ms"); 22 | 23 | // Calculate sum of squares using parallel stream 24 | startTime = System.currentTimeMillis(); 25 | final int parallelSum = Arrays.stream(intArray) 26 | .parallel() 27 | .map(n -> n * n) 28 | .sum(); 29 | endTime = System.currentTimeMillis(); 30 | System.out.println("Parallel sum: " + parallelSum); 31 | System.out.println("Time Taken by Parallel Stream: " 32 | + (endTime - startTime) + " ms"); 33 | } 34 | } 35 | 36 | -------------------------------------------------------------------------------- /src/MapAndFlatMap/MapAndFlatMap.java: -------------------------------------------------------------------------------- 1 | package MapAndFlatMap; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.stream.Collectors; 6 | 7 | public class MapAndFlatMap { 8 | public static void main(String[] args) { 9 | 10 | //MAP EXAMPLE 11 | List list = Arrays.asList("apple", "mango","orange"); 12 | final List upperCaseList = list.stream() 13 | .map(String::toUpperCase) 14 | .collect(Collectors.toList()); 15 | System.out.println("MAP OUTPUT: "+upperCaseList); 16 | //MAP OUTPUT: [APPLE, MANGO, ORANGE] 17 | 18 | //FLATMAP EXAMPLE 19 | List> nestedList = Arrays.asList( 20 | Arrays.asList("apple","mango"), 21 | Arrays.asList("orange","pineapple"), 22 | Arrays.asList("grapes","kiwi") 23 | ); 24 | System.out.println("NESTED LIST OUTPUT: "+nestedList); 25 | // NESTED LIST OUTPUT: [[apple, mango], [orange, pineapple], [grapes, kiwi]] 26 | 27 | final List flattenedUpperCaseList = nestedList.stream() 28 | .flatMap(List::stream) 29 | .map(String::toUpperCase) 30 | .collect(Collectors.toList()); 31 | System.out.println("FLATMAP OUTPUT: "+flattenedUpperCaseList); 32 | // FLATMAP OUTPUT: [APPLE, MANGO, ORANGE, PINEAPPLE, GRAPES, KIWI] 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/StreamProblems/PersonSortingExample.java: -------------------------------------------------------------------------------- 1 | package StreamProblems; 2 | 3 | import java.util.Arrays; 4 | import java.util.Comparator; 5 | import java.util.List; 6 | import java.util.stream.Collectors; 7 | 8 | public class PersonSortingExample { 9 | public static void main(String[] args) { 10 | List people = Arrays.asList( 11 | new Person("John", 25), 12 | new Person("Anna", 22), 13 | new Person("Mike", 29), 14 | new Person("Sophia", 24) 15 | ); 16 | 17 | // Sorting by age in descending order 18 | List sortedByAgeDesc = people.stream() 19 | .sorted(Comparator.comparing(Person::getName).reversed()) 20 | .collect(Collectors.toList()); 21 | 22 | System.out.println 23 | ("Sorted by age in descending order:"); 24 | sortedByAgeDesc.forEach(System.out::println); 25 | } 26 | } 27 | 28 | class Person { 29 | private String name; 30 | private int age; 31 | 32 | public Person(String name, int age) { 33 | this.name = name; 34 | this.age = age; 35 | } 36 | 37 | public String getName() { 38 | return name; 39 | } 40 | 41 | public int getAge() { 42 | return age; 43 | } 44 | 45 | @Override 46 | public String toString() { 47 | return "Person{name='" + name + "', age=" + age + "}"; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/PangramString/PangramString.java: -------------------------------------------------------------------------------- 1 | package PangramString; 2 | 3 | public class PangramString { 4 | 5 | // Function to check if a string 6 | // contains all the letters from 7 | // a to z (ignoring case) 8 | public static void 9 | allLetter(String str) 10 | { 11 | // Converting the given string 12 | // into lowercase 13 | str = str.toLowerCase(); 14 | 15 | boolean allLetterPresent = true; 16 | 17 | // Loop over each character itself 18 | for (char ch = 'a'; ch <= 'z'; ch++) { 19 | 20 | // Check if the string does not 21 | // contains all the letters 22 | if (!str.contains(String.valueOf(ch))) { 23 | allLetterPresent = false; 24 | break; 25 | } 26 | } 27 | 28 | // Check if all letter present then 29 | // print "Yes", else print "No" 30 | if (allLetterPresent) 31 | System.out.println("Yes"); 32 | else 33 | System.out.println("No"); 34 | } 35 | 36 | // Driver Code 37 | public static void main(String args[]) 38 | { 39 | // Given string str 40 | String str = "Abcdefghijklmnopqrstuvwz12"; 41 | 42 | // Function call 43 | allLetter(str); 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /src/completableFuture/WeatherApplication.java: -------------------------------------------------------------------------------- 1 | package completableFuture; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | 5 | public class WeatherApplication { 6 | public static void main(String[] args) { 7 | // Task 1: Fetch Weather Data from API 1N 8 | CompletableFuture fetchWeatherDataAPI1 = CompletableFuture.supplyAsync(() -> { 9 | // Simulate fetching weather data from API 1 10 | return "Weather data from API 1"; 11 | }); 12 | 13 | // Task 2: Fetch Weather Data from API 2 14 | CompletableFuture fetchWeatherDataAPI2 = CompletableFuture.supplyAsync(() -> { 15 | // Simulate fetching weather data from API 2 16 | return "Weather data from API 2"; 17 | }); 18 | 19 | // Task 3: Combine Results 20 | CompletableFuture combineResults = fetchWeatherDataAPI1.thenCombine(fetchWeatherDataAPI2, 21 | (dataFromAPI1, dataFromAPI2) -> { 22 | // Combine results to create a comprehensive weather report 23 | return "Comprehensive Weather Report:\n" + dataFromAPI1 + "\n" + dataFromAPI2; 24 | }); 25 | 26 | // Display the combined weather report 27 | combineResults.thenAccept(System.out::println); 28 | 29 | // Wait for all tasks to complete 30 | CompletableFuture.allOf(fetchWeatherDataAPI1, fetchWeatherDataAPI2, combineResults).join(); 31 | 32 | System.out.println("Weather data processing completed"); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/StreamProblems/TransactionsProblem.java: -------------------------------------------------------------------------------- 1 | package StreamProblems; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.Map; 6 | import java.util.stream.Collectors; 7 | 8 | public class TransactionsProblem { 9 | public static void main(String[] args) { 10 | List transactions = Arrays.asList( 11 | new Transaction("P1", "Electronics", 1000), 12 | new Transaction("P2", "Books", 500), 13 | new Transaction("P3", "Electronics", 800), 14 | new Transaction("P4", "Clothing", 1200), 15 | new Transaction("P5", "Books", 600) 16 | ); 17 | 18 | Map totalSalesByCategory = transactions.stream() 19 | .collect(Collectors.groupingBy(Transaction::getCategory, 20 | Collectors.summingInt(Transaction::getAmount))); 21 | 22 | System.out.println("Total sales by category: " + totalSalesByCategory); 23 | } 24 | 25 | static class Transaction { 26 | private String productId; 27 | private String category; 28 | private int amount; 29 | 30 | public Transaction(String productId, String category, int amount) { 31 | this.productId = productId; 32 | this.category = category; 33 | this.amount = amount; 34 | } 35 | 36 | public String getCategory() { 37 | return category; 38 | } 39 | 40 | public int getAmount() { 41 | return amount; 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/JVM/Test.java: -------------------------------------------------------------------------------- 1 | package JVM; 2 | 3 | // A Java program to demonstrate working 4 | // of a Class type object created by JVM 5 | // to represent .class file in memory. 6 | import java.lang.reflect.Field; 7 | import java.lang.reflect.Method; 8 | 9 | // Java code to demonstrate use 10 | // of Class object created by JVM 11 | public class Test { 12 | public static void main(String[] args) 13 | { 14 | Student s1 = new Student(); 15 | 16 | // Getting hold of Class 17 | // object created by JVM. 18 | Class c1 = s1.getClass(); 19 | 20 | // Printing type of object using c1. 21 | System.out.println(c1.getName()); 22 | 23 | // getting all methods in an array 24 | Method m[] = c1.getDeclaredMethods(); 25 | for (Method method : m) 26 | System.out.println(method.getName()); 27 | 28 | // getting all fields in an array 29 | Field f[] = c1.getDeclaredFields(); 30 | for (Field field : f) 31 | System.out.println(field.getName()); 32 | 33 | //System.out.println(Test.class.getClassLoader()); 34 | } 35 | } 36 | 37 | // A sample class whose information 38 | // is fetched above using its Class object. 39 | class Student { 40 | private String name; 41 | private int roll_No; 42 | 43 | public String getName() { return name; } 44 | public void setName(String name) { this.name = name; } 45 | public int getRoll_no() { return roll_No; } 46 | public void setRoll_no(int roll_no) 47 | { 48 | this.roll_No = roll_no; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/ShallowVsDeepCopy/Person.java: -------------------------------------------------------------------------------- 1 | package ShallowVsDeepCopy; 2 | 3 | 4 | class Address implements Cloneable { 5 | String city; 6 | String country; 7 | 8 | Address(String city, String country) { 9 | this.city = city; 10 | this.country = country; 11 | } 12 | 13 | // Deep copy 14 | protected Object clone() throws CloneNotSupportedException { 15 | return new Address(this.city, this.country); 16 | } 17 | } 18 | 19 | class Person implements Cloneable { 20 | String name; 21 | Address address; 22 | 23 | Person(String name, Address address) { 24 | this.name = name; 25 | this.address = address; 26 | } 27 | 28 | // Deep copy 29 | protected Object clone() throws CloneNotSupportedException { 30 | Person cloned = (Person) super.clone(); 31 | cloned.address = (Address) this.address.clone(); 32 | return cloned; 33 | } 34 | public static void main(String[] args) throws CloneNotSupportedException { 35 | Address address = new Address("Pune", "India"); 36 | Person person1 = new Person("John", address); 37 | Person person2 = (Person) person1.clone(); 38 | System.out.println(person1.name); 39 | System.out.println(person2.name); 40 | System.out.println(person1.address.city); 41 | System.out.println(person2.address.city); 42 | System.out.println("-------------------------------------"); 43 | // Change the address of person2 44 | person2.name = "Paul"; 45 | person2.address.city = "Mumbai"; 46 | 47 | System.out.println(person1.name); 48 | System.out.println(person2.name); 49 | System.out.println(person1.address.city); 50 | System.out.println(person2.address.city); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/ReverseString/ReverseString.java: -------------------------------------------------------------------------------- 1 | package ReverseString; 2 | 3 | public class ReverseString { 4 | public static void main(String[] args) { 5 | String str= "codeSnippet"; 6 | reverseUsingLoop(str); 7 | reverseUsingStringBuilder(str); 8 | reverseUsingTwoPointers(str); 9 | } 10 | private static void reverseUsingLoop(String str) { 11 | String nstr =""; 12 | for (int i = 0; i< str.length(); i++) 13 | { 14 | nstr= str.charAt(i)+nstr; //adds each character in front of the existing string 15 | } 16 | System.out.println("reverseUsingLoop: " 17 | + nstr); 18 | } 19 | private static void reverseUsingStringBuilder(String str) { 20 | StringBuilder stringBuilder = new StringBuilder(); 21 | 22 | // append a string into StringBuilder stringBuilder 23 | stringBuilder.append(str); 24 | 25 | // reverse StringBuilder stringBuilder 26 | stringBuilder.reverse(); 27 | 28 | // print reversed String 29 | System.out.println("reverseUsingStringBuilder : " 30 | +stringBuilder); 31 | } 32 | private static void reverseUsingTwoPointers(String str) { 33 | char[] temArray = str.toCharArray(); 34 | int left, right = 0; 35 | right = temArray.length - 1; 36 | 37 | for (left = 0; left < right; left++, right--) { 38 | // Swap values of left and right 39 | char temp = temArray[left]; 40 | temArray[left] = temArray[right]; 41 | temArray[right] = temp; 42 | } 43 | System.out.print("reverseUsingTwoPointers :"); 44 | for (char c : temArray) 45 | System.out.print(c); 46 | System.out.println(); 47 | } 48 | 49 | 50 | 51 | 52 | 53 | 54 | } 55 | 56 | 57 | -------------------------------------------------------------------------------- /src/ThreadPoolExecutorExample/ThreadPoolExecutorExample.java: -------------------------------------------------------------------------------- 1 | package ThreadPoolExecutorExample; 2 | 3 | import java.sql.Time; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | import java.util.concurrent.*; 7 | 8 | public class ThreadPoolExecutorExample { 9 | 10 | public static void main(String[] args) { 11 | parallel(); 12 | ThreadPoolExecutor executor = new ThreadPoolExecutor( 13 | 1, 14 | 10, 15 | 0L, 16 | TimeUnit.MILLISECONDS, 17 | new LinkedBlockingDeque<>(2)); 18 | 19 | // Submit tasks to the ThreadPoolExecutor 20 | for (int i = 1; i <= 5; i++) { 21 | final int taskId = i; 22 | executor.submit(() -> { 23 | try { 24 | Thread.sleep(1000); // Simulate task execution time 25 | System.out.println 26 | ("Task " + taskId + " completed by " 27 | + Thread.currentThread().getName()); 28 | } catch (InterruptedException e) { 29 | e.printStackTrace(); 30 | } 31 | }); 32 | } 33 | 34 | // Shut down the ThreadPoolExecutor 35 | executor.shutdown(); 36 | } 37 | private static void parallel(){ 38 | List intList =Arrays.asList(1,2,3,4); 39 | long t1 = System.currentTimeMillis(); 40 | intList.stream().parallel().forEach(n->{ 41 | try { 42 | Thread.sleep(2000); 43 | System.out.println(n); 44 | } catch (InterruptedException e) { 45 | throw new RuntimeException(e); 46 | } 47 | }); 48 | long t2 = System.currentTimeMillis(); 49 | System.out.println("t2-t1"+(t2-t1)); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/parallelAndSequentialStreams/FactorialParallelAndSequentialStreams.java: -------------------------------------------------------------------------------- 1 | package parallelAndSequentialStreams; 2 | 3 | import java.util.Arrays; 4 | 5 | import java.util.stream.LongStream; 6 | 7 | public class FactorialParallelAndSequentialStreams { 8 | public static void main(String[] args) { 9 | long[] longArray = new long[20000]; 10 | for (int i = 0; i < longArray.length; i++) { 11 | longArray[i] = i + 1; 12 | } 13 | 14 | // Calculate sum of factorials using sequential stream 15 | long startTime = System.currentTimeMillis(); 16 | long sequentialSum = Arrays.stream(longArray) 17 | .map(FactorialParallelAndSequentialStreams::factorial) 18 | .sum(); 19 | long endTime = System.currentTimeMillis(); 20 | System.out.println("Sequential sum of factorials: " + 21 | "" + sequentialSum); 22 | System.out.println("Time Taken by Sequential Stream: " 23 | + (endTime - startTime) + " ms"); 24 | 25 | 26 | // Calculate sum of factorials using parallel stream 27 | startTime = System.currentTimeMillis(); 28 | long parallelSum = Arrays.stream(longArray) 29 | .parallel() 30 | .map(FactorialParallelAndSequentialStreams::factorial) 31 | .sum(); 32 | endTime = System.currentTimeMillis(); 33 | System.out.println("Parallel sum of factorials: " 34 | + parallelSum); 35 | System.out.println("Time Taken by Parallel Stream: " 36 | + (endTime - startTime) + " ms"); 37 | } 38 | 39 | // Method to calculate factorial of a number 40 | public static long factorial(long number) { 41 | return LongStream.rangeClosed(1, number) 42 | .reduce(1, (long a, long b) -> a * b); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/SerializationInJava/SerializationExample.java: -------------------------------------------------------------------------------- 1 | package SerializationInJava; 2 | 3 | import java.io.*; 4 | 5 | // Define a serializable class 6 | class Person implements Serializable { 7 | private static final long serialVersionUID = 1L; 8 | private String name; 9 | private int age; 10 | transient private String email; 11 | 12 | public Person(String name, int age, String email) { 13 | this.name = name; 14 | this.age = age; 15 | this.email = email; 16 | } 17 | 18 | @Override 19 | public String toString() { 20 | return "Person{" + 21 | "name='" + name + '\'' + 22 | ", age=" + age + 23 | ", email='" + email + '\'' + 24 | '}'; 25 | } 26 | } 27 | 28 | public class SerializationExample { 29 | 30 | public static void main(String[] args) { 31 | // Serialize object 32 | Person person = 33 | new Person("John", 30, "john@example.com"); 34 | try (FileOutputStream fos = new FileOutputStream("person.txt"); 35 | ObjectOutputStream oos = new ObjectOutputStream(fos)) { 36 | oos.writeObject(person); 37 | System.out.println("Serialization successful"); 38 | } catch (IOException e) { 39 | e.printStackTrace(); 40 | } 41 | 42 | // Deserialize object 43 | try (FileInputStream fis = new FileInputStream("person.txt"); 44 | ObjectInputStream ois = new ObjectInputStream(fis)) { 45 | Person deserializedPerson = (Person) ois.readObject(); 46 | System.out.println("Deserialization successful"); 47 | System.out.println("Deserialized Person: " + deserializedPerson); 48 | } catch (IOException | ClassNotFoundException e) { 49 | e.printStackTrace(); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/RotateArrays.java: -------------------------------------------------------------------------------- 1 | public class RotateArrays { 2 | static void rotateUsingTemp(int arr[], int d, int n) 3 | { 4 | // Storing rotated version of array 5 | int temp[] = new int[n]; 6 | 7 | // Keeping track of the current index 8 | // of temp[] 9 | int k = 0; 10 | 11 | // Storing the n - d elements of 12 | // array arr[] to the front of temp[] 13 | //1, 2, [3, 4, 5, 6, 7] 14 | for (int i = d; i < n; i++) { 15 | temp[k] = arr[i]; 16 | k++; 17 | } 18 | 19 | // Storing the first d elements of array arr[] 20 | // into temp 21 | // 3, 4, 5, 6, 7, [1, 2] 22 | for (int i = 0; i < d; i++) { 23 | temp[k] = arr[i]; 24 | k++; 25 | } 26 | 27 | 28 | for (int i = 0; i < n; i++) { 29 | System.out.print(temp[i] + " "); 30 | } 31 | } 32 | public static void rotateOneByOne(int arr[], int d, int n) 33 | { 34 | int p = 1; 35 | while (p <= d) { 36 | int last = arr[0]; 37 | for (int i = 0; i < n - 1; i++) { 38 | arr[i] = arr[i + 1]; 39 | } 40 | arr[n - 1] = last; 41 | p++; 42 | } 43 | // 1, 2, 3, 4, 5, 6, 7 44 | // last = 1 45 | //2, 3, 4, 5, 6, 7, 1 46 | //last = 2 47 | //3, 4, 5, 6, 7, 1, 2 48 | for (int i = 0; i < n; i++) { 49 | System.out.print(arr[i] + " "); 50 | } 51 | } 52 | 53 | public static void main(String[] args) { 54 | int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; 55 | int N = arr.length; 56 | // Rotate 2 times 57 | int d = 2; 58 | // 3, 4, 5, 6, 7, 1, 2 59 | // Function call 60 | //rotateUsingTemp(arr, d, N); 61 | rotateOneByOne(arr, d, N); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/ListComparison.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.LinkedList; 3 | import java.util.List; 4 | 5 | public class ListComparison { 6 | public static void main(String[] args) { 7 | // Initialize ArrayList and LinkedList 8 | List arrayList = new ArrayList<>(); 9 | List linkedList = new LinkedList<>(); 10 | 11 | // Add elements to both lists 12 | for (int i = 0; i < 10000; i++) { 13 | arrayList.add(i); 14 | linkedList.add(i); 15 | } 16 | 17 | // Measure access time\] 18 | long startTime = System.nanoTime(); 19 | arrayList.get(5000); 20 | long endTime = System.nanoTime(); 21 | System.out.println( 22 | "ArrayList access time: " + 23 | (endTime - startTime) + " ns"); 24 | 25 | startTime = System.nanoTime(); 26 | linkedList.get(5000); 27 | endTime = System.nanoTime(); 28 | System.out.println( 29 | "LinkedList access time: " + 30 | (endTime - startTime) + " ns"); 31 | 32 | // Measure insertion time 33 | startTime = System.nanoTime(); 34 | arrayList.add(5000, 99999); 35 | endTime = System.nanoTime(); 36 | System.out.println( 37 | "ArrayList insertion time: " 38 | + (endTime - startTime) + " ns"); 39 | 40 | startTime = System.nanoTime(); 41 | linkedList.add(5000, 99999); 42 | endTime = System.nanoTime(); 43 | System.out.println( 44 | "LinkedList insertion time: " 45 | + (endTime - startTime) + " ns"); 46 | 47 | // Measure deletion time 48 | startTime = System.nanoTime(); 49 | arrayList.remove(5000); 50 | endTime = System.nanoTime(); 51 | System.out.println("" + 52 | "ArrayList deletion time: " 53 | + (endTime - startTime) + " ns"); 54 | 55 | startTime = System.nanoTime(); 56 | linkedList.remove(5000); 57 | endTime = System.nanoTime(); 58 | System.out.println( 59 | "LinkedList deletion time: " 60 | + (endTime - startTime) + " ns"); 61 | } 62 | } 63 | 64 | -------------------------------------------------------------------------------- /src/InstanceOfDemo/MessageProcessor.java: -------------------------------------------------------------------------------- 1 | package InstanceOfDemo; 2 | 3 | class Message {} 4 | 5 | class TextMessage extends Message { 6 | private final String text; 7 | 8 | public TextMessage(String text) { 9 | this.text = text; 10 | } 11 | 12 | public String getText() { 13 | return text; 14 | } 15 | } 16 | 17 | class ImageMessage extends Message { 18 | private final String imageUrl; 19 | 20 | public ImageMessage(String imageUrl) { 21 | this.imageUrl = imageUrl; 22 | } 23 | 24 | public String getImageUrl() { 25 | return imageUrl; 26 | } 27 | } 28 | 29 | class VideoMessage extends Message { 30 | private final String videoUrl; 31 | 32 | public VideoMessage(String videoUrl) { 33 | this.videoUrl = videoUrl; 34 | } 35 | 36 | public String getVideoUrl() { 37 | return videoUrl; 38 | } 39 | } 40 | 41 | public class MessageProcessor { 42 | 43 | public static void main(String[] args) { 44 | Message textMessage = 45 | new TextMessage("Hello, world!"); 46 | Message imageMessage = 47 | new ImageMessage 48 | ("https://example.com/image.jpg"); 49 | Message videoMessage = 50 | new VideoMessage 51 | ("https://example.com/video.mp4"); 52 | 53 | processMessage1(textMessage); 54 | processMessage1(imageMessage); 55 | processMessage1(videoMessage); 56 | } 57 | static void processMessage(Message message) { 58 | if (message instanceof TextMessage) { 59 | TextMessage textMessage = (TextMessage) message; 60 | // Process text message 61 | System.out.println 62 | ("Processing text message: " 63 | + textMessage.getText()); 64 | 65 | } else if (message instanceof ImageMessage) { 66 | ImageMessage imageMessage = (ImageMessage) message; 67 | // Process image message 68 | System.out.println 69 | ("Processing image message: " 70 | + imageMessage.getImageUrl()); 71 | 72 | } else if (message instanceof VideoMessage) { 73 | VideoMessage videoMessage = (VideoMessage) message; 74 | // Process video message 75 | System.out.println 76 | ("Processing video message: " 77 | + videoMessage.getVideoUrl()); 78 | 79 | } else { 80 | // Unknown message type 81 | System.out.println("Unknown message type"); 82 | 83 | } 84 | } 85 | 86 | static void processMessage1(Message message) { 87 | if (message instanceof TextMessage textMessage) { 88 | System.out.println( 89 | "Processing text message: " 90 | + textMessage.getText()); 91 | } else if (message instanceof ImageMessage imageMessage) { 92 | System.out.println 93 | ("Processing image message: " + 94 | imageMessage.getImageUrl()); 95 | } else if (message instanceof VideoMessage videoMessage) { 96 | System.out.println 97 | ("Processing video message: " + 98 | videoMessage.getVideoUrl()); 99 | } else { 100 | System.out.println("Unknown message type"); 101 | } 102 | } 103 | } 104 | --------------------------------------------------------------------------------