{"id":28522072,"url":"https://github.com/swathireddy369/java-core-concepts","last_synced_at":"2026-06-28T02:32:39.216Z","repository":{"id":290396598,"uuid":"974317579","full_name":"swathireddy369/java-core-concepts","owner":"swathireddy369","description":"A collection of Java examples and exercises covering core topics like OOP, data structures, algorithms, exception handling, concurrency, and design patterns. Perfect for developers looking to strengthen their understanding of Java fundamentals and build efficient applications.","archived":false,"fork":false,"pushed_at":"2025-09-10T23:34:43.000Z","size":19851,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-09-11T02:59:56.741Z","etag":null,"topics":["abstraction","aggregation","class","composition","encapsulation","has-a-relationship","inheritance","is-a-relationship","many-to-many","multipleinheritance","mutilevelinheritance","object","one-to-many","one-to-one","overloading","overriding","polymorphism","singleinheritance"],"latest_commit_sha":null,"homepage":"","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/swathireddy369.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-04-28T15:33:31.000Z","updated_at":"2025-09-10T23:34:47.000Z","dependencies_parsed_at":null,"dependency_job_id":"e3918467-cb2d-468d-ae5f-e7be71c243b4","html_url":"https://github.com/swathireddy369/java-core-concepts","commit_stats":null,"previous_names":["swathireddy369/java-core-concepts"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/swathireddy369/java-core-concepts","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/swathireddy369%2Fjava-core-concepts","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/swathireddy369%2Fjava-core-concepts/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/swathireddy369%2Fjava-core-concepts/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/swathireddy369%2Fjava-core-concepts/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/swathireddy369","download_url":"https://codeload.github.com/swathireddy369/java-core-concepts/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/swathireddy369%2Fjava-core-concepts/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34875357,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-28T02:00:05.809Z","response_time":54,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["abstraction","aggregation","class","composition","encapsulation","has-a-relationship","inheritance","is-a-relationship","many-to-many","multipleinheritance","mutilevelinheritance","object","one-to-many","one-to-one","overloading","overriding","polymorphism","singleinheritance"],"created_at":"2025-06-09T08:42:52.766Z","updated_at":"2026-06-28T02:32:39.208Z","avatar_url":"https://github.com/swathireddy369.png","language":"Java","funding_links":[],"categories":[],"sub_categories":[],"readme":"# java-core-concepts\nA collection of Java examples and exercises covering core topics like OOP, data structures, algorithms, exception handling, concurrency, and design patterns. Perfect for developers looking to strengthen their understanding of Java fundamentals and build efficient applications.\n\n\nThis repository contains a collection of Java programming examples and exercises that cover fundamental and advanced concepts in the Java language. It is designed to help developers at all skill levels deepen their understanding of Java’s core features, including object-oriented programming, data structures, algorithms, exception handling, concurrency, and more.\n\nTopics Covered:\n\nBasic Syntax \u0026 Operators\n\nObject-Oriented Programming (OOP): Classes, Inheritance, Polymorphism, Abstraction, Encapsulation\n\nCollections Framework: Lists, Sets, Maps, Queues\n\nConcurrency \u0026 Multithreading\n\nException Handling\n\nJava Streams API\n\nDesign Patterns: Singleton, Factory, Observer, etc.\n\nData Structures \u0026 Algorithms in Java\n\nThis repository is continuously updated with new examples and challenges to reinforce core Java principles. It serves as a reference for both beginner and intermediate Java developers looking to solidify their skills and build robust applications.\n\nDay-1:\n=============================\n\n/🔁 OOP Concepts - Quick Revision\n⚙️ Class \u0026 Object\nClass: Blueprint/template for creating objects\n\nObject: Instance of a class\n\n📌 1st Pillar: Abstraction\nHiding internal details and showing only essential features\n\nExample: You drive a car without knowing the internal engine mechanism\n\n📌 2nd Pillar: Encapsulation\nBinding data and methods into a single unit (class)\n\nAchieved using access modifiers (private, public, etc.)\n\nProtects data from outside interference\n\n📌 3rd Pillar: Inheritance\nMechanism where a child class inherits properties and behaviors from a parent class\n\nPromotes code reusability\n\n🔸 Types of Inheritance\ncsharp\nCopy\nEdit\n           [Vehicle]\n               ↑\n             Single\n         [Car extends Vehicle]\n\n           [Vehicle]\n               ↑\n         [Car extends Vehicle]\n               ↑\n         Multilevel\n         [SportsCar extends Car]\n\n⚠️ Multiple inheritance with classes is not supported in Java.\nInstead, use interfaces to achieve it.\n📌 4th Pillar: Polymorphism\nCompile-time (Method Overloading)\n\nRuntime (Method Overriding)\n\nAllows one action to behave differently based on the object\n\n🔗 Relationships in OOP\n✅ IS-A Relationship (Inheritance)\nAchieved through inheritance\n\nExample:\n\nkotlin\n\nclass Animal {}\nclass Dog extends Animal {}\n\nDog IS-A Animal ✅\n✅ HAS-A Relationship (Association)\nOne class uses or contains another class's object\n\n🔸 One-to-One\nOne student has one course\n\n🔸 One-to-Many\nOne student has many courses\n\n🔸 Many-to-Many\nMany students take many courses\n\n🔍 Ways to Achieve HAS-A Relationship\n1. 🧩 Aggregation (Weak Association)\nUses object reference from one class to another\n\nBoth objects can exist independently\n\n\nclass Student {}\nclass School {\n    List\u003cStudent\u003e students;  // Aggregation\n}\nExample:\n\nRemoving students does not destroy the school\n\nSchool can still exist empty and enroll new students\n\n2. 🧱 Composition (Strong Association)\nObject of one class is created inside another class\n\nIf one is destroyed, the other is affected\n\nclass Classroom {}\nclass School {\n    Classroom room = new Classroom();  // Composition\n}\nExample:\n\nIf we remove all rooms, the school can't function\n\nRemoving the school also removes its rooms\n\n📊 Summary Table\n\n\nAbstraction\tHides internal details\tCar \ninterface (not engine)\nEncapsulation\tBinds data + methods\tPrivate fields with getters/setters\nInheritance\tChild inherits from Parent\tclass Car extends Vehicle\nPolymorphism\tOne interface, many forms\trun() method in multiple classes\nIS-A\tInheritance\tCar IS-A Vehicle\nHAS-A\tClass uses another class\tSchool HAS-A Student\nAggregation\tWeak HAS-A (independent)\tSchool–Student\nComposition\tStrong HAS-A (dependent)\tSchool–Room\n\n\nDay-2:\n\n===========================\n📌 What is Java?\nJava is a platform-independent, object-oriented programming language.\n\nIt supports WORA (Write Once, Run Anywhere).\n\n📦 Java Compilation \u0026 Execution Flow:\nWrite Java Program\n→ Save with .java extension.\n\nCompile using Java Compiler (javac) from JDK\n→ Converts source code into bytecode (.class file).\n\nRun using JVM (Java Virtual Machine)\n\nJVM interprets bytecode and converts it to machine code.\n\nIf the bytecode uses any libraries, JRE is needed to provide class libraries.\n\n🧩 Components:\nJDK (Java Development Kit):\n\nContains compiler, debugger, and programming tools.\n\nIncludes JRE + development tools.\n\nJRE (Java Runtime Environment):\n\nContains JVM and class libraries.\n\nCannot be used to write Java programs (only run them).\n\nJVM (Java Virtual Machine):\n\nConverts bytecode to machine code.\n\nIncludes JIT (Just-In-Time) Compiler for performance.\n\n💡 Summary:\nYou need JDK to write and run Java programs.\n\nJDK = JRE + JVM + Development Tools\n\nJRE = JVM + Class Libraries\n\n🧵 Java Editions:\nJSE (Java Standard Edition): Core Java – classes, objects, OOP concepts.\n\nJEE (Java Enterprise Edition / Jakarta Edition):\nAPIs for enterprise apps – transactions, rollback, commit, servlets, JSP, eCommerce.\n\nJME (Java Micro Edition): APIs for mobile apps.\n\n⚙️ Java File Rules:\nFile name must be the same as the public class name.\n\nA file can only have one public class.\n\nThe class must contain the main method to run.\n\n🔁 public static void main(String[] args)\npublic: JVM can access it from outside.\n\nstatic: JVM doesn’t need to create an object to call it.\n\nvoid: It does not return anything.\n\nString[] args: JVM can pass arguments to the program.\n\n📝 Comments in Java:\nSingle-line comment: // this is comment\n\nMulti-line comment:\n\n\n/* this is also a  \n   comment multiline */\n🛠️ Commands:\n\njavac filename.java     // Compile the program\njava filename           // Run the program\n\nDay 3:\n\n\n//variable is a conatiner which holds value\n//java static and strongly type language\n//static:because its data type defined initailly\n//after defined data type we should assign the values as per that datatype range itself it tells us java is stronlgy typed as well\n//variable names can contain alll unicodes\n//variable starting should be either of these _,$ or character not digit\n//if we have two words in variabke anme then should follow camelcase\n//if we define static variable then give all captail letters for that\n\nP## 1. Data Types\n\n### char\n- 2 bytes\n\n### byte\n- 1 byte\n- Signed (2's complement)\n- Default: 0\n\n### short\n- 2 bytes\n- Example: short var = 4;\n\n### int\n- 4 bytes\n- Example: int var = 45;\n\n### long\n- 8 bytes\n- Example: long var = 456L;\n\n### float\n- 32-bit (IEEE 754)\n- Example: float var = 45.56f;\n\n### double\n- 64-bit (IEEE 754)\n- Example: double var = 43.56d;\n\n### boolean\n- 1 bit\n- Values: true or false\n- Default: false\n\n---\n\n## 2. Types of Conversion\n\n### Widening / Automatic Conversion\n- Lower datatype → Higher datatype\n- Automatic if sufficient range\n\n### Downcasting / Explicit Conversion\n- Higher datatype → Lower datatype\n- Causes error (lossy conversion) unless explicitly typecasted\n- May result in negative values\n\n### Promotion During Expression\n- If range exceeds in expression\n- Automatically promoted to next datatype unless explicitly cast\n\n### Explicit Casting During Expression\n- When lower and higher datatypes are used in an expression\n- Converted to higher type unless explicitly cast\n\n---\n\n## 3. Types of Variables\n\n### Member / Instance Variable\n- Declared inside class\n- Default values assigned as per datatype\n- Separate copy per object\n\n### Static Variable\n- Shared at class level\n- Single copy, not per object\n\n### Constructor Variable\n- Passed via constructor\n- Needs object to be used\n\n### Local Variable\n- Declared inside methods\n- Limited to method scope\n\n### Parameter Variable\n- Passed as arguments to methods\n- Available only within that method\n\n\n\nDay-4:\n\n## 📌 Reference Data Types\n\n### 🔹 Class\n- Reference type: When we create an object of a class, it creates memory in the heap.\n- That variable points to the memory address.\n- If we update anything with that object, it updates the value at that memory address.\n\n---\n\n### 🔹 String\n\n```java\npublic class Stringbasics {\n    public static void main(String a[]) {\n        String s1 = \"hello\"; // goes into String Constant Pool in heap\n        String s2 = \"hello\"; // reuses \"hello\" from pool if it exists\n\n        if (s1.equals(s2)) {\n            // checks content equality\n        }\n\n        if (s1 == s2) {\n            // checks reference equality\n        }\n\n        String s3 = new String(\"hello\"); // creates new object in heap\n\n        if (s1 == s3) {\n            // false – references are not equal\n        }\n\n        if (s3.equals(s1)) {\n            // true – contents are equal\n        }\n    }\n\n    // String literals = contents in String Constant Pool\n    // Strings are immutable – updates create a new object in pool\n}\n🔹 Interface\n\npublic interface InnerInterfaceDetails {\n    public String profession();\n}\n\nclass Student implements InnerInterfaceDetails {\n    @Override\n    public String profession() {\n        return \"Masters\";\n    }\n}\n\nclass Employee implements InnerInterfaceDetails {\n    @Override\n    public String profession() {\n        return \"Software Engineer\";\n    }\n}\nWays to create object:\n\n\nInnerInterfaceDetails infoObj1 = new Employee(); // parent reference → child object\nInnerInterfaceDetails infoObj2 = new Student();  // parent reference → child object\nStudent s1 = new Student();                      // child reference → child object\nEmployee e1 = new Employee();                    // child reference → child object\n🔹 Array\n\nint[] arr = new int[5];\nint[] arr2 = {0, 1, 2, 3, 4};\nint arr3[] = new int[5];\nArrays hold the reference to the memory location of the elements.\n\n🔹 Primitive \u0026 Wrapper Types\nPrimitive types (pass by value):\n\n\nchar, byte, short, int, long, double, float, boolean\nWrapper classes (reference types):\n\n\nCharacter, Byte, Short, Integer, Long, Double, Float, Boolean\nAll collections use reference types only.\n\nUse wrapper classes in collections like ArrayList, HashMap.\n\n🔹 Auto Boxing \u0026 Unboxing\n\n// Auto-boxing: primitive → wrapper\nint var1=9;\nInteger var = var1;\n\n// Auto-unboxing: wrapper → primitive\nInteger var=45;\nint var1 = var;\n\n🔹 Constant Variables\n\nstatic int var = 9; // shared across class\n\n// To prevent modification:\nstatic final int VAR = 9;\n\nstatic: one copy at class level\nfinal: value cannot be changed\n\nDay-5:\naccess specifiers:\npublic\nprivate\nprotected\ndefault\n\nreturn types\n\nboolean\nint\n\nmethod name (should be action)\ncamelCase(if two words)\n\nmethod parameters and arguments\n\n\ntypes of methods:\n\nsystem define method: Math.max (JRE)\nuser defined method\noverloaded methods same name of two diff methods and diff parameters\nploy morphism\n\noverrite:subclass has same as parent class vechile and car\n\n\nstatic: class level copy maintained\ncannot use non static methods and variables inside static\ncannit overide staic methods\n\n\ncreate static method when there is no need of instance or class variables\n\nfinal:make method as final whne you dont want to make any chanegs on that in further\n\nabstarct: abstract method can be declared in abstarct class itself and only declaration can make in parent class the rest implementation can be done by child class\n\nvariable paramters: ...var\nbut only one variable arg can be presnet\nand variable arg should be in last\n\n\n\nDay 7:\n\n class Employee{\n  private Employee(){ //it should be same as class name to idefiy easily and it should not have any return type \n    // it should be tye as abstract,static and final\n    // if it is abstract then it should be declraed in parent and define din child right in inheritance concpet as the first step we cannot inherit construtor becuase whereevrr constru present it shoud same as class class it's not achive in child class so we cannot inherit and overriden so no ise of abstract\n    // final: final defines the method should not be mutated as we are mutating the constructor so it should allow\n  //static if we put static it cannot use not static (instance variables) but our construtor assigns or updates values of instance variables so dont put static \n\n    System.out.println(\"con\");\n  }\n  public static Employee getInstance(){ //it should be public and static because non static should require instance to call \n    return new Employee();\n  }\n}\n//what if we put private access specifier for construtor so then we cannot create object of calls from outside this class the main purpose of construtor is create instanc eof a class if we put [privet we cannot achieve that ]\n//  so we should not ok then if we put cons private we have to have explore  (return)that by public another method to create object frommoutside otherwise we cannot create objetct  for it\n public class Constructor {\n    public static void main(String  args[]){\n      Employee empObj=Employee.getInstance();\n      \n    }\n}\npublic class ConstructorChaining {\n    public static void main(String args[]){\n   Person pObj=new Person();\n   \n    }\n}\nclass Person extends ConstructorChainingParent{\n    int age;//localor class variable can  be assigned default value.\n    String name;\n ///no args custom\n  Person(){\n     this(33);//this must be in the first statement this does know before \n    //  super(33);\n    System.out.println(\"custom con\"+age+\"\"+name);\n  }\n  Person(int age){\n    this(age,\"swathi\");\n    //   super(33);\n    this.age=age;\n  }\n  Person(int age,String name){\n     super(33);\n    this.age=age;\n    this.name=name;  }\n}\n\nparent\n public class ConstructorChainingParent {\n    int age;\n      ConstructorChainingParent(int age){\n        this.age=age;\n        System.out.println(\"Im parent\"+age);\n      } \n}\nJava Constructor Concepts: Organized Notes\nLet me organize your notes about Java constructors, constructor chaining, and access modifiers into a clear, structured format.\n1. Constructor Basics\n\nDefinition: A constructor is a special method used to initialize objects\nCharacteristics:\n\nMust have the same name as the class\nNo return type (not even void)\nExecutes automatically when an object is created\n\n\n\n2. Constructor Access Modifiers\nPrivate Constructors\n\nMakes direct instantiation from outside the class impossible\nUse cases:\n\nSingleton pattern\nFactory method pattern\nUtility classes (static methods only)\n\n\nExample:\n\njavaclass Employee {\n  private Employee() {\n    System.out.println(\"con\");\n  }\n  \n  public static Employee getInstance() {\n    return new Employee();  // Factory method\n  }\n}\nWhy Constructor Can't Be...\n\nAbstract: Constructors can't be inherited or overridden (must have same name as class)\nStatic: Constructors initialize instance variables, static methods can't access non-static members\nFinal: Not needed as constructors can't be overridden anyway\n\n3. Constructor Chaining\n\nDefinition: Calling one constructor from another within the same class\nImplementation: Using this() keyword\nRules:\n\nthis() must be the first statement in the constructor\nOnly one this() call allowed per constructor\n\n\n\n4. Constructor and Inheritance\n\nChild classes don't inherit parent constructors\nParent constructor is called before child constructor\nIf no explicit call, super() is implicitly called\nUsing super(parameters) to call specific parent constructor\n\n5. Visual Representation\nartifact: constructor-conceptsJava Constructor ConceptsDiagram 6. Constructor Execution Flow Example\nartifact: execution-flowConstructor Execution Flow ExampleDiagram 7. Code Example Analysis\nExample 1: Private Constructor with Factory Method\njavaclass Employee {\n  private Employee() {\n    System.out.println(\"con\");\n  }\n  \n  public static Employee getInstance() {\n    return new Employee();\n  }\n}\n\npublic class Constructor {\n  public static void main(String args[]) {\n    Employee empObj = Employee.getInstance();\n  }\n}\nOutput: con\nKey Points:\n\nPrivate constructor prevents direct instantiation\nFactory method provides controlled object creation\nCould be modified to implement Singleton pattern\n\nExample 2: Constructor Chaining\njavaclass Person extends ConstructorChainingParent {\n  int age;\n  String name;\n  \n  Person() {\n    this(33);  // Calls Person(int)\n    System.out.println(\"custom con\" + age + \"\" + name);\n  }\n  \n  Person(int age) {\n    this(age, \"swathi\");  // Calls Person(int, String)\n    this.age = age;  // Note: This overwrites value set in Person(int, String)\n  }\n  \n  Person(int age, String name) {\n    super(33);  // Calls parent constructor\n    this.age = age;\n    this.name = name;\n  }\n}\n\nclass ConstructorChainingParent {\n  int age;\n  \n  ConstructorChainingParent(int age) {\n    this.age = age;\n    System.out.println(\"Im parent\" + age);\n  }\n}\nExecution Flow:\n\nPerson() calls Person(33)\nPerson(33) calls Person(33, \"swathi\")\nPerson(33, \"swathi\") calls ConstructorChainingParent(33)\nParent constructor executes, prints \"Im parent33\"\nPerson(33, \"swathi\") sets age=33, name=\"swathi\"\nPerson(33) sets age=33 again (redundant)\nPerson() prints \"custom con33swathi\"\n\n8. Best Practices\n\nKeep constructors simple and focused on initialization\nFollow the constructor chaining pattern for parameter variations\nUse factory methods for complex object creation logic\nConsider validation in constructors to ensure object integrity\nMinimize side effects in constructors (like network calls or file I/O)\n\n\n\nWeek-3:\n\nDay 8:monday\n\nstack ,heap and garbage collector mark and sweep\n\nstack:stroes primitive variables and references to the objects which are stored in heap\nwhenever we create a instance of a object the object is going to store at heap and that heapmemory reference stored in stack\n\nwhenever string encounters in our code it simple stores a reference obj in string constant pool ,if we create another sting with same first it checks whether string constant contain that value or not if it does it simply store that refrence only instead of creating new one, when we say new String then it creas new constant pool\n\nas we know jvm periodaically runs the GC here when gc stars running all the appliation progess or api is being passed till GC complets its execution \nwe have serial GC:stops the world and runs one thread\nparallel Gc:runs multiple threads to collect still pasue the applicatipn api but little bit better \nconcurrent gc:depricated in java 9 because it does not perform compact memory collection after swept  and removed in java 14 it runs parallely with app apis to reduce pause but it reslt in fragment left space not compact one\nGI GC : here till java 9 collector default gc remaining 3 of does compact memory collection\n\nstack conatin smultple threads but in heap has one thred****************************(need to focus)\nand in stack whenever a block is started it allocates a frame for that block as go throguh when encounter block end the frame from stack would be deleted in last in first out order\n here while allocation or code is being compiled if encounters a open brance it assumes it has new method and it allocate new frmae for that in memory\nbut if that block contains any reference variabke then reference variable container would be deleted but not the actula reference from heap so to clear that actual memory space in heap GC will come into play \n JVM throughly runs GC to check whether heap does conatins any unreferenced objects from stack it if does then simply remove it from heap by using mark and sweep algorithm\n\nas refrences are concerd we ahve 3 types of reference  \nstrong reference: when GC runs if it encounters  a string ref just check whther ref exit in stack or not if not only removes it from heap \n\nbut in week ref case GC simply removes the memory for that reference in heap irrespective of checking from stack ,althougth if try to access it from stack simple gives numm pointer exception i think gives null\n\nwhereas in case of sensitive it is similar to week but before it does cleanup only in case of emergency \n\n\n\n how GC works by using mark and sweep algoriythm:\n\n here in heap we have two phases\n\n young phase and older phase\n young has 3 block eden,survivor0,survivor1\n\n first when create object it goes into young eden phase as soon as GC runs as it follows mark an dsweep algo it first makrs the object which are unreferenced okay then it removes fron eden and move the nremaining objs to su0 and update the age by 1, beofre next Gc runs if we create any obj it goes to eden first then now if gc runs it again mark nodes and sweep them and move object to su1 and incrementin age accordingly then after GC ruuning 3rd time it moves to su0 agin it circulate between 2block especially once moves to survivor space of new it goes eden here one facto every heap has some threeshold it object age reahces threeshold it simple mv=oves to old generation as major gen for young we call minor in old gen as well GC folow same process but as the old the process it little bit slow compare to young and we have one more block non heap meta space it stores class variavles ,static,static final constants beofre java7 we have peremanent space but it inclues in heap when it fills it throuws error as heap as limited space okay so that it moved to out of heap and named as meta space it stores info about class \n\n\nJava Memory Management: Stack, Heap, and Garbage Collection\nI've organized your notes into a comprehensive explanation of Java memory management. Here's a clear breakdown of the concepts:\nStack\n\nPurpose: Stores primitive variables and references to objects in heap\nCharacteristics:\n\nEach thread has its own stack\nWhen a new code block starts, a new frame is allocated on the stack\nWorks in Last-In-First-Out (LIFO) order\nWhen a block ends, its frame is removed from the stack\nLimited in size compared to heap\n\n\n\nHeap\n\nPurpose: Stores actual objects created during runtime\nCharacteristics:\n\nSingle shared memory area across all threads\nManaged by Garbage Collector\nDivided into generations for efficient memory management\n\n\n\nHeap Generations\n\nYoung Generation:\n\nEden Space: Initial allocation area for new objects\nSurvivor Spaces (S0 and S1): Objects that survive GC cycles move here\nObjects cycle between S0 and S1, with age incremented each cycle\n\n\nOld Generation (Tenured):\n\nObjects that survive multiple GC cycles and reach age threshold\nMajor GC runs here (slower but less frequent)\n\n\n\nString Constant Pool\n\nSpecial area in memory that stores string literals\nIf creating a string with same value, JVM checks if it exists in pool first\nUsing new String() forces creation of a new object regardless of pool content\n\nMetaspace (Non-Heap)\n\nReplaced PermGen space since Java 8\nLocated outside of heap memory\nStores:\n\nClass metadata\nStatic variables\nStatic final constants\n\n\n\nGarbage Collection\n\nPurpose: Reclaim memory occupied by unused objects\nMark and Sweep Algorithm:\n\nMark: Identify live objects (referenced from stack)\nSweep: Remove unmarked objects and compact memory\n\n\n\nGC Process\n\nMinor GC: Runs on Young Generation\n\nMarks unreferenced objects in Eden\nMoves surviving objects to S0/S1, incrementing age\nObjects circulate between survivors until reaching threshold\n\n\nMajor GC: Runs on Old Generation\n\nSlower but less frequent\nSame marking and sweeping process\n\n\n\nReference Types\n\nStrong References: Normal object references\n\nGC only removes if no references exist in stack\n\n\nWeak References: Removed during next GC cycle\n\nRegardless of stack references\nAccessing after GC returns null\n\n\nSoft References: Similar to weak but cleared only when memory is low\n\nUsed for caching scenarios\n\nhttps://claude.ai/public/artifacts/db4d5c3b-50f8-425d-bd40-77c67da9e741\n\n\n===========================================================================================\n\nDay 8:Tuesday\n\nClass Types:\nConcrete class:\nA class that we can create instance for it and all methods in this class should contain implementation. It may be implemented by interface or it can be extended from abstract parent class\nby achieving abstraction in this point. Access modifier would be public or private package.\n\nAbstract class:\nA key which abstract key in front of class name. As it suggests, it should have at least one abstract method and it may contain implementation methods remaining.\n❌ we cannot create instance for it. Access modifier would be public or private package.\n\nSuper Class and Sub Class:\nAlso known as parent and child class. A class which can be inherited by other class called child class, and a class which is inherited is called parent.\nAlways a parent class can refer to child object.\nWhen we call child class constructor by default it calls parent constructor under the hood — it contains super() for default constructor.\nIf it is a parameterised one, we should call super() manually.\n\nObject:\nLet say A is parent for B class, so B is child. Then for A the object is parent class:\n\njava\nCopy\nEdit\nObject obj = new A();\nObject obj = new B();\nobj.notifyAll();\nNested Class:\nStatic Nested Class:\nA class inside another class is called nested class.\nLet’s say a particular class is being used in only one class, then instead of creating new file for that we can create class inside the class where we were using this class.\n\njava\nCopy\nEdit\nclass A {\n    static class B {\n        public void print() {\n        }\n    }\n}\nSo as B is static class, no need of object creation for outer class.\nBut it cannot access instance members of parent — only static members can access.\n\njava\nCopy\nEdit\nA.B abobj = new A.B();\nabobj.print();\nNon-Static Nested Class:\ninner class\n\nmember class\n\nanonymous class\n\nInner Class:\nSame like a class inside another class. Here we should create object for outer class as well if we want to use members of nested class.\n\njava\nCopy\nEdit\nclass A {\n    class B {\n        public void print() {\n        }\n    }\n}\n\n// A obj = new A();\nB bobj = obj.new B();\nbobj.print();\nMember Class:\nMember class defines a class which is defined inside a member of another class\nso that it can be accessed inside that block itself.\nAs we know, once end brace encounters, its frame will be removed from stack.\n\nIts access modifier is private because it cannot be used outside the block.\nIf we want to use outside, have to create one public member inside that block and expose that instance of private class.\n\njava\nCopy\nEdit\nclass A {\n    public void display() {\n        class B {\n            System.out.println(\"print\");\n        }\n        B bobj = new B();\n        bobj.print();\n        \n        public expose() {\n            B bobj = new B();\n        }\n    }\n}\nAnonymous Class:\nAnonymous defined as a class that does not have any class name.\nWe usually provide class right? Let say we have a method in abstract class and we need to provide implementation for that — that is no other usage of that —\nthen simply use anonymous class to provide implementation without creating class with class name.\n\njava\nCopy\nEdit\nabstract class A {\n    public abstract void display();\n}\n\nA aobj = new A() {\n    public void display() {\n        System.out.println(\"hii hello\");\n    }\n};\n\n\n\n\nDay-9:wednesday\n\nUnderstanding Java Generics\nBasic Generic Class\njavaclass check\u003cT\u003e {\n    T ob;\n\n    public void assign(T ob) {\n        System.out.println(ob);\n    }\n\n    public T getValObject() {\n        return ob;\n    }\n}\nGeneric Subclass\njava// Generic subclass - preserves type parameter\nclass sub\u003cT\u003e extends check\u003cT\u003e {}\n\n// Non-generic subclass - fixes type parameter\nclass sub1 extends check\u003cInteger\u003e {}\nMultiple Type Parameters\njavaclass multiple\u003cT, K\u003e {\n    private T key;\n    private K val;\n\n    public void assign(T key, K val) {\n        System.out.println(key + \"\" + val);\n    }\n\n    // public T getValObject() {\n    //     return key;\n    // }\n    // public K getValObject1() {\n    //     return val;\n    // }\n}\nGeneric Method\njavaclass check2 {\n    public \u003cT\u003e void assign(T ob) {\n        System.out.println(ob);\n    }\n}\nBounded Type Parameters\nUpper Bound\njava// Single upper bound\nclass upper\u003cT extends Number\u003e {\n}\n\n// Multiple bounds\nclass multibound\u003cT extends Number, inf1, inf2\u003e {\n}\nWildcard Notes\njava// With wildcards, we can have different types for each parameter\n// public void method1(List\u003cT\u003e val1, List\u003cK\u003e val2) {}\n\n// With generic methods, we use a single type parameter\n// public \u003cT\u003e void method1(List\u003cT\u003e val1) {}\n\nWildcard methods can support lower bounds\nGeneric methods with single type cannot handle multiple types\nFor multiple types, we need multi-generic methods\n\nUnbounded Type Parameters\njavaclass sub3 {\n    public \u003cT\u003e void setvashe() {\n        // Here unbounded - can pass any type\n    }\n}\nImportant Concepts\n\nType erasure: After compiling, generic types are erased and replaced with Object in bytecode\nRaw types: When we don't mention any type, just pass values\nUpper bound: We can pass the specified type and its children (e.g., Number and Number's child types)\nLower bound: We can pass the specified type and its parent types\nUnbounded: Can pass any type\n\nUsage Example\njavapublic class GenericExamples {\n    public static void main(String args[]) {\n        // Using generic class with Integer\n        check\u003cInteger\u003e obj = new check\u003c\u003e();\n        obj.assign(3);\n        // obj.assign(\"swathi\"); // This won't work - type safety\n\n        // Generic subclass\n        sub\u003cInteger\u003e st = new sub\u003c\u003e();\n        st.getValObject();\n        \n        // Raw type usage\n        sub sb1 = new sub();\n        sb1.getValObject();\n        \n        // Multiple type parameters\n        multiple\u003cInteger, String\u003e obj4 = new multiple\u003c\u003e();\n        obj4.assign(1, \"swathi\");\n\n        // Generic method\n        check2 gm = new check2();\n        gm.assign(4);\n        \n        // Upper bound example\n        upper\u003cInteger\u003e u = new upper();\n    }\n}\n\n//////////////////////////\n/// \n/// Java POJO and Enum Concepts\nPOJO (Plain Old Java Object)\nA POJO is a simple Java class with the following characteristics:\n\nUses public access modifier for the class\nContains variables (fields) with their getter and setter methods\nCan extend other classes or implement interfaces\nHas a public default constructor\nDoes not use annotations like @Entity (remains framework-independent)\n\nCommon Use Cases for POJOs:\n\nData Transfer/Mapping:\n\nWhen receiving data from clients (e.g., JSON like {id, name, address})\nActs as a mapping class to standardize variable names between client and server\n\n\nIn Application Architecture Flow:\n\nTypical flow: Controller → Service → Repository → POJO (entity objects)\nUsed to represent data structures consistently across application layers\n\n\n\nExample of a POJO:\njavapublic class StudentPojo {\n    // Private fields\n    private int id;\n    private String name;\n    private String address;\n    \n    // Default constructor\n    public StudentPojo() {\n    }\n    \n    // Parameterized constructor\n    public StudentPojo(int id, String name, String address) {\n        this.id = id;\n        this.name = name;\n        this.address = address;\n    }\n    \n    // Getter and Setter methods\n    public int getId() {\n        return id;\n    }\n    \n    public void setId(int id) {\n        this.id = id;\n    }\n    \n    public String getName() {\n        return name;\n    }\n    \n    public void setName(String name) {\n        this.name = name;\n    }\n    \n    public String getAddress() {\n        return address;\n    }\n    \n    public void setAddress(String address) {\n        this.address = address;\n    }\n}\nEnum (Enumeration)\nAn Enum is a special type of class in Java that represents a collection of constants:\n\nDeclared using the enum keyword\nImplicitly extends java.lang.Enum class (cannot extend any other class)\nCan implement interfaces\nCan have variables, constructors, and methods\nCan have abstract methods (but each constant must provide implementation)\nConstructor is always private (even default constructor becomes private in bytecode)\nNo other class can extend an enum\nNo need for instance creation as constants are static and final\nOrdinal values start from 0 automatically\n\nAdvantages over Static Final Constants:\n\nType-safety: Methods can accept only valid enum constants\nBuilt-in methods: values(), valueOf(), ordinal(), name()\nCan associate methods and additional data with each constant\nPrevents invalid values being passed to methods\n\nExample of an Enum:\njavapublic enum DayOfWeek {\n    MONDAY(1, \"day1\") {\n        @Override\n        public String specialAboutMyDay() {\n            return \"Shiva\";\n        }\n    },\n    TUESDAY(2, \"day2\") {\n        @Override\n        public String specialAboutMyDay() {\n            return \"Yallamma Thalli\";\n        }\n    },\n    WEDNESDAY(3, \"day3\") {\n        @Override\n        public String specialAboutMyDay() {\n            return \"Vinayaka\";\n        }\n    },\n    THURSDAY(4, \"day4\") {\n        @Override\n        public String specialAboutMyDay() {\n            return \"Ayyappa Swamy\";\n        }\n    },\n    FRIDAY(5, \"day5\") {\n        @Override\n        public String specialAboutMyDay() {\n            return \"Laxmi Devi\";\n        }\n    },\n    SATURDAY(6, \"day6\") {\n        @Override\n        public String specialAboutMyDay() {\n            return \"Lord Venkateswara Swamy\";\n        }\n    },\n    SUNDAY(7, \"day7\") {\n        @Override\n        public String specialAboutMyDay() {\n            return \"All Devotionals\";\n        }\n    };\n    \n    // Instance variables\n    private int id;\n    private String day;\n    \n    // Private constructor (enum constructors are always private)\n    DayOfWeek(int id, String day) {\n        this.id = id;\n        this.day = day;\n    }\n    \n    // Getter methods\n    public int getId() {\n        return id;\n    }\n    \n    public String getName() {\n        return day;\n    }\n    \n    // Other methods\n    public String toLowerCase(String day) {\n        return day.toLowerCase();\n    }\n    \n    // Abstract method - each enum constant must implement\n    public abstract String specialAboutMyDay();\n    \n    // Regular method\n    public boolean isWeekend() {\n        return this == SATURDAY || this == SUNDAY;\n    }\n}\nAlternative using Static Final Constants (Less Preferred):\njavapublic class DayConstants {\n    public static final int MONDAY = 0;\n    public static final int TUESDAY = 1;\n    public static final int WEDNESDAY = 2;\n    public static final int THURSDAY = 3;\n    public static final int FRIDAY = 4;\n    public static final int SATURDAY = 5;\n    public static final int SUNDAY = 6;\n    \n    // Disadvantage: This approach is not type-safe\n    public static boolean isWeekend(int day) {\n        return day == SATURDAY || day == SUNDAY;\n        // Nothing prevents passing invalid values like 10 or -1\n    }\n}\nFinal Classes in Java\nWhen a class is declared with the final keyword:\n\nIt cannot be extended by any other class\nTypically used when you want to prevent inheritance\n\nExample:\njavapublic final class ImmutableClass {\n    // This class cannot be extended\n}\n\n// This would cause a compilation error:\n// class ChildClass extends ImmutableClass { }\nCommon Enum Methods\n\nvalues(): Returns array of all enum constants\nvalueOf(String): Converts a string to the corresponding enum constant\nordinal(): Returns the position of the enum constant (zero-based)\nname(): Returns the name of the enum constant as declared\nhttps://claude.ai/public/artifacts/8fa2755c-dbc4-4f53-b86f-4d098503e345\n\n\n\nDay-10 thursday\n\nSingleton Design Pattern Summary\nI've organized and corrected your notes on singleton design patterns and immutable classes. Here's a summary of the key concepts:\nSingleton Implementation Methods\n\nEager Initialization\n\nInstance created when class loads\nSimple but potentially wastes memory if unused\n\n\nLazy Initialization\n\nCreates instance only when needed\nNot thread-safe - can create multiple instances with concurrent threads\n\n\nSynchronized Method\n\nThread-safe using synchronized keyword\nPerformance issues due to locking mechanism for every call\n\n\nDouble-Checked Locking (DCL)\n\nImproved performance with thread safety\nKey corrections:\n\nNeed volatile keyword for thread visibility\nDon't create second instance outside synchronized block\n\n\n\n\nBill Pugh Singleton (Holder Pattern)\n\nUses static helper class\nThread-safe without synchronization\nLazy loading - inner class loads only when needed\nRecommended for Java applications\n\n\nEnum Singleton\n\nSimplest implementation\nThread-safe by JVM design\nAutomatically handles serialization\nHighly recommended approach\n\n\n\nImmutable Class Implementation\nKey principles:\n\nClass declared as final (cannot be extended)\nAll fields private and final\nNo setter methods\nDeep copy for mutable objects in constructor\nReturn defensive copies from getters for mutable objects\n\nThe diagram and code samples have been updated to reflect these corrections. The main technical issues in your original code were:\n\nIn the Double-Checked Locking implementation, you were creating the instance twice\nMissing the volatile keyword in DCL for proper thread visibility\nNeeded consistent defensive copying in your immutable class\n\nBill Pugh and Enum approaches are indeed the best singleton implementations for most Java applications, combining thread safety, lazy initialization (for Bill Pugh), and clean code.\n\n// 1. Eager Initialization\npublic class SingleTonClass {\n    // Instance created at class loading time\n    private static SingleTonClass db = new SingleTonClass();\n\n    // Private constructor prevents external instantiation\n    private SingleTonClass() {}\n\n    // Public access method\n    public static SingleTonClass getInstance() {\n        return db;\n    }\n}\n// Problem: Memory wastage if instance never used\n\n// 2. Lazy Initialization\nclass Lazy {\n    // Instance not created until needed\n    private static Lazy db;\n\n    private Lazy() {}\n\n    public static Lazy getInstance() {\n        if (db == null) {\n            db = new Lazy(); // Created only when needed\n        }\n        return db;\n    }\n}\n// Problem: Not thread-safe - multiple instances possible with concurrent threads\n\n// 3. Synchronized Method\nclass Sync {\n    private static Sync db;\n\n    private Sync() {}\n\n    // Thread-safe but performance penalty\n    synchronized public static Sync getInstance() {\n        if (db == null) {\n            db = new Sync();\n        }\n        return db;\n    }\n}\n// Problem: Performance overhead due to locking for every method call\n\n// 4. Double-Checked Locking (CORRECTED)\nclass DoubleCheck {\n    // volatile ensures visibility across threads\n    private static volatile DoubleCheck db;\n\n    private DoubleCheck() {}\n\n    public static DoubleCheck getInstance() {\n        if (db == null) {\n            synchronized (DoubleCheck.class) {\n                if (db == null) {\n                    db = new DoubleCheck();\n                }\n            }\n        }\n        return db; // Return once, no duplicate creation\n    }\n}\n// Better performance with thread safety\n\n// 5. Bill Pugh Singleton (Holder Pattern)\nclass BillPugh {\n    private BillPugh() {}\n    \n    // Inner static helper class - loaded only when getInstance is called\n    private static class SubClass {\n        private static final BillPugh obj = new BillPugh();\n    }\n    \n    public static BillPugh getInstance() {\n        return SubClass.obj;\n    }\n}\n// Best approach: Lazy loading, thread-safe, no synchronization needed\n\n// 6. Enum Singleton\nenum EnumSingleton {\n    INSTANCE;\n    \n    // Add methods and fields as needed\n    public void doSomething() {\n        // Implementation\n    }\n}\n// Usage: EnumSingleton.INSTANCE.doSomething();\n// Thread-safe by JVM, handles serialization automatically\n\n// Immutable Class Example\nfinal class ImmutableClass {\n    private final int id;\n    private final ArrayList\u003cInteger\u003e list;\n    \n    public ImmutableClass(int id, ArrayList\u003cInteger\u003e list) {\n        this.id = id;\n        // Deep copy in constructor\n        this.list = new ArrayList\u003c\u003e(list);\n    }\n    \n    public int getId() {\n        return id; // Primitive type, no need for defensive copy\n    }\n    \n    public List\u003cInteger\u003e getList() {\n        // Return defensive copy to prevent modification\n        return new ArrayList\u003c\u003e(list);\n    }\n}\n// Thread-safe without synchronization, good for shared resources\nhttps://claude.ai/public/artifacts/515e2dd8-7e62-4b9a-8f31-94c606e003ae\n\nInterface:\nOrganized Notes on Java Interfaces\nBasic Interface Concepts\n\nInterface is a system where two systems connect without knowing each other\nDefault access specifier for interface and its methods is public\nAbstract methods must be implemented by classes that implement the interface\nVariables in interfaces are implicitly static final constants\nCannot create objects for interfaces, only implement them\n\nNested Interfaces\n\nInterfaces can contain other interfaces (nested interfaces)\nClasses can also contain interfaces\nIf a class implements parent interface, it can access both parent and child interface methods\nIf a class implements only child interface, it can only access child methods\nWhen interface is nested in a class, it's implemented using ClassName.InterfaceName\n\nJava 8 Interface Features\n\nDefault methods: provides implementation in interface itself\n\nCan be overridden in implementing classes\nAdded to avoid breaking existing implementations when interface evolves\nAccess specifier is implicitly public\n\n\nStatic methods: cannot be overridden but can be accessed using interface name\n\nCan only access static members\nAccess specifier is implicitly public\n\n\n\nJava 9 Interface Features\n\nPrivate methods: only accessible within the interface\n\nUsed to avoid code duplication between default methods\nIncreases readability and reusability\n\n\nPrivate static methods: only accessible within static methods of the interface\n\nCan only be used in static methods of the interface\n\n\n\nImplementation Rules\n\nClasses must implement all abstract methods of interfaces they implement\nCannot override static methods from interfaces\nCannot modify access specifiers when overriding interface methods\nJava Interface EvolutionImage Java Interface Example CodeCode // Interface Basic Structure\npublic interface Bird {\n    // Abstract methods - implicitly public and abstract\n    void canBreath();  // Must be implemented by implementing classes\n    void fly();        // Must be implemented by implementing classes\nJava Interface Concepts - Organized Notes\nI've organized your notes on Java interfaces while keeping your original language style. Here are the key concepts:\nKey Points About Interfaces\n\nBasic Purpose\n\nInterface is a system where two systems connect without knowing each other\nCannot create objects for interfaces, only implement them\nProvides abstraction and allows multiple inheritance\n\n\nAccess Modifiers\n\nDefault access modifier for interface and its methods is public\nCannot modify access modifiers while overriding interface methods\n\n\nMembers of Interface\n\nAbstract methods: no implementation, must be implemented by classes\nVariables: implicitly public static final constants\nAll abstract methods must be implemented by non-abstract implementing classes\n\n\n\nJava 8 Interface Features\n\nDefault Methods\n\nAdded to avoid breaking existing implementations when interface evolves\nProvides implementation in interface itself\nCan be overridden in implementing classes\nAccess modifier is implicitly public\n\n\nStatic Methods\n\nProvides utility methods related to interface\nCannot be overridden but can be accessed using interface name\nCan only access static members\nAccess modifier is implicitly public\n\n\n\nJava 9 Interface Features\n\nPrivate Methods\n\nOnly accessible within the interface\nUsed to avoid code duplication between default methods\nIncreases readability and reusability\n\n\nPrivate Static Methods\n\nOnly accessible within static methods of the interface\nCan only be used in static methods\n\n\n\nNested Interfaces\n\nInterface within Interface\n\nCan be accessed using Parent.Child syntax\nIf a class implements parent interface, it can access both parent and child methods\nIf a class implements only child interface, it can only access child methods\n\n\nInterface within Class\n\nAccessed using ClassName.InterfaceName\nProvides logical grouping and encapsulation\nCan be implemented by any class\n\n\n\nTechnical Clarifications\nI noticed some technical points that might need clarification:\n\nThe statement \"if a class implements parent interface then class can be accessible for both parent and child methods\" is only true if you're specifically referring to parent interfaces that contain nested interfaces. Normally, implementing an interface doesn't automatically give access to other interfaces.\nIn Java 8+, default methods are not package-private - they are implicitly public, just like abstract methods.\nYour commented code for Java 9 private methods is correct - they can only be used within the interface itself and are useful for avoiding code duplication.\n\nhttps://claude.ai/public/artifacts/8794d598-f822-4b64-820f-9abbcdc31bfd\n\n\n\nDay-11: friday\n\nFunctional interface:\nFunctionalInterfaceEx\nFunInterfaceImpl\n\n\nReflection:\n\n\nimport java.lang.reflect.*;\n//Reflection defines as a method of examining the class,accessspecifiers ,methods and variables in runtime.\n// it can also changes the bhehaviour of it\n//how it changes:\n// the reflection process can happen in runtime becuase it creates a class object of Class\n//this Class represents the class which are running in jvm \n//at that point jvm creates classobj for that Class to access thses classes\n// once obj is created we can get all meta indformation about partilcur class\n// so that first we need to get particulr class obj right\n// here we have 3 ways to get classObj of our class\n//1. Class cObj=class.forName(\"Eagle\");\n//2. Class cObj=Eagle.class()\n//3. Eagle eobj=new Eagle();\n//   Class cObj=eobj.newInstance();\npublic class ReflectionCheck {\n    public static void main(String[] args) {\n        /// class reflection checkingh\n        /// 1.\n        //   Class\u003c?\u003e cObj3 = Class.forName(\"Eagle\"); \n        // System.out.println(cObj.getName());\n        // 2. \n        // Class cObj1=Eagle.class;\n        //  System.out.println(cObj1.getName());\n        // //  3.\n        // Eagle eobj=new Eagle();\n        // Class cobj=eobj.getClass();\n        //  System.out.println(cobj.getName());\n        //     System.out.println(cobj.getFields());\n\n            //method reflcetion\n            Class mObj=Eagle.class;\n            Method allmethods[]=mObj.getMethods();\n            Method decMethods[]=mObj.getMethods();\n            for(Method method2:allmethods){\n                System.out.println(method2);\n            } \n              for(Method method2:decMethods){\n                System.out.println(method2);\n            \n            } \n            Object eobj=new Eagle(); //so cannot create instance as i made class as single but stiil throgh refle tion i can make it lets see\n             Constructor con=mObj.getConstructor(\"Eagle\");\n             con.setAccessible(true);\n             Eagle ealgePrivateConobj=(Eagle)con.newInstance();//seee its private cons and single calls still here able to clreate class so this is also a disadavntag\n\n            Method method =mObj.getMethod(\"eat\", Integer.class);\n            method.invoke(eobj, 12);\n\n              //fileds reflcetion\n            Class fObjClass=Eagle.class;\n            Field[] fileds=fObjClass.getDeclaredFields();\n            for(Field field:fileds){\n                System.out.println(field);\n            }\n        Field fed=fObjClass.getDeclaredField(\"age\");\n        fed.setAccessible(true);\n        fed.set(fObjClass,9);\n\n    }//here it made to change private variable behavious as well so it voilets the oops conpet encapsilatin so this is one of the disadvnatgae\n\n}\n\n class Eagle {\n    private int age;\n    public String name;\n    private Eagle() {//singleton i made this singleton\n        System.out.println(\"I am constructor\");\n    }// constructore\n    public void eat(int age) {\n        System.out.println(\"I am eat\");\n    }// constructor\n    private void jump() {\n        System.out.println(\"I am constructor\");\n    }// constructor\n}\n\n\nas observed throgh refelction it voilets the oops concept of encapsulation buy changeprivate filed fron outside and able to crete instance for singleton class outside \nso not suggestable for use although its not such neccesary we can achive all the behavious with our instance of class\nand one more all these reflection process done in jvm soo it s performance is also slow\n\\\n\n\n\n\n\n\n\n\nAnnotations:\n\n\n\n\n\n\nbefore going to start by mention annotations we are giving information to compiler to add additionchecks as per the mentioned annotation like of we metion @oveeride then compiler will check whether same method conatines conatines inmparent or not @Deprecated: if we decide to not to process further on a particulr method then memthion with annotation as @deprecated then whenevr if they trying to use this particuler method they are able to see warnings as it has been deprecated \n@Override: as we all aware of this to override methods in children classses we use this annotation  \n@SupressWarnings: usually when we are using a method,class, which is not being processed further then we get deprecation warning message to avoid that we can use this annotation \n@FunctionInterface: it is used to let compiler know that its functional interface\n@Savevarargs(heappollution): this is for solve heappollution issue usually when we assign object reference of one to another polllution may happen and to solve that this will be used, but showing compile time issue s is better to avoid get rid of runtime erros right.\ninstead of ising these kind of warnings and moving forward will cause failure in runtime\n\nMeta-Anotations:these are the annoatations that tells where particular annotation will be used and some rules it will be over on anotation\n\n@Target  (type:method,class,field,constructore) it defines where can we use particulr annotaion which is represented below to it\n@Retention: it has (retentionPolicy:source) or class or runtime\nsource: mean sthe annotation will be appear in souce our souce java finl eonly once the copiler creates .class files it will not be there ,\nclass: here annotation willl be represented in .class file as well but not in runtime\nrun time:  here annotation will go till runtime as we see in reflection (then jvm )\n@Documented: annoattions will be appeared in  geenrated  document \n@Inherited: here the if you mention tus annotation the annotation which are mentiong for parent will also be applicable for child as well\n@Repeatable: here it say can we mention same annotation doublke or multipletimes before java8 it noyt possible after java 98 it is but here to do this we need two steps\n\nto create annoattion \n\n@Repeatable(Categories.class); //this is the conatiner to store multiple category values\npublic @interface Category{\n//custom annotation\nString[] name(); //these type would be primitive,enum and string but should not pass args\nint val();\n}\n\npublic @interface Categories{\n    Category[] val();\n}\n@Category(name:\"swathi\")\n@Category(name:\"rajesh\")\n@Category(name:\"gopi\")\npublic class Eagle{\n\n}\n\n@CustomAnotations\n\nas inhave shown in above example we can create custom annoations and by provindg target and retention annotation we add some detial to thet where we use particular annotation and is it repeatable or not\n\n\nDay-12: saturday\n\nExcpetion handling:\n\n// Exception:\n// it is a piece of code it may cause to stop the excution of our code\n// we can handle the exceptions\n//we have two types of exceptions and have errors as well\n// erros:\n// loke jvm erros memory out of error (heap erro) and stack overflow error we cannot handle these \n// where as exceptions are bith two types:\n\n// checked/compile time exceptions\n// // unchecked/runtime exceptions\n// // however\n\n// checked exceptions are \n// object-\u003eException-\u003ethowable-\u003e(Runtimeand compiletime)\n// 1) classNotFoundException\n// here compiler does  force us to handle this while compilation itslef\n//we should handle it by using try-catch or thro it to main call ti ll start of stack\n\n// 2)run time exception \n// 1)arthimatiException\n// 2)ClassCastException\n// 3)IndexOutOFBoundexception(Arrayindexoutofbound,stringindexoutofbound)\n// 4) nullpointerexception\n// here compiler does not force us to handle these exceptions\n\n//its runtime exception just throwing excpetion\n\nimport java.io.IOException;\n\npublic class ExceptionCheckCLass {\n    // public static void main(String[] args) throws ClassNotFoundException {\n     public static void main(String[] args){\n        try {\n            compiletime(0);\n        } catch(IOException ie){\n            System.out.println(ie);\n        }catch (Exception e) {\n            //if theyw ant to put some they can \n            // throw e;//it may again throw it to main caller if it throws from here the caller should throw again\n\n            System.out.println(e);\n            \n        }\n        // catch(IOException ie){\n//this is not work here as all exception are handled above so move to up\n        // }\n          try {\n            compiletime(0);\n        } catch (Exception e) {\n            //if theyw ant to put some they can \n            // throw e;//it may again throw it to main caller if it throws from here the caller should throw again\n\n            System.out.println(e);\n            \n        }finally{\n            //close any streams which are opened i can help you wjen you return from any of them try and catch but when systemgot shutdon and stack or memory erros occured or focrecifully stppped the excution i cannot help you in gthis to excute otherwise i do not have any restriction i ncan run\n        }\n\n\n        //try can use with just try and finally \n        runTime(0);\n    }\n\n    // compile time it thows error sas we not handling it\n    private static void compiletime(int num) throws ClassNotFoundException ,IOException{\n        if (num == 0) {\n            throw new ClassNotFoundException();\n        }\n\n    }\n\n    // it does not throwing any error as its runtimeerror\n    private static void runTime(int num) throws NullPointerException {\n        if (num == 0) {\n            throw new NullPointerException();\n        }\n    }\n}\n\n\n\n\nOperators:\n\noperator is a sign to perform operation on operands\noperands : which are being performed in operation \n\n\n1) arithmatic operators (+,-,*,%,/)\n2) relational operators (==,!=,\u003c=,\u003e=)\n3)logical operators(\u0026\u0026,||,!) ! treadt as unary operator as well\n4) assignment operators (=)\n5)unary operators (++,--,!) single operand\n6) bitwise operators (\u0026\u0026,||,!|,NOT)\n\nfor \u0026-\u003e if both are true then only true\nfor | -\u003e if any on eof them true then it would be true\nfor ^ : -\u003eif both are same then its false if eithe rone of them is diff then its true\n\n~: it chnages from true to false\nfalse to true\n\n\nif we see 1 at MSB it teated as negative here\n\n7)bitwise shift operators (signed left \u003c\u003c ,signed left\u003e\u003e and unsigned right \u003c\u003c\u003c,unsigned right  \u003e\u003e\u003e)\nhere for singed left first we do 1s compliment then we cakculate usalually foir left its n*2 for right its n/2 \nfor unsigned left no diff same as signed left but where as in unsigned right once we shift to right have to take from above for msb as me moved right\nthis is case we should be keep in mid remaing is normal \n\none thing for unsinged need to take 1s compilientn double times as need to do 2's compliment \n8)ternary operator:its mimc the for loop (a\u003eb)? \"hii\":\"heloo\"\n9)instance of type operator   parentclass obj=new chilclase();\n\n obj instanceOf(chilcclass)\n\n \n\n Day-13: sunday\ncontrol flow statements:\nif,ifelse,nested if,if else ladder,while,do while and switch\n\ntopic2:\ncollection\ncollection is a part of collection framework,it is a interface where it expose multiple methods whch has been implemented by collection classes those are arraylist,queue,linkedlit,set\n\n\n\n where as collections: it is a class (utility) where it has all static methods to do operation on collection \n like sort()\n reverse()\n\n import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Stack;\n\npublic class CollectionEx{\n    public static void main(String[] args) {\n        \n List\u003cInteger\u003e li=new ArrayList\u003c\u003e();\n System.out.println(li.add(3));\n System.out.println( li.add(6));\n  System.out.println(li.add(9));\n\n  System.out.println(li.size());//3\n  System.out.println(li.isEmpty());//false\n  System.out.println(li.contains(5));//false\n  System.out.println(li.add(5));\n  System.out.println(li.contains(5));//true\n  System.out.println(li.remove(3));//3rd index will be removed\n  System.out.println(li.remove(Integer.valueOf(5)));//here now it will remove the value of particular indexd\n\n Stack\u003cInteger\u003e st=new Stack\u003c\u003e();\n  System.out.println(st.addAll(li));//all values from li will be added to st\n  System.out.println(st.remove(Integer.valueOf(2)));\n  System.out.println(st.containsAll(li));\n  System.out.println(st.removeAll(li));\n  st.clear();\n  System.out.println(st.isEmpty());\n   /////collections\n  Collections.sort(li);\n    System.out.println(li);\n     System.out.println(Collections.max(li));\n    }\n}\n\n\n\nweek 4:\nDay-14\n\n\n//queue first in first out\n//queue is interface which are extended from collection interface\n//it folows first in out but some exceptions like priorityqueue\nimport java.util.Arrays;\nimport java.util.Collections;\n\nimport java.util.PriorityQueue;\n\npublic class PriorityQueueEx {\n    public static void main(String[] args) {\n        PriorityQueue\u003cInteger\u003e pq = new PriorityQueue\u003c\u003e((a, b) -\u003e b - a);// its by default sort them in ascending ordedr\n        pq.add(5);\n        pq.add(8);\n        pq.add(3);\n        pq.add(1);\n        pq.add(9);\n        System.out.println(pq);\n        pq.isEmpty();\n        // if we want to make pq in descending order need to provide custom comparator\n        // pq.add to add elements in to the pq\n        // pq.add(null)throws exception null pointer exception\n        // offer also add elemtns into the pq it returns false if adding fails\n\n        // poll()//retrives and remove the head of queeu return null if queue is empty\n        // remove()//it throws exception no such element exception if queue empty\n\n        // peek() //just remove first element from queue does not remove it\n        // element is same peek if queue empt just return exception\n\n        // iteratable-collection-queue-PriorityQueueEx\n        // minPriorityQueue - min heap\n        // maxPriorityQueue -max heap\n\n        // add - O(logn)\n        // peek-O(1)\n        // remove-O(logn)\n        // arbitary element -O(n)\n\n        // primitive collection sort\n        int[] arr = new int[] { 3, 5, 68, 9 };\n        // comparator\n        // comaprable compareTo\n        Arrays.sort(arr);\n\n        // object collection sorting\n\n        // comparator (fnctional interface)\n        // which abstarct method\n\n        // Comparator\n\n        Integer[] arr1 = { 4, 56, 7 };\n        Arrays.sort(arr1, (a, b) -\u003e b - a);// its by default sort them in ascending ordedr\n\n        Arrays.sort(arr1);// comparable compare to\n\n        // if a\u003eb = 1 (swap happens)\n        // a==b = 0\n        // a\u003cb =-1\n        for (Integer val : arr1) {\n            System.out.println(val);\n        }\n        Car[] cArray = new Car[3];\n        cArray[0] = new Car(\"telsa\");\n        cArray[1] = new Car(\"porche\");\n        cArray[2] = new Car(\"hondai\");\n        Arrays.sort(cArray, (a, b) -\u003e a.compareTo(b));// this compares and sorts in lexicograpahical order\n    }\n\n}\n\nclass Car implements Comparable\u003cCar\u003e {\n    String carType;\n\n    public Car(String type) {\n        this.carType = type;\n    }\n\n    @Override\n    public int compareTo(Car o) {\n        // TODO Auto-generated method stub\n        return this.carType.compareTo(o.carType);\n    }\n}\n\nJava Queue and PriorityQueue Notes\nQueue Interface\n\nQueue is an interface that extends from Collection interface\nFollows First In First Out (FIFO) principle\nSome exceptions like PriorityQueue don't strictly follow FIFO\n\nPriorityQueue\n\nDefault behavior: Sorts elements in ascending order (min heap)\nCustom comparator: Can be used for descending order (max heap)\n\nKey Methods\nMethodDescriptionException Handlingadd()Adds elements to PQThrows exception if adding failsoffer()Adds elements to PQReturns false if adding failspoll()Retrieves and removes headReturns null if queue is emptyremove()Retrieves and removes headThrows NoSuchElementException if emptypeek()Just returns first elementReturns null if emptyelement()Same as peek()Throws exception if empty\nTime Complexity\n\nadd: O(log n)\npeek: O(1)\nremove: O(log n)\narbitrary element search: O(n)\n\nImportant Notes\n\npq.add(null) throws NullPointerException\nMin PriorityQueue = min heap\nMax PriorityQueue = max heap\n\nHierarchy\nIterable → Collection → Queue → PriorityQueue\nSorting in Java\nPrimitive Arrays\njavaint[] arr = {3, 5, 68, 9};\nArrays.sort(arr); // Uses natural ordering\nObject Arrays\nUsing Comparator (Functional Interface)\njavaInteger[] arr1 = {4, 56, 7};\nArrays.sort(arr1, (a, b) -\u003e b - a); // Descending order\nArrays.sort(arr1); // Ascending order (uses Comparable)\nComparator Logic\n\nIf a \u003e b → return positive (swap happens)\nIf a == b → return 0 (no swap)\nIf a \u003c b → return negative (no swap)\n\nComparable Interface\n\nClasses implement Comparable\u003cT\u003e interface\nMust override compareTo() method\nUsed for natural ordering\n\nExample Code Structure\njava// PriorityQueue with custom comparator (descending order)\nPriorityQueue\u003cInteger\u003e pq = new PriorityQueue\u003c\u003e((a, b) -\u003e b - a);\n\n// String sorting (lexicographical order)\nArrays.sort(stringArray, (a, b) -\u003e a.compareTo(b));\n\n// Custom class implementing Comparable\nclass Car implements Comparable\u003cCar\u003e {\n    String carType;\n    \n    @Override\n    public int compareTo(Car other) {\n        return this.carType.compareTo(other.carType);\n    }\n}\n\n\n\n\n\nDay-15:\nDequeue-insert and delete from both ends\nArrayDeque:its array but extends queue so that from this we can insert and delete from biut ends of array basically we use this shilw implementing the stack or queue from array\nList\nIterator-it implements iterable i intyerface it itterators over the collection ot has hasNext,next and remove\nLinkedList: it implemets list and queue so that we can add elemnt from first and last and from index basis as well\nVector: same as arraylist but it thread safe\nSatck:follows last in firt our order it also implements queue but its thread safe because for vector ans stack put lock on threads by using syncronised functional interface\n\n\nMap: (very important)\nmap does not extends from collections here all the collections have unique values but in hashmap we have two one iskey abf value\n here in hashamo key are uniquee\n\n we have size()\n isEmpty()\n put()\n remove()\nits a form of table underthehood like whle initilizaing if we metion  any size it takes that size otherwise it just take default size as 16\nand for each cell conatins hash,key,val,node next \n first whenevrr we try to insert like put the key into the map its first calculate the hash value fir that \n and it does % with size the map default 16 then will get index in that index it append key and value and hash which we calculuted and key ,value from input.\n\n lets say if two or more keys get same index then it creases childrn linkedlist at particular index of  next  it points to  that  is nested linkedlist.\n it would be helppul innfurther processing while getting elements\n\n if linkedlist size grows there is a threeshold (loadfactor) if it reaches tjat loadfactor it simply converts linkedlist into treefy RBL trees binary search trees (AVL trees) this is the process happeing underthe hood\n for put\n let say when trying to a key from hash sae process uts again calculate the hash from that it calute mod same as before and checks whetehr tjat mainindex conatins the key which we need or not if not it checks whetehr the children linkedlist is there for that index or not if it does then it itterates ove r th elinkedi and cehcjs for the key whereas if it contains a Binary search its slight more easy to get elemnet or to search  as we eliminate half part of the tree as per key value\nit also as a node next \n Hashtable:\n so hashmap and table almost similar with minor differences those are hashmap not htread safe whereas hashtable are (syncronized put locks for threads) and hashtable does not allow null but in hashmap we can use null as key and value \n and hashtable follows order but hashmap odes not\n \n time compleixty for hashmap: \n put: avergae O(1) \nget:average O(1) worest case its O(n) if we have linked list if trr\nsearch:O(1) worest caseits O(n) where as for binary search tree its O(logn)\nremove():O(1) worest caseits O(n) where as for binary search tree its O(logn)\n\n\nlinkedhashmap:\nit is similar to hashamap but it follows linkedit nature and contains extra two keys for before and after to maintian the before an dafter of particular node\nwhile inserting it follow same process as hashmpa calculating hash and % of length of map to get index then once key is being added it updates the before and after  for that \nagain this is not htread safe but explicltoy to make thread safe use utility class Collections.syncronizedMap(new LinkedList());\n\nHashMap\u003cInteger,String\u003e map=new LinkedHashMap\u003c\u003e();\n\nTreemap:\nmap-sortedmap-navigablemap-treemap\n\nmap\u003cInteger\u003e map=new TreeMap\u003c\u003e();\n\nits is a node where its has left,parent,key,value,right\nit uses RBL trees means RBL sorted array so it takses O(logn) averaga time complexity\nfor parnt node its parent is null \n\nit has few methods and it folows sorting oirder default as asceining and if we mention comparatore tjhen it follows that \ncomparator\n\nmap.headmap(tokey) //exclusive\nmap.tailMap(fromkey) //inclusive\nmap.firstKey()\nmap.lastKey();\n\n\nJava Collections Framework\nQueue Implementations\nArrayDeque\n\nImplementation of queue using an array\nAllows insertion and deletion from both ends (double-ended queue)\nUsed for implementing both stack and queue data structures\nNot thread-safe\nOperations: addFirst(), addLast(), removeFirst(), removeLast()\n\nLinkedList\n\nImplements both List and Queue interfaces\nAllows element insertion/deletion at both ends and at specific index positions\nDouble-ended queue capabilities with methods like addFirst(), addLast(), removeFirst(), removeLast()\n\nVector\n\nSimilar to ArrayList but thread-safe\nUses synchronized methods for thread safety\nGenerally slower than ArrayList due to synchronization overhead\n\nStack\n\nFollows Last-In-First-Out (LIFO) order\nThread-safe (extends Vector)\nOperations: push(), pop(), peek()\n\nIterator\n\nImplements Iterable interface\nUsed to iterate over collections\nMain methods: hasNext(), next(), remove()\n\nMap Implementations\nHashMap\n\nStores key-value pairs where keys must be unique\nDoes not extend from Collections framework (separate hierarchy)\nCore operations: put(), get(), remove(), size(), isEmpty()\n\nInternal Implementation:\n\nDefault initial capacity: 16 buckets\nUses array of buckets under the hood\nProcess for put() operation:\n\nCalculates hash code of the key\nMaps hash to array index using hash % array_length\nStores key-value pair at calculated index\nHandles collisions using linked lists at each bucket\n\n\n\nCollision Handling:\n\nInitially uses linked lists for collision resolution\nIf linked list size exceeds threshold (load factor), converts to Red-Black Tree\nConversion to tree improves worst-case performance from O(n) to O(log n)\n\nPerformance:\n\nAverage case: O(1) for put/get/remove operations\nWorst case: O(n) with linked lists, O(log n) with trees\n\nKey Features:\n\nNot thread-safe\nAllows null keys and values\nNo guaranteed iteration order\nHashMap Internal StructureImage HashTable\n\nSimilar to HashMap but with key differences:\n\nThread-safe (uses synchronized methods)\nDoes not allow null keys or values\nTypically slower than HashMap due to synchronization\nHas predictable iteration order (unlike HashMap)\n\n\n\nLinkedHashMap\n\nExtends HashMap with additional linked list structure\nMaintains insertion order of elements\nContains extra references (before/after) for each entry to maintain order\nInternal implementation:\n\nUses same hash calculation process as HashMap\nAdditionally maintains doubly-linked list to track insertion order\nUpdates before/after references when new entries are added\n\n\n\nMaking thread-safe:\njavaMap\u003cInteger, String\u003e synchronizedMap = Collections.synchronizedMap(new LinkedHashMap\u003c\u003e());\nTreeMap\n\nImplements SortedMap and NavigableMap interfaces\nStores entries in sorted order (natural ordering or custom Comparator)\nImplemented using Red-Black Trees\nNode structure: left child, parent, key, value, right child\nFor root node, parent is null\n\nPerformance:\n\nAll operations take O(log n) time\nGuaranteed sorted iteration\n\nKey methods:\n\nheadMap(toKey) - returns entries with keys less than toKey (exclusive)\ntailMap(fromKey) - returns entries with keys greater than or equal to fromKey (inclusive)\nfirstKey() - returns the first (lowest) key\nlastKey() - returns the last (highest) key\n\n\n\n\n\n\n\nDay-16:\nhashset almost similiar to the hashmap except one difference here in hashset we dont concentarte on value we will be having keys only while adding elemnt into the set it adds elemnt as key and value as dummy object so its similar to hashmap but concentareed on keys onlyyyyy \nhashset\nlinkedhashset\ntreeset everything similar to hashmap,linkedhashmapp and treemap\n\n\n\nStream:\n\nwe consider stream as a pipeline through our collection of data passess through\nwhile data passing through pipelines, many intermediate operations can be performed on our data\nit's useful whemn we have to process bulk data we can do parallel processing\n\nhere we have 3 steps to follow\n\n1) create stream for our data\n2) do intermediate operations on data (filter,map,sorted,distint) here we treat these operations are lazy operations because these are executed when terminal operation invoked\n3) do terminal operations on data ( reduce,count,collect,) thses operation will trigger the stream means it closes the stream we cannot perform further processing on streatm after terminal operation\nand one more thing we should chnage main input stream at the end we give output as new stream not inout stream\n\nimport java.util.stream.*;\nimport java.util.*;\n\npublic class StreamEx {\n    public static void main(String[] args) {\n        // from collection to stream\n        List\u003cInteger\u003e li = Arrays.asList(5, 1, 2, 9, 5, 32, 3, 4);\n        Stream\u003cInteger\u003e number = li.stream();\n        System.out.println(number.filter((Integer num) -\u003e num \u003e 33).count());\n        // from array to stream\n        Integer[] arr = new Integer[] { 45, 678, 899 };\n        Stream\u003cInteger\u003e streaData = Arrays.stream(arr);\n        streaData.map((Integer num) -\u003e num * 9)\n                .forEach((Integer n) -\u003e System.out.println(n));\n        List\u003cInteger\u003e fiResult = Arrays.stream(arr).map((Integer num) -\u003e num * 0)\n                .peek((Integer n) -\u003e System.out.println(n)).collect(Collectors.toList());\n        System.out.println(\"wooo\" + fiResult);\n\n        // from static method\n\n        Stream\u003cInteger\u003e streamData = Stream.of(3, 4, 5, 7, 8, 9, 8);\n        // from streambuilder\n        Stream.Builder\u003cInteger\u003e streamData1 = Stream.builder();\n        streamData1.add(9);\n        streamData1.add(5);\n        streamData1.add(3);\n\n        // from stream iterate\n\n        Stream\u003cInteger\u003e streamDataIt = Stream.iterate(100, ((Integer num) -\u003e num + 100)).limit(9);\n        // flatmap\n        String[][] list = new String[][] { { \"B\", \"a\", \"A\", \"hiii\", \"hello\", \"hdbfhdkgaekg\", \"asdjkfnhaslfhdf\" },\n                { \"hiii\" },\n                { \"sam\" } };\n\n        System.out.println(Arrays.stream(list)\n                .flatMap((sentence) -\u003e Arrays.stream(sentence)).sorted((a, b) -\u003e b.compareTo(a))\n                .collect(Collectors.toSet()));\n        // System.out.println(st);\n\n        // peek\n\n        System.out.println(Arrays.stream(list).map((st) -\u003e Arrays.stream(st))\n                .collect(Collectors.toSet()));\n    }\n}\n//we have similiar intermediate and terminal function to playu with them and can do parallel processing as well to reduce the time of execution by using fork-join-pool technique in gthis algorthim they use to reduce the task into small chucks till possible and then do processing on small chuck and hthen combine the result  intsead of doing procsseing on one by one \n//once we perform any operation on stream data then we cannot perform on that seperately we can take resilt of first processed one and do operations on that otherwise take from main stream.\n\n\nDay-17:\n\nprocess is instance of a program that is being executed\n\nwhenever we are executing the program our first step is javac filename.java \nit compiles the code and convert into byte code \nthen we run execute java filaname\nat that point of time process is created or started \nonce process started its JVM instance is being created\nwhile creating jvm instance we jvm allocate some memory for that process from overall heap memory thisprocessshould use that memory once when its trying to ius emore it will get memory error\n\nonce jvm instance is created the main thread is being created then the jit compiler starts executing \nso here for each process a jvm instance will be created as i told so it shares heap,codesegement,datasegment among all thread where as stack ,counter,and registery is seperate from each thread they do not share resources\n\nlet start executing main thread while executing by JIT compiler to covert into machine code it may create few thread as per requirement to easy the execution \n \n\nJIT compiler converts byte code into  machine code and stores that machine code into code segement which has been shared by all over the process or instance\n\nlet s say \n\nheap - to store instances which are created in runtime\ncode segement-it stores all the machine code\ndata segemnt- it stores gloabla and static variables (data)\n\nstack- all local variables and method calls\nregistry -it;s store the intermediate result for particulr thread\ncounter -it holds memory address of an insturtion where the  thread is going to start execution \n onece thread creattion and convereting to machine code is done \n\n OS or JVM will schedule the task to run theese threads into cpu\n\n\n lets say t1 as allocated to cpu then thread1 gives its counter and regirty to cpu to execute and cpu does its task whenver os or jvm tells cpu to stop execution of thread1 and if it allocate to anithe rthread then then thread current thread takes its processed resultand stores inti its personall regisrtu and waits for nest call. when next allocted just thread loads registry intermedite results into cpu then cpu starts exeution from where it was left.\n\nprocess does not share any resources among them whereas threads do\n\nmultitasking and multri threading :\n\nmultitasking cannot share resoucres among theem where multiple thread can share\n\n\nthread creation:\nhere we have two ways to create thread\none is by implemening runnable interface and other one is extending thread class in product based companaies uses implement runnable concept because once the class extends one class it cannot extend  others that is why\n\npublic class RunnableInterfaceThread {\n    public static void main(String[] args) {\n        MyClass1 clsObj1 = new MyClass1(); // instance of our class\n        Thread th1 = new Thread(clsObj1);// thread created underthe wood it runns the our class run method\n        Thread th2 = new Thread(clsObj1);\n        // th1.start();// we need to start the thread\n        // th2.start();\n\n        Thread th3 = new Thread(() -\u003e {\n            try {\n                Thread.sleep(1000);\n\n            } catch (Exception e) {\n\n            }\n            clsObj1.produce();\n        });\n        Thread th4 = new Thread(() -\u003e {\n\n            clsObj1.consumer();\n\n        });\n        th4.start();\n        th3.start();\n\n    }\n}\n\nclass MyClass1 implements Runnable {\n    boolean isAvaialble = false;\n\n    @Override\n    public void run() {\n        // TODO Auto-generated method stub\n        System.out.println(\"i am implemeing runnable\");\n    }\n\n    public synchronized void produce() {\n        isAvaialble = true;\n        System.out.println(\"i am notifying all\");\n        notifyAll();\n\n    }\n\n    public synchronized void consumer() {\n        System.out.println(\"in cosume in sync\");\n        try {\n            if (!isAvaialble) {\n                wait();\n            }\n        } catch (Exception e) {\n            System.out.println(e);\n        }\n        System.out.println(\"i am acquired lock and done\");\n        isAvaialble = true;\n    }\n\n}\n\nstop,suspend,resume deprecated \n\nt1.join() it makes the current thread to wait until finish certain thread\nit helps if we have dependency on other thread to complete our thread\n\nth1.priority()// 1 lesss 10 high\n\nit does not gurante that threads is execute in this order but it just a hint to thread scheduler to execute next\nif thread schduler has its own priority it follows its own priority\npriority is inherited from parent thread\nor we can setPriority() custom\n\n\nDaemon thread:\nit start executing with main thread asyncronously but when main thread is terminated our daemon thread will be terminated \n\nits most import we use daemon lock for GC, autosave and loggong it does very complex operations\n\nDay-17: Java Threading \u0026 Process Management Notes\nWhat is a Process?\nProcess is instance of a program that is being executed.\nWhenever we are executing the program our first step is javac filename.java - it compiles the code and converts into byte code. Then we run java filename - at that point of time process is created or started.\nOnce process started, JVM instance is being created. While creating JVM instance, JVM allocates some memory for that process from overall heap memory. This process should use that memory - once when it's trying to use more it will get memory error.\nOnce JVM instance is created, the main thread is being created then the JIT compiler starts executing.\nMemory Structure \u0026 Thread Sharing\nSo here for each process a JVM instance will be created. It shares these among all threads:\n\nHeap - to store instances which are created in runtime\nCode segment - it stores all the machine code\nData segment - it stores global and static variables (data)\n\nThese are separate for each thread (they do not share resources):\n\nStack - all local variables and method calls\nRegistry - it stores the intermediate result for particular thread\nCounter - it holds memory address of an instruction where the thread is going to start execution\n\nHow Thread Execution Works\nLet's start executing main thread. While executing by JIT compiler to convert into machine code, it may create few threads as per requirement to ease the execution.\nJIT compiler converts byte code into machine code and stores that machine code into code segment which has been shared by all over the process or instance.\nOnce thread creation and converting to machine code is done, OS or JVM will schedule the task to run these threads into CPU.\nLet's say t1 is allocated to CPU - then thread1 gives its counter and registry to CPU to execute and CPU does its task. Whenever OS or JVM tells CPU to stop execution of thread1 and if it allocates to another thread, then the current thread takes its processed result and stores in its personal registry and waits for next call. When next allocated, the thread loads registry intermediate results into CPU then CPU starts execution from where it was left.\nProcess vs Threads\nProcess does not share any resources among them whereas threads do.\nMultitasking vs Multithreading:\n\nMultitasking cannot share resources among them\nMultiple threads can share resources\n\nThread Creation\nHere we have two ways to create thread:\n\nBy implementing Runnable interface\nExtending Thread class\n\nIn product based companies they use implement Runnable concept because once the class extends one class it cannot extend others - that is why.\nCode Example:\njavapublic class RunnableInterfaceThread {\n    public static void main(String[] args) {\n        MyClass1 clsObj1 = new MyClass1(); // instance of our class\n        Thread th1 = new Thread(clsObj1);// thread created under the hood it runs our class run method\n        Thread th2 = new Thread(clsObj1);\n        // th1.start();// we need to start the thread\n        // th2.start();\n\n        Thread th3 = new Thread(() -\u003e {\n            try {\n                Thread.sleep(1000);\n            } catch (Exception e) {\n            }\n            clsObj1.produce();\n        });\n        \n        Thread th4 = new Thread(() -\u003e {\n            clsObj1.consumer();\n        });\n        \n        th4.start();\n        th3.start();\n    }\n}\n\nclass MyClass1 implements Runnable {\n    boolean isAvailable = false;\n\n    @Override\n    public void run() {\n        System.out.println(\"i am implementing runnable\");\n    }\n\n    public synchronized void produce() {\n        isAvailable = true;\n        System.out.println(\"i am notifying all\");\n        notifyAll();\n    }\n\n    public synchronized void consumer() {\n        System.out.println(\"in consume in sync\");\n        try {\n            if (!isAvailable) {\n                wait();\n            }\n        } catch (Exception e) {\n            System.out.println(e);\n        }\n        System.out.println(\"i am acquired lock and done\");\n        isAvailable = false; // ⚠️ FIXED: Should be false after consuming\n    }\n}\nThread Control Methods\nDeprecated methods: stop, suspend, resume are deprecated\njoin(): t1.join() - it makes the current thread to wait until certain thread finishes. It helps if we have dependency on other thread to complete our thread.\nPriority: th1.setPriority() - 1 is lowest, 10 is highest priority.\n\nIt does not guarantee that thread is executed in this order but it's just a hint to thread scheduler to execute next\nIf thread scheduler has its own priority it follows its own priority\nPriority is inherited from parent thread\nOr we can setPriority() custom\n\nDaemon Thread\nIt starts executing with main thread asynchronously but when main thread is terminated our daemon thread will be terminated.\nIt's most important - we use daemon threads for GC, autosave and logging. It does very complex operations.\n\n⚠️ Technical Fixes Made:\n\nFixed typo: isAvaialble → isAvailable\nLogic fix: In the consumer method, after consuming, isAvailable should be set to false, not true\nSpelling fixes: Various minor spelling corrections throughout\n\nDay-17:socket issue\n\nDay-18:\n\ncustom locks:it does not deal with object\n\n# Reentrant lock: only one htread should allow into critical section irrespective of object\n# readwritelock : mutiple threads can aquire read lock on resource but no write lock can be acquired while read lock acquired by other threads.\n only one write lock can be acquired at any  time no read lock can be acquired while write lock acquired\n    ## shared lock -readlock\n    ## exclusive lock - write lock\n# stampedlock\n  ## optimiclock () - all these custom locks like reentrant lock,read write locks are persimistic locks but on thing here no lock will be available but it manages the stamp to communicate in place of lock and unlock after every thread operation it release lock\n  ## persimistic lock(readwritelock but it maintains the stamp): same as read write lock it uses stamp before doing operation, crosschecks either stamp has changed by some other thread by using lock.validate(stamp) after has been read by this thread.\n#semaphore lock  :here it allows more than one thread to acquire lock at a point of time\n#condition lock : here for all our custom locks we dont have wait and notify like monitorlocks(syncronized) so to add that capability in custom locks we have await (similar to wait) and signal or sigmnalAll similar to notifyall\n\n\n### CAS operation :\ncompare and swap operation its a low level operation\nits single operation\nautomic operation\nwhether running multiple threades or running in mutiple cores parallelly does not matter it treated as single operation\n\nit like optimistic lock method: as it checks rv before updating \nnote: optimistic inspired from cas operation in cas we have 3 paramters those are memory,expected and new value whenevr the expected and memory valuye matched then then it does operation as it update new value\n\n1) load the data from memory (memory address as first argument)\n2) modify \n3)update\nwhere before update checks the expectd and actual value \n\nlet say we have value x=10 , memory address for x=10 and expected as 10 and new value as 15 beofre update it checks actuala nd expected\n\nhere first it has x=10 then 11,then 13 again it chnage to 10 then that should not become true case so that is called ABA issue to resolve that issue \nwe can add timestamp or version to avoid mismates\n\nint count =0; here it is atomic operation\n\n int count =0;\n count++;\n this is not atomic here we are doing 3 operations those are \n first loading the counter from memory\n second modifying count to count+1\n\n thirs updation so overall 3 steps it does not give expetced results when we use threads righty so that here to resole this we have two options \n \n \n 1)lock based system\n 2) lock fee mechanism automic integer \n\n here when we have load,modify and update case use this scenario lock fee mechanism automic integer :\n\n which has been provided by CAS\n\n do{\n    expected=load data from memory\n }while(!CAS(memory,expected,newvalue));\n\n it has been updated till the CAS bemome true\n\n refer :AutomicInteger practice\n\nfinally \n\nwe have  AutomicInteger, AutomicBoolean, AutomicLong and AutomicReference\n\nAtomic vs voilatile\n\nAtomic belongs to threadsafe and related to threads concept whereas \n\nvoilatile not threadsafe not belongs to thread\n\n\nlets say \n\ncpu1-core1-l1cache-\n                          common l2cache -memory\n\ncpu1-core2-l1cache-\n\nlet say if th1 running in core 1 of  cpu and update the x value to 11 from 10 and written in l1 cache of its core where two cores l1 caches are not in sync so while core2 wants to load data of x then it checks with its l1chache l2chache cache as expected it does not contain so it checks with memory while memory contains x but its old value there will be mismatch so to avoid that if we put voilatile beofre variable then every read and writte operation should be done from and to to memory so there would be no mismatch. \n\nfile:///C:/Users/swath/Downloads/concurrency_diagram.html\n\n\n\n\n\nWeek-4-Day-7:\n\nThread pool executor: but not satisfied with day sorry \n\n\nWeek-5-Day-1:\n\nusually when we use threadpoolexecutor we just run submit executor to run the task (it will create thread for that task)\nbut but main thread does not know the status of the thread which created for runnable task\nwhether its completed or stopped or got any execption\n\n\nso here we have Future interface to catch the status of thread which we created \nwe have few methods to get to know the child thread status\n\n1) .done() - it returns true\n   #Future is the interface and it accepts wild card it may be anything the\n        # Future\u003c?\u003e reason to put this is it returns nothing so void in such case it would be Object\n     \n  # main thread does not wait for the child thread\n     \n     isDone() - it returns boolean weather thread complets its execution or not (Done means whatever the status of thread like it may thrown an error, completed successfully, and cancelled)\n     cancel(true or false) -it accepts boolean as argument and it decides as per the argument whether it stop the execution or not if already started execution\n     isCancelled - it returns boolean weather thread execution has been cancelled or not by passing above cancel command\n     get() - it allows main thread to wait for runnable thread to complete its execution, so it sould wait till the time runnable thread completes its execution\n     get(1.TimiUnit.MiNUTES) it allow mainthread to wait fro runnable thread till the time mentioned in the arguments after the time period it does not wait  irrespective of runnable thread status\n        \n      1) we have runnable and callable\n\n     # here one more point i would like to add \n     if we mention like this \n        Future\u003c?\u003e futureObj = executor.submit(() -\u003e {\n            System.out.println(\"i am running\");\n        });\n        it triggers runnable thread becaue we mentioned Future interface attribute type as wildcard so that it means it may or may not return so that it assumes task as runnable type\n        whereas callable sg=hould return something if we mention return type then it triggers callable let me check\n\n//CompletableFuture\n\n//this feature avaiable from java8 \n//it makes task asyncronous\n// it is an advanced feature of Future\n//we have few features in \n//it prodives chaining\n//if we provide poolexecutor then it will take thread from that pool itslef otherwise it takes from default shared fork join pool executor\n\n\n\nWeek-5-Day-2:\n\n1)supplyAsync: it makes task asyncronous (default Forkjoinpool, we can provide executor)\n     \n2) thenApply and thenApplyAsync\n\nthenApply:it allow us to add another function for already executed function (chaining) and it syncronous means it uses same thread which we have used for prev task\n\nthenApplyAsync: it allow us to chain another function to already calcualted function where it is asyncronous so that it takes another thread from pool\n\n3)thenCompose:\n\n thenComposeAsync:\n\n we use compose when we have a dependency where our task dependent on previous task result the we use compose (combining two tasks one after another )\n\n 4) then accpet:its for final when you want to do something in the final after all task done like clearing interval or some cleanup kind of things you can do but it does not return anything\n\n 5) thenCombine: it is the purpose of combining tow task results that is \n\n in all cases async means it runs on different thread than previou thread which did task1\n  if we did not put async it run on same thread which did task 1\n\n\n  so so after careful observation i came to know that putting async is safe because what if our task1 runs on important thread let say threads which accpets user request are limited ,webserver threads need to respond quickly what if our task1 runs on that type of thread and if our task2 is alson running on same thread and our task2 might be slow or it may be long task then our important may block here to complete task2 it efects that performace simply main chef handles the main prep and he manages the front and assitant does the remainingb tasks  it shows better perfomance otherwise if main chef blocked by secondary tasks then customers does not feel good\n\n\n\n\n  week-5 Day-3:\n  1)fixedThreadPool:it has fixed min and max pool size of threads and unbloked queue and live time yes because we have limited threads \n  min and max: 3\n  queue: non blocked\n  live when idle: yes\n  advantage: when we have limited tasks and we know exaclty\n  disadvatange:  what if many tasks submitted then limited thread issue may occur\n\n  2)CacheThreadPool\n\n  min and max: no number it creates threads as per incoming tasks (100 tasks 100 threads)\n  queue: non blocked\n  live when idle: 6seconds\n  advantage: when we have short live threads\n  disadvatange: what if our task take long time the memory error would occur\n\n  3)SinglethreadPool  :\n   min and max: 1,1\n  queue: non blocked\n  live when idle: yes\n  advantage: when the case we have single task\n  disadvatange: no consurrency occured\n\n\n  4)workjoinpool\n  Forkjoinpool: workjoinpool nothung but forkjoinpool because basically in our thread pool executer our tasks converts into small tasks to run paralley by using\n  fork() and then wait to complete all tasks and join the result in this way run concurrently in less time\n  so task1 and task2\n\n  task1 dont have any need to split so thread is executing it\n  where as task2 is big so need to spli into two task so t2,t3 then thread 2 execute the task2 and then each thread contains its own workstealpoolqueue(dequeue)\n  so that thread2 put this sub task3 into thier WSP, however if task1 completes its job then its \n  check\n  1) does it contain any thread its WSt\n  2)does it conatins any thread in submission queue'\n  3) it can steal task from any busy thread in the pool from its WSP back and \n  and put that task into its WSP front\n\n\n\n  1)shutdown; main thread will be terminated immediatley but the threads which are running inside pool will be executed and then (waiting,running,sleeping)\n  2)awaitTermination : it checke wether the thread shutdowned or not after showndown (true or false) because if there any threads running inside it shoudn't be termiated completely ad one thisng here for awaut terminate it give some delay time  after delay it check weather thread terminated or not\n  3)shutdownnow : main thread and all inner thread which are ruuning and waiting completely terminated in this case(await termiate gives you true)\n\n  schedule\n\n  schedule(runnabletask,delay,timeunit);\n  schedule(callableTask \u003cV\u003e,delay,timeunit);\n  scheduleFixedRate(runnable,long delay,long period,Timeunit unit);\n  scheduleFixedDelay(runnable,long initaildelay, long delay, Timeuint unit)\n\n\n  \n  week-6 Day-1:\n\n  Local class\n\n  platform thread and virtula thread\n\n  lombok:\n  1)@val,var\n  2)@NonNull\n  3)@toString\n  4)@getter and @setter\n  5)@AllArgsConstructor\n    @NoArgsConstructor\n    @RequiredArghsConstructor\n  6)HashcodeEquals \n  7)@Data\n  8)@value\n  9)@builder\n  10)@cleanup\n\n  sequenced collection, sequencedmap,sequencedset","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fswathireddy369%2Fjava-core-concepts","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fswathireddy369%2Fjava-core-concepts","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fswathireddy369%2Fjava-core-concepts/lists"}