Java Program: Write a program to remove duplicates from an array. Core Functionality The program processes an integer array containing several duplicate values (such as 65 and 87). It utilizes a Set data structure to filter out these duplicates and then attempts to sort the result before printing it to the console. Step-by-Step Execution Initialization: An integer array named array is defined with the values {10, 20, 65, 87, 44, 87, 65, 2, 1}. Deduplication: A LinkedHashSet<Integer> is instantiated. A Set is a collection that, by definition, cannot contain duplicate elements. The program iterates through the array using an enhanced for loop. For each number, it checks if the set already contains the value. If not, it adds the value to the set. Note: Since a Set automatically rejects duplicates, the if(!set.contains(num)) check is technically redundant but safe. Sorting: The code calls Arrays.sort(set). Technical Note: In standard Java, Arrays.sort() is designed for arrays, not Collections like a Set. To make this specific code snippet functional in a real environment, the set would typically be converted back into a list or an array before sorting, or a TreeSet would be used to handle sorting automatically. Output: Finally, the program prints the resulting collection to the console. Comparison of Collection Types used Summary of Key Points Purpose: To extract unique elements from a dataset and sort them. Mechanism: Leverages the unique property of the Java Collections Framework (specifically Set) to handle duplicate logic automatically. Result: The original array of 9 elements is reduced to 7 unique elements: [1, 2, 10, 20, 44, 65, 87].
Vinayak Titti’s Post
More Relevant Posts
-
🚀 Java Wrapper Classes & The Mystery of Buffer Caching Many devs get confused when this happens: Integer a = 100; Integer b = 100; System.out.println(a == b); // ✅ true (cached) Integer x = 200; Integer y = 200; System.out.println(x == y); // ❌ false (different objects) 🤔 Why is 100 cached but 200 is not? This behavior occurs because of Integer Caching, a memory optimization technique in Java's wrapper classes. 1. Reference vs. Value Comparison In Java, the == operator behaves differently depending on the data type: Primitives (int): Compares actual numerical values. Objects (Integer): Compares memory addresses (references). It checks if both variables point to the exact same object in memory. 2. The Integer Cache To save memory and improve performance, the Java Virtual Machine (JVM) maintains a cache of Integer objects for frequently used values. The Default Range: Values between -128 and 127 (inclusive) are pre-created and stored in a pool. How it Works: When you assign a value like Integer a = 100, Java uses autoboxing to convert the primitive to an object. Internally, it calls Integer.valueOf(100), which returns a reference to the already existing object in the cache. 3. Why 100 == 100 is True When you declare two Integer variables with the value 100: Both variables are assigned the same reference from the internal cache. Because they point to the exact same object in memory, a == b evaluates to true. 4. Why 200 == 200 is False When you use a value outside the cache range, such as 200: Java must create a new, distinct object for each assignment. Even though their values are the same, these two objects exist at different memory addresses. Because the references are different, x == y evaluates to false. Best Practice To avoid this "trap," always use the .equals() method when comparing Integer objects. This method compares the actual numerical value inside the object rather than its memory location. 💡 Next time someone asks why 200 isn’t cached but 100 is — you know the JVM story behind it 😉
To view or add a comment, sign in
-
𝗝𝗮𝘃𝗮 𝗦𝗲𝗿𝗶𝗲𝘀 – 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝗮𝗹 𝗜𝗻𝘁𝗲𝗿𝗳𝗮𝗰𝗲 & 𝗟𝗮𝗺𝗯𝗱𝗮 𝗘𝘅𝗽𝗿𝗲𝘀𝘀𝗶𝗼𝗻𝘀 (𝗦𝗶𝗺𝗽𝗹𝗲 𝗚𝘂𝗶𝗱𝗲) Java 8 introduced a powerful concept: 👉 Functional Programming in Java The core of it is: • Functional Interface • Lambda Expression Let’s understand both simply 👇 🔹 What is a 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝗮𝗹 𝗜𝗻𝘁𝗲𝗿𝗳𝗮𝗰𝗲? A 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝗮𝗹 𝗜𝗻𝘁𝗲𝗿𝗳𝗮𝗰𝗲 is an interface that has only ONE abstract method. Example: @FunctionalInterface interface MyInterface { void sayHello(); } Key points: • Only one abstract method • Can have multiple default/static methods • Used with Lambda Expressions Real examples in Java: Runnable Callable Comparator 🔹 What is a 𝗟𝗮𝗺𝗯𝗱𝗮 𝗘𝘅𝗽𝗿𝗲𝘀𝘀𝗶𝗼𝗻? A 𝗟𝗮𝗺𝗯𝗱𝗮 𝗘𝘅𝗽𝗿𝗲𝘀𝘀𝗶𝗼𝗻 is a short way to implement a functional interface. 👉 Instead of writing full class → write simple function Without Lambda MyInterface obj = new MyInterface() { public void sayHello() { System.out.println("Hello"); } }; With Lambda MyInterface obj = () -> { System.out.println("Hello"); }; ✔ Less code ✔ More readable ✔ Modern Java style 🔹 How Lambda Works Internally 👉 Lambda provides implementation for the single abstract method of functional interface. So this: () -> System.out.println("Hello"); Means: 👉 “Implement the method sayHello()” Syntax of Lambda (parameters) -> { body } Examples: // No parameter () -> System.out.println("Hello"); // One parameter x -> x * x; // Multiple parameters (a, b) -> a + b; 🔹 Functional Interface + Lambda (Full Example) @FunctionalInterface interface Add { int sum(int a, int b); } public class Main { public static void main(String[] args) { Add obj = (a, b) -> a + b; System.out.println(obj.sum(5, 3)); } } Output: 8
To view or add a comment, sign in
-
-
There is no silver bullet when choosing between LinkedList and ArrayList in Java. I’m currently studying DSA for coding interviews, and revisiting the trade-offs between these two classes has been a great refresher. 𝐋𝐢𝐧𝐤𝐞𝐝𝐋𝐢𝐬𝐭 is an implementation of a doubly-linked list. It stores each record in a node consisting of the data and two pointers. • The Trade-off: You can insert or delete records in O(1) time because you just change the pointers to the new address, but finding data takes O(n) due to link traversing. It also uses more memory to store those extra pointers. • Best Use Case: When you need to frequently insert and delete from the beginning or end of a collection. A classic example is building an "Undo" feature where you constantly save and remove the latest edit. 𝐀𝐫𝐫𝐚𝐲𝐋𝐢𝐬𝐭 uses an internal array that the JVM dynamically resizes when needed. The records are stored in contiguous data blocks, providing excellent memory locality and exploiting CPU cache for fast access. • The Trade-off: You get O(1) read access using indexes. However, insertion and deletion can be O(n) in the worst case because the JVM has to shift elements to make room, or when the array has reach its capacity, copy and rewrite the old data to a new allocated array. • Best Use Case: When you need to iterate over large datasets quickly, such as generating a monthly financial report from thousands of transactions. You can read more about them in the official Java 25 docs: 🔗 LinkedList: https://lnkd.in/d_kVgPpW 🔗 ArrayList: https://lnkd.in/dkpzZZxf
To view or add a comment, sign in
-
-
In Java, the immutability of the String class means that once a String object is created, its value cannot be changed. Any attempt to modify it—such as using methods like concat(), replace(), or substring()—results in the creation of a new String object rather than altering the original. Here are the key reasons for String immutability: ✔️**Security**: Strings often hold sensitive data, including usernames, passwords, URLs, file paths, and network connections. If Strings were mutable, malicious code could change their values after they have been used in security checks. For example: String url = "https://secure.com"; // If mutable, another thread could change it to "http://malicious.com" ✔️**Thread-Safety**: Immutable objects are inherently thread-safe, allowing multiple threads to share the same String without requiring synchronization. This is particularly important in multithreaded environments, such as web servers. ✔️**String Pool Optimization**: Java maintains a String Constant Pool to optimize memory usage. If Strings were mutable, changing one reference could impact all references in the pool, leading to inconsistencies. For example: String a = "Hello"; String b = "Hello"; // Both point to the same object in the pool ✔️**Caching and Performance**: The immutability of Strings allows their hash code to be cached after the first calculation, making them efficient as keys in hash-based collections like HashMap and HashSet. ✔️**Predictable Behavior**: Immutability guarantees that once a String is created, it will consistently represent the same sequence of characters, simplifying debugging and code reasoning. 🟢 In summary, Java strings are immutable to ensure security, thread-safety, memory efficiency, performance, and predictable behavior.
To view or add a comment, sign in
-
What does ‘Abstract’ mean in Java? Or these rules are sometimes part of the written test ;-) Abstraction is a process of hiding the implementation details and only show important functionality. ‘abstract’ keyword is used to create an abstract class and method. The purpose of an abstract class is to specify the default functionality of an object and let its sub-classes to explicitly implement that functionality. Thus, it stands as an abstraction layer that must be extended and implemented by the corresponding sub-classes. • Abstract class can’t be instantiated (it needs to be extended) << abstract class A {} >> | an abstract method contains a method signature, but no method body. << abstract void methodName(); >> • Abstract class is used to provide default/common method implementation to all the subclasses. • If you are extending any abstract class that have abstract methods, you must either provide the implementation of all abstract methods or make this sub-class abstract. • An abstract class can have both abstract and non-abstract (or concrete) methods. • If a class have abstract methods, then the class should also be abstract. • An abstract class can have data member, abstract method, concrete method (body), constructor and even main() method. • An abstract class may have static fields and static methods. • Abstract method can never be final and static. Abstract class and methods are usually declared where two or more subclasses are expected to do a similar thing in different ways through different implementations. Most common e.g. Shape as the abstract class >> its implementation provided by the Rectangle and Circle classes. Note: Abstract classes are not Interfaces. They are different.
To view or add a comment, sign in
-
Java Program: Write a program to check whether the given string is a palindrome using a StringBuilder. Explanation: To check for a palindrome using `StringBuilder`, the process is simplified by leveraging the class's mutable nature and built-in utilities: Explanation: To check for a palindrome using StringBuilder, the process is simplified by leveraging the class's mutable nature and built-in utilities: Initialization: We wrap the original String inside a StringBuilder object. Reversal: The StringBuilder class provides a reverse() method that efficiently flips the character sequence in place. Comparison: Since StringBuilder does not override the equals() method from the Object class (it compares memory addresses rather than content), we must convert the reversed sequence back into a String using toString(). Case Sensitivity: In the example, equalsIgnoreCase() is used to ensure that words like "Radar" or "madam" are still identified as palindromes despite the capital "R". Key Points Summary: A palindrome reads the same forward and backwards. StringBuilder is preferred over String for reversals because String is immutable, meaning every change creates a new object in memory. Always remember to use .toString() before comparing the reversed StringBuilder to the original String.
To view or add a comment, sign in
-
-
🚀 Java Trap: Why remove() in List can remove the WRONG element? 🤔 Looks simple… but can silently break your logic. Java List<Integer> list = new ArrayList<>(); list.add(10); list.add(20); list.add(30); list.remove(1); System.out.println(list); 👉 Output: [10, 30] Wait… we wanted to remove value 1, right? ❌ But Java removed index 1, not value 1. The reason is simple but tricky: remove(int index) // removes by index remove(Object o) // removes by value When you write list.remove(1), Java calls remove(int index). So how do you remove by value? list.remove(Integer.valueOf(20)); // ✅ correct or list.remove((Integer) 20); // ✅ ⚠️ Dangerous case: list.remove(10); This will throw IndexOutOfBoundsException because Java tries to remove index 10. 💡 Real takeaway: Method overloading + autoboxing can create subtle bugs. Always be clear whether you're removing by index or by value. 💬 Small mistake… big production issue. #Java #Programming #Coding #JavaTips #Developers
To view or add a comment, sign in
-
Java Map.Entry Cheat Sheet: Sorted() & Max() Made Simple ------------------------------------------------------------ MAP.ENTRY SYNTAX FOR SORTED AND MAX ----------------------------------- 1. SORTED BY KEY (ASC) map.entrySet() .stream() .sorted(Map.Entry.comparingByKey()) 2. SORTED BY KEY (DESC) map.entrySet() .stream() .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder())) 3. SORTED BY VALUE (ASC) map.entrySet() .stream() .sorted(Map.Entry.comparingByValue()) 4. SORTED BY VALUE (DESC) map.entrySet() .stream() .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) 5. MAX BY VALUE map.entrySet() .stream() .max(Map.Entry.comparingByValue()) 6. MIN BY VALUE map.entrySet() .stream() .min(Map.Entry.comparingByValue()) 7. MAX BY KEY map.entrySet() .stream() .max(Map.Entry.comparingByKey()) 8. MIN BY KEY map.entrySet() .stream() .min(Map.Entry.comparingByKey())
To view or add a comment, sign in
-
Top 5 Causes of Memory Leaks in Java 🚀 Memory leaks in Java may not cause immediate crashes, but they can significantly degrade performance over time. These leaks occur when objects are no longer needed but are still referenced, preventing Garbage Collection from cleaning them up. The top causes of memory leaks in Java include: 1. Unused objects still referenced – Objects remain in memory due to active references. 2. Static collections – Data continues to grow because static variables persist for the entire application lifecycle. 3. Incorrect equals() and hashCode() – This can lead to duplicate entries in collections like HashMap. 4. Unclosed resources – Resources such as database connections, streams, or sessions are not properly closed. 5. Non-static inner classes – These classes hold implicit references to outer class objects. Understanding these causes can help developers write more efficient Java applications.
To view or add a comment, sign in
-
-
🚀 Java Enums – Why not just Classes? 🔹 Ever wondered why we use enum instead of creating constant classes or interfaces? Enums are not just "fancy constants" – they are type‑safe, singleton‑like objects with hidden powers. 💡 Hook: "Imagine traffic lights without enums – everywhere you’d see 'RED', 'GREEN', 'YELLOW' strings… and a single typo could crash the entire system!" ✅ Why Enums over Classes? Type Safety: Compiler ensures only valid values (no random strings). Singleton Guarantee: Each enum constant is a single instance (no duplicates). Readable Code: TrafficLight.RED looks cleaner than "RED" string. Extra Features: Enums can have constructors, methods, and even implement interfaces. 🔍 Internal Working of Enums Every enum internally extends java.lang.Enum. Enum constants are actually static final objects created at class load time. You can add fields & methods → each constant can have its own behavior. Reflection or cloning cannot create new instances → immutability ensured. 🧩 Example: enum TrafficLight { RED("Stop"), GREEN("Go"), YELLOW("Wait"); private String action; TrafficLight(String action) { this.action = action; } public String getAction() { return action; } } 👉 Here, each constant is an object with its own property.
To view or add a comment, sign in
-
More from this author
Explore related topics
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