✅ Day 11 of Studying Java --- 🧠 1. Pass by Value ≠ Pass by Reference (But in Java… it’s tricky!) ✅ In Java, everything is Pass by Value — even object references. 🔹 When you assign `Car b = a;`, you’re copying the *reference value* (memory address), not the object itself. 🔹 Both `a` and `b` now point to the same object → changes via either reference reflect everywhere. 🔸 Real-world analogy? One car, two keys. Change the air freshener with one key → both drivers smell it! ⚠️ Interview Tip: “Java doesn’t have true pass-by-reference — it passes the *value of the reference*. Always clarify with diagrams!” --- 🧱 2. Object Creation & Memory Management in Java 📌 Objects live in the Heap. References live in the Stack. 📌 Instance variables? → Heap. Local variables? → Stack. ♻️ No manual cleanup! Java’s Garbage Collector auto-removes unreferenced objects (the real MVP 🧹). 💡 Fun Fact: Why “Heap”? → It’s where your “heap of garbage” (unreferenced objects) piles up before GC cleans it! --- ⚙️ 3. Java Methods Demystified Every method has 4 parts: 1️⃣ Method Name 2️⃣ Parameters (Input) 3️⃣ Body (Logic) 4️⃣ Return Type (Output) 🎯 4 Types of Methods: - ❌ No input, ❌ No output → `void methodName()` - ❌ No input, ✅ Output → `int methodName() { return value; }` - ✅ Input, ❌ No output → `void methodName(int x)` - ✅ Input, ✅ Output → `int methodName(int x) { return x+1; }` 📌 Pro Tip: `System.out.println()` ≠ returning output. Use `return` for actual data handoff between methods. --- 🏗️ 4. Stack Segment = LIFO in Action 🔁 Last In, First Out (LIFO) — just like your school lunchbox 🍱: → Rice (first in) → Sambar → Snacks (last in) → Snacks eaten first → Rice last! 💻 In Code: The method on top of the stack executes. When done, it pops off → control returns to caller. --- TAP Academy #Java #CoreJava #PassByValue #PassByReference #JavaMemoryManagement #HeapAndStack #JavaMethods #CodingBootcamp #SoftwareDeveloper #TechInterviews #LearnToCode #Programming #JavaOOP #GarbageCollection #JavaTips #CodeNewbie #DeveloperCommunity
Java Pass by Value vs Reference Explained
More Relevant Posts
-
Day 65 of Sharing What I’ve Learned 🚀 Creating Threads in Java — Turning Concepts into Execution After building a clear understanding of programs, processes, and threads, the next step was to move from theory to practice — how threads are actually created and used in Java. Understanding what a thread is is important. But knowing how to create and control it is where things start getting real. 🔹 Two Ways to Create Threads in Java Java provides two primary ways to create threads: 1️⃣ Extending the Thread class Here, we create a class that extends Thread and override the run() method. class MyThread extends Thread { public void run() { System.out.println("Thread is running..."); } } public class Main { public static void main(String[] args) { MyThread t1 = new MyThread(); t1.start(); // starts a new thread } } 👉 start() is important — it creates a new thread and calls run() internally. 2️⃣ Implementing the Runnable interface This is the more flexible and commonly used approach. class MyRunnable implements Runnable { public void run() { System.out.println("Thread using Runnable..."); } } public class Main { public static void main(String[] args) { Thread t1 = new Thread(new MyRunnable()); t1.start(); } } 👉 This approach is preferred because Java doesn’t support multiple inheritance, but it allows implementing multiple interfaces. 🔹 Key Difference Thread → Direct but less flexible Runnable → More scalable and widely used in real-world applications 🔹 Important Observation Creating a thread is not just about writing run() 👉 It’s about understanding how execution flow changes run() → normal method call (no new thread) start() → creates a new thread (parallel execution) 🔹 Simple Perspective Thread creation = defining a task start() = actually running it concurrently 🔹 Why This Matters This is where applications start becoming powerful: 👉 Multiple tasks can run independently 👉 Better performance and responsiveness 👉 Foundation for advanced concepts like thread synchronization and concurrency 🔹 My Realization Earlier, execution felt linear — one step after another. Now it’s clear that: 👉 Execution doesn’t have to wait 👉 Tasks can run side by side 👉 Efficiency comes from how we structure execution This is just the next layer — Up next: controlling threads and managing their lifecycle. #Java #Multithreading #Programming #JavaDeveloper #100DaysOfCode #DeveloperJourney #Day65 Grateful for guidance from TAP Academy Sharath R kshitij kenganavar
To view or add a comment, sign in
-
-
🚀 Exploring Emojis in Java 21 – Complete Guide with Examples! 😄🔥 Did you know that emojis in Java are handled using Unicode code points? Even in Java 21, there is no direct API like isEmoji(), but we can still work with emojis effectively using built-in features. Here’s a complete set of practical programs you can use 👇 💡 1. Print Emoji from Unicode Code Point public class EmojiFromCode { public static void main(String[] args) { int codePoint = 0x1F604; // 😄 String emoji = new String(Character.toChars(codePoint)); System.out.println("Emoji: " + emoji); } } 💡 2. Print Multiple Emojis public class MultipleEmoji { public static void main(String[] args) { int[] codePoints = {0x1F525, 0x1F680, 0x1F44D}; for (int cp : codePoints) { System.out.print(new String(Character.toChars(cp)) + " "); } } } 💡 3. Get Unicode from Emoji (Reverse) public class EmojiToCode { public static void main(String[] args) { String emoji = "😄"; int codePoint = emoji.codePointAt(0); System.out.println("Unicode: U+" + Integer.toHexString(codePoint).toUpperCase()); } } 💡 4. Print All Code Points in a String public class EmojiString { public static void main(String[] args) { String text = "Hello 🔥😄"; text.codePoints().forEach(cp -> System.out.println("U+" + Integer.toHexString(cp).toUpperCase()) ); } } 💡 5. Detect Emoji in a String (Custom Logic) public class EmojiDetector { public static boolean containsEmoji(String text) { return text.codePoints() .anyMatch(cp -> cp >= 0x1F600 && cp <= 0x1F64F); } public static void main(String[] args) { String messageWithEmoji = "Hello Java 21! 😄"; String messageWithoutEmoji = "Hello Java!"; System.out.println(containsEmoji(messageWithEmoji)); // true System.out.println(containsEmoji(messageWithoutEmoji)); // false } } 💡 6. JUnit Test for Emoji Detection import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; public class EmojiTest { boolean containsEmoji(String text) { return text.codePoints() .anyMatch(cp -> cp >= 0x1F600 && cp <= 0x1F64F); } @Test void testEmoji() { String messageWithEmoji = "Hello Java 21! 😄"; String messageWithoutEmoji = "Hello Java!"; assertTrue(containsEmoji(messageWithEmoji)); assertFalse(containsEmoji(messageWithoutEmoji)); } } 🔍 Key Takeaways: ✔ Emojis are Unicode characters (code points) ✔ Use codePoints() instead of charAt() ✔ Convert Unicode → Emoji using Character.toChars() ✔ Java doesn’t provide direct emoji detection (custom logic needed) ✔ Great concept for interviews & teaching Core Java #Java21 #CoreJava #Unicode #Programming #Developers #JavaLearning #CodingTips #JUnit
To view or add a comment, sign in
-
Day 16 — #100DaysJava today I learned Stream API in Java. And honestly, this one changed how I write code. ☕ Before streams, I used to write for loops for everything. Filter this, transform that, add them up. Five lines of code for something simple. Streams do the same thing in one line. Clean, readable, powerful. Here is what clicked for me today — saving this for anyone learning Java --- What is a Stream? A Stream is a pipeline. You take data, pass it through a series of operations, and get a result at the end. You are not changing the original data. You are just processing it. Think of it like a factory assembly line. Raw material goes in. Each station does one job. Final product comes out. --- The three operations I practiced today: filter() — keep only the elements that match a condition. I used it to get only even numbers from an array. Arrays.stream(arr).filter(n -> n % 2 == 0) map() — transform every element. I used it to double every number in the array. Arrays.stream(arr).map(n -> n * 2) reduce() — combine everything into one result. I used it to calculate the sum of all numbers. Arrays.stream(arr).reduce(0, (a, b) -> a + b) --- One thing that confused me first — boxed(). When you have an int array, Java creates an IntStream not a Stream of Integer objects. boxed() converts it from primitive int to Integer object so you can collect it into a List. IntStream → boxed() → Stream of Integer → collect to List Once I understood that, everything made sense. --- collect(Collectors.toList()) is how you end the stream and get your result back as a List. The stream itself does not store data — it just processes it. collect() is what actually creates the final collection. --- The real power of Streams — you can chain all of this together. Filter the evens, double them, collect into a list. One line. No loop. No temporary variables. This is exactly how modern Java code looks in real companies. --- 16 days in. Every day something new clicks. 💪 Day 1 ...................................... Day 16 Are you using Streams in your daily Java work? What is the most useful stream operation you use? Drop it below! 🙏 #Java #StreamAPI #FunctionalProgramming #100DaysOfJava #JavaDeveloper #LearningInPublic #BackendDevelopment #100DaysOfCode #CleanCode #ModernJava
To view or add a comment, sign in
-
🚀🎊Day 86 of 90 – Java Backend Development ✨🎆 In Java, an Enum (short for "enumeration") is a special data type used to define a collection of constants. Think of it as a way to create a fixed list of predefined values that a variable can hold—like the days of the week, compass directions, or the states of a process. Before enums were introduced in Java 5, developers used public static final constants, which were prone to errors and lacked type safety. Enums solved this by making the code more readable and robust. 👉1. Basic syntax: Defining an enum is similar to defining a class, but you use the enum keyword. By convention, enum constants are written in uppercase. enum Level { LOW, MEDIUM, HIGH } You can then use this enum in your code like this: Level myVar = Level.MEDIUM; 👉2. Why use enums? Type Safety: You can't accidentally assign a value that isn't part of the enum (e.g., you can't set a Level to "SUPER_HIGH" if it isn't defined). i) Readability: It makes it clear to anyone reading your code what the allowed options are. ii) Switch Statements: Enums work beautifully with switch blocks, making logic branching much cleaner. 👉3. Enums are classes: In Java, enums are more powerful than in many other languages because they are effectively classes. This means they can have: i) Fields: To store additional data for each constant. ii) Methods: To perform actions based on the constant. iii) Constructors: To initialize those fields (though they are always private or package-private). 👉Code explanation enum TrafficLight { RED("STOP"), YELLOW("CAUTION"), GREEN("GO"); private String action; // Constructor TrafficLight(String action) { this.action = action; } public String getAction() { return this.action; } } 👉4. Useful built-in methods: Every Java enum automatically inherits methods from the java.lang.Enum class: i) values() ----->Returns an array of all constants in the enum. ii) ordinal() ----->Returns the index of the constant (starting at 0). iii) valueOf(String)------>Returns the enum constant with the specified string name. 👉5. When to avoid them: While enums are great for fixed sets of data, don't use them if the list of values needs to change at runtime (e.g., a list of users or products from a database). Enums are strictly for compile-time constants. #Java #Enums
To view or add a comment, sign in
-
-
🚀 Java Revision Journey – Day 33 Today I revised TreeMap in Java, a powerful Map implementation used for storing sorted key-value pairs. 📝 TreeMap Overview TreeMap is a class in java.util that implements the Map interface and stores elements in a sorted order based on keys. Sorting can be done using: • Natural ordering (default) • Custom Comparator 📌 Key Characteristics: • Stores key → value pairs • Maintains sorted order of keys • Uses Red-Black Tree internally • Time complexity → O(log n) for operations • Does not allow null keys (allows null values) • Not thread-safe 💻 Example TreeMap<Integer, String> map = new TreeMap<>(); map.put(3, "C"); map.put(1, "A"); map.put(2, "B"); System.out.println(map); // Output: {1=A, 2=B, 3=C} 🏗️ Constructors Default Constructor TreeMap<Integer, String> map = new TreeMap<>(); With Comparator TreeMap<Integer, String> map = new TreeMap<>(Comparator.reverseOrder()); From Existing Map TreeMap<Integer, String> map = new TreeMap<>(existingMap); 🔑 Basic Operations Adding Elements: • put(key, value) → Inserts in sorted order Updating Elements: • put(key, newValue) → Replaces existing value Removing Elements: • remove(key) → Deletes mapping 🔁 Iteration for (Map.Entry<Integer, String> entry : map.entrySet()) { System.out.println(entry.getKey() + " " + entry.getValue()); } ⚙️ Internal Working (Important) • Uses Red-Black Tree (self-balancing BST) • Maintains sorted keys automatically • Ensures balanced height → O(log n) operations 💡 Key Insight TreeMap is widely used when you need: • Sorted key-value data automatically • Range-based operations (like finding nearest keys) • Implementing leaderboards, rankings, ordered data • Efficient searching with ordered traversal Understanding TreeMap is essential when working with sorted maps and ordered data processing, especially in DSA and backend systems. Day 33 done ✅ — you're building strong mastery step by step 💪🔥 #Java #JavaLearning #TreeMap #DataStructures #JavaDeveloper #BackendDevelopment #Programming #JavaRevisionJourney 🚀
To view or add a comment, sign in
-
-
🚀 Understanding Generics in Java – Write Flexible & Type-Safe Code If you’ve ever worked with collections like List or Map, you’ve already used Generics — one of the most powerful features in Java. 🔹 What are Generics? Generics allow you to write classes, interfaces, and methods with a placeholder for the data type. This means you can reuse the same code for different data types while maintaining type safety. 🔹 Why use Generics? ✔️ Eliminates type casting ✔️ Provides compile-time type safety ✔️ Improves code reusability ✔️ Makes code cleaner and more readable 🔹 Simple Example: List<String> names = new ArrayList<>(); names.add("Sneha"); // names.add(10); ❌ Compile-time error 🔹 Generic Class Example: class Box<T> { private T value; public void set(T value) { this.value = value; } public T get() { return value; } } 🔹 🔥 Advanced Concepts Explained 🔸 1. Bounded Types (Restricting Types) You can limit what type can be passed: class NumberBox<T extends Number> { T value; } 👉 Only Integer, Double, etc. are allowed (not String) 🔸 2. Wildcards (?) – Flexibility in Collections ✔️ Unbounded Wildcard List<?> list; 👉 Can hold any type, but limited operations ✔️ Upper Bounded (? extends) List<? extends Number> list; 👉 Accepts Number and its subclasses 👉 Used when reading data ✔️ Lower Bounded (? super) List<? super Integer> list; 👉 Accepts Integer and its parent types 👉 Used when writing data 💡 Rule: PECS → Producer Extends, Consumer Super 🔸 3. Generic Methods public <T> void print(T data) { System.out.println(data); } 👉 Works independently of class-level generics 🔸 4. Type Erasure (Important for Interviews) Java removes generic type info at runtime: List<String> → List 👉 No runtime type checking 👉 Only compile-time safety 🔸 5. Multiple Bounds <T extends Number & Comparable<T>> 👉 A type must satisfy multiple conditions 🔸 6. Restrictions of Generics ❌ Cannot use primitives (int, double) → use wrappers ❌ Cannot create generic arrays ❌ Cannot use instanceof with generics 💡 Final Insight: Generics are not just a feature—they are a design tool that helps build scalable, reusable, and maintainable applications. Mastering advanced concepts like wildcards and type erasure can set you apart as a strong Java developer. #Java #Generics #AdvancedJava #Programming #JavaDeveloper #Coding #TechInterview
To view or add a comment, sign in
-
☕ Core JAVA Notes — Complete Study Guide 📖 About the Document A thorough, beginner-to-intermediate Core Java study guide spanning 130 pages, packed with clear explanations, syntax breakdowns, real code examples, and comparison tables. Scanned and formatted for students and aspiring Java developers. 🚀 🏗️ What's Inside? 🔷 Chapter 1 — Java Introduction ➤ What is Java? — A high-level, object-oriented, platform-independent language by Sun Microsystems (now Oracle), born in 1995 ➤ The legendary "Write Once, Run Anywhere" (WORA) principle powered by the JVM ➤ Key features: Platform Independence, OOP, Robustness, Multithreading, Rich Standard Library ➤ Where Java is used: Web Development, Mobile Apps (Android), Enterprise Systems ➤ First program: Hello, World! 👋 🔶 Chapter 2 — OOP Concepts (Object-Oriented Programming) ➤ Classes & Objects — Blueprints and instances of real-world entities ➤ POJO (Plain Old Java Object) — private fields, constructors, getters/setters, toString/hashCode ➤ Constructors — Default, Parameterized, this() and super() keywords ➤ Inheritance — extends keyword, parent-child relationships, super calls ➤ Polymorphism — Method Overloading & Overriding ➤ Abstraction — Abstract classes & Interfaces ➤ Encapsulation — Access modifiers: public, private, protected 🟡 Chapter 3 — Core Language Features ➤ Data Types, Variables, Operators, Control Statements (if, switch, loops) ➤ Arrays — single/multi-dimensional, iteration patterns ➤ Exception Handling — try, catch, finally, throws, custom exceptions 🟢 Chapter 4 — String Handling ➤ String class — immutable, pool concept ➤ Key methods: length(), charAt(), substring(), equals(), compareTo(), replace() ➤ StringBuilder — mutable, faster, single-threaded environments ➤ StringBuffer — mutable, thread-safe for concurrent modifications 🔵 Chapter 5 — Collections Framework ➤ ArrayList vs Array — dynamic sizing, java.util.ArrayList ➤ List, Set, Map interfaces — HashMap, HashSet, LinkedList ➤ Iterating with for, for-each, and Iterator ➤ Java Collections = store & manipulate groups of objects efficiently 📦 #CoreJava #Java #JavaProgramming #OOPConcepts #LearnJava #JavaForBeginners #ObjectOrientedProgramming #JVM #WORA #JavaCollections #StringHandling #StringBuilder #Inheritance #Polymorphism #Encapsulation #Abstraction #LambdaExpressions #AnonymousClass #Multithreading #JavaInterviewPrep #PlacementPreparation #ComputerScience #CodingNotes #ProgrammingLanguage #SoftwareDevelopment #JavaDeveloper #BackendDevelopment #TechNotes #StudyMaterial #CodeWithJava
To view or add a comment, sign in
-
𝐈𝐬 𝐄𝐯𝐞𝐫𝐲𝐭𝐡𝐢𝐧𝐠 𝐚 𝐎𝐛𝐣𝐞𝐜𝐭 𝐈𝐧 𝐉𝐚𝐯𝐚? In Java, we often hear that "everything is an object"—but that’s not entirely true. We still rely on 𝐩𝐫𝐢𝐦𝐢𝐭𝐢𝐯𝐞 𝐝𝐚𝐭𝐚 𝐭𝐲𝐩𝐞𝐬 (like int, char, and boolean) for performance and simplicity. However, there are moments when these primitives aren't enough. That is where 𝐖𝐫𝐚𝐩𝐩𝐞𝐫 𝐂𝐥𝐚𝐬𝐬𝐞𝐬 come into play. 𝐖𝐡𝐚𝐭 𝐢𝐬 𝐚 𝐖𝐫𝐚𝐩𝐩𝐞𝐫 𝐂𝐥𝐚𝐬𝐬? A Wrapper class is exactly what it sounds like: a class that "wraps" or encapsulates a primitive data type into an object. This allows you to treat a simple value as a full-fledged object. 𝐖𝐡𝐲 𝐝𝐨 𝐰𝐞 𝐧𝐞𝐞𝐝 𝐭𝐡𝐞𝐦? You might wonder, "Why go through the extra effort of creating an object?" Here are the primary reasons: •𝐂𝐨𝐥𝐥𝐞𝐜𝐭𝐢𝐨𝐧𝐬 & 𝐆𝐞𝐧𝐞𝐫𝐢𝐜𝐬: Java Collections (like ArrayList or HashMap) cannot store primitives. You can’t have an ArrayList<int>, but you can have an ArrayList<Integer>. •𝐍𝐮𝐥𝐥 𝐕𝐚𝐥𝐮𝐞𝐬: Primitives must have a value (e.g., 0 for int). Wrapper objects can be null, which is essential for representing "no data" in databases or APIs. •𝐔𝐭𝐢𝐥𝐢𝐭𝐲 𝐌𝐞𝐭𝐡𝐨𝐝𝐬: Wrapper classes provide helpful tools. For example, Integer.parseInt("123") or Character.isDigit('5'). 𝐓𝐡𝐞 𝐌𝐚𝐠𝐢𝐜 𝐨𝐟 𝐀𝐮𝐭𝐨𝐛𝐨𝐱𝐢𝐧𝐠 𝐚𝐧𝐝 𝐔𝐧𝐛𝐨𝐱𝐢𝐧𝐠 Java makes the transition between primitives and objects seamless through two features: 𝟏. 𝐀𝐮𝐭𝐨𝐛𝐨𝐱𝐢𝐧𝐠 This is the automatic conversion of a primitive to its corresponding wrapper class. 𝐄𝐱𝐚𝐦𝐩𝐥𝐞: Java int b = 357; Integer a = b; // 𝐀𝐮𝐭𝐨𝐦𝐚𝐭𝐢𝐜𝐚𝐥𝐥𝐲 𝐜𝐨𝐧𝐯𝐞𝐫𝐭𝐬 𝐢𝐧𝐭 -> 𝐈𝐧𝐭𝐞𝐠𝐞𝐫 𝟐. 𝐔𝐧𝐛𝐨𝐱𝐢𝐧𝐠 The reverse process: automatically converting a wrapper object back into a primitive. 𝗘𝘅𝗮𝗺𝗽𝗹𝗲: Java Integer objectNum = 24; int primitiveNum = objectNum; // 𝐀𝐮𝐭𝐨𝐦𝐚𝐭𝐢𝐜𝐚𝐥𝐥𝐲 𝐜𝐨𝐧𝐯𝐞𝐫𝐭𝐬 𝐈𝐧𝐭𝐞𝐠𝐞𝐫 -> 𝐢𝐧𝐭 𝐅𝐢𝐧𝐚𝐥 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 Wrapper classes are the "bridge" between the performance of procedural programming (primitives) and the power of Object-Oriented Programming (objects). Understanding when to use them is key to mastering Java's memory management and collection framework. A special Thank You to Syed Zabi Ulla Sir for beautifully explaining this core Java concept and making the logic so clear. #Java #Programming #CodingTips #BackendDevelopment #SoftwareEngineering #WrapperClasses #ObjectOrientedProgramming
To view or add a comment, sign in
-
✨ Most Useful Keywords In Java✨ ➡️final : The final keyword can be applied to classes, variables, methods, and blocks. Once assigned, it cannot be changed. A final class cannot be extended, a final variable cannot be reassigned, and a final method cannot be overridden. ➡️static : The static keyword can be applied to variables, methods, and blocks. Static members can be accessed using the class name without creating an object. Static methods cannot be overridden. ➡️abstract : Used to create a class or method that is incomplete and must be implemented by sub-classes ➡️assert : Used for debugging to test assumptions during runtime ➡️boolean : Represents a logical data type with values true or false ➡️break : Terminates a loop or switch statement immediately ➡️byte : Data type to store 8-bit integer values ➡️case : Defines a branch in a switch statement ➡️catch : Handles exceptions raised in a try block ➡️char : Stores a single character ➡️class : Used to declare a class ➡️continue : Skips the current loop iteration and continues with the next one ➡️default : Executes when no case matches in switch Defines default methods in interfaces ➡️do : Used in a do-while loop (executes at least once) ➡️double : Stores 64-bit decimal numbers ➡️else : Executes when an if condition is false ➡️enum :Defines a fixed set of constants ➡️extends : Used by a subclass to inherit another class ➡️finally : Block that always executes, used for cleanup ➡️float : Stores 32-bit decimal values ➡️for : Used for loop execution with initialization, condition, and increment ➡️if : Executes code when a condition is true ➡️implements : Used by a class to implement an interface ➡️import : Allows access to classes defined in other packages ➡️instanceof : Checks whether an object belongs to a specific class ➡️int : Stores 32-bit integer values ➡️interface : Used to declare a contract that classes must follow ➡️long : Stores 64-bit integer values ➡️new : Creates an object or instance ➡️package : Groups related classes and interfaces ➡️return : Sends a value back from a method and exits it ➡️short : Stores 16-bit integer values ➡️static : Belongs to the class, not object ➡️super : Refers to parent class object or constructor ➡️switch : Selects execution paths based on an expression ➡️synchronized : Controls thread access to prevent data inconsistency ➡️this : Refers to the current object ➡️throw : Explicitly throws an exception ➡️throws : Declares exceptions that a method may pass upward ➡️transient : Prevents variable from being serialized ➡️try : Wraps code that may generate exceptions ➡️void : Indicates a method returns no value ➡️volatile : Ensures variable value is read from main memory, not cache ➡️while: Executes a loop while condition remains true ➡️var: var enables local variable type inference ➡️record: record is a special immutable class used to store data only #javafeatures #oops #opentowork #fresher #softwareengineer #hiring #javadeveloper
To view or add a comment, sign in
-
🚀 LinkedHashMap in Java Collections After exploring HashMap, I moved to LinkedHashMap, which solves one important limitation of HashMap — ordering. 🔹 What is LinkedHashMap? LinkedHashMap is a class in Java Collections Framework It stores data as key-value pairs (K, V) It maintains insertion order 👉 It is an ordered version of HashMap 🔹 Key Features Stores data as (Key, Value) pairs ✅ Maintains insertion order ❌ No duplicate keys allowed ✅ Allows one null key & multiple null values ⚡ Uses hashing + linked structure 🔹 Internal Structure Backed by: Hash Table (Array of buckets) Doubly Linked List (to maintain order) 👉 Uses: hashCode() → find bucket equals() → find exact key 👉 Linked list ensures: Elements are accessed in insertion order 🔹 Constructors LinkedHashMap() LinkedHashMap(int capacity) LinkedHashMap(int capacity, float loadFactor) LinkedHashMap(Map m) 👉 Default: Capacity → 16 Load Factor → 0.75 🔹 Important Methods put(K key, V value) get(Object key) remove(Object key) containsKey(key) containsValue(value) keySet() values() entrySet() ⭐ 🔹 Traversal (Accessing Elements) For-each: for (Map.Entry<K, V> entry : map.entrySet()) { entry.getKey(); entry.getValue(); } Iterator: Iterator<Map.Entry<K, V>> it = map.entrySet().iterator(); Stream (Java 8): map.entrySet().stream().forEach(...) 🔹 Performance Insert → O(1) Search → O(1) Slightly slower than HashMap (due to ordering) 🔹 LinkedHashMap vs HashMap HashMap → No order LinkedHashMap → Maintains insertion order 👉 Use LinkedHashMap when: Order matters along with fast access 🔹 When to Use LinkedHashMap? When you need predictable iteration order When implementing LRU Cache (very important use case) When combining performance + ordering 🔹 Learning Outcome Clear understanding of ordered map structures Difference between HashMap and LinkedHashMap How hashing + linked list work together Better decision-making for choosing Map implementations 🙌 Special thanks to the amazing trainers at TAP Academy: kshitij kenganavar Sharath R MD SADIQUE Bibek Singh Vamsi yadav Hemanth Reddy Harshit T Ravi Magadum Somanna M G Rohit Ravinder TAP Academy #TapAcademy #Week13Learning #CoreJava #CollectionsFramework #LinkedHashMap #HashMap #DataStructures #JavaInternals #LearningByDoing #FullStackJourney #VamsiLearns
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development