ð ð ð®ððð²ð¿ð¶ð»ðŽ ðð®ðð® ð ð®ðœ ðð»ðð²ð¿ð³ð®ð°ð²: ðð®ððµð ð®ðœ ðð ðð¶ð»ðžð²ð±ðð®ððµð ð®ðœ ðð ð§ð¿ð²ð²ð ð®ðœ ðð ðð®ððµðð®ð¯ð¹ð² If youâve ever worked with key-value data in Java, the Map Interface is your go-to toolkit. It maps unique keys to specific values â just like storing names and phone numbers in your contacts list ð±. ðð²ð¿ð²âð ð® ðŸðð¶ð°ðž ð¯ð¿ð²ð®ðžð±ðŒðð»: ð¹ ðð®ððµð ð®ðœ: ðð¢ðŽðµðŠðŽðµ, ð¶ð¯ð°ð³ð¥ðŠð³ðŠð¥, ð¢ððð°ðžðŽ ð°ð¯ðŠ ð¯ð¶ðð ð¬ðŠðº â ð±ðŠð³ð§ðŠð€ðµ ð§ð°ð³ ð¯ð°ð¯-ðµð©ð³ðŠð¢ð¥ðŠð¥ ð¢ð±ð±ððªð€ð¢ðµðªð°ð¯ðŽ. ð¹ ðð¶ð»ðžð²ð±ðð®ððµð ð®ðœ: ðð¢ðªð¯ðµð¢ðªð¯ðŽ ðªð¯ðŽðŠð³ðµðªð°ð¯ ð°ð³ð¥ðŠð³ â ðšð³ðŠð¢ðµ ðžð©ðŠð¯ ð°ð³ð¥ðŠð³ ð®ð¢ðµðµðŠð³ðŽ. ð¹ ð§ð¿ð²ð²ð ð®ðœ: ððµð°ð³ðŠðŽ ð¬ðŠðºðŽ ðªð¯ ðŽð°ð³ðµðŠð¥ (ð¢ðŽð€ðŠð¯ð¥ðªð¯ðš) ð°ð³ð¥ðŠð³ â ðªð¥ðŠð¢ð ð§ð°ð³ ð°ð³ð¥ðŠð³ðŠð¥ ð¥ð¢ðµð¢ ð°ð³ ð³ð¢ð¯ðšðŠ ð²ð¶ðŠð³ðªðŠðŽ. ð¹ ðð®ððµðð®ð¯ð¹ð²: ðð©ð³ðŠð¢ð¥-ðŽð¢ð§ðŠ ð£ð¶ðµ ð°ðð¥-ðŽð€ð©ð°ð°ð â ð³ðŠð±ðð¢ð€ðŠð¥ ð®ð°ðŽðµððº ð£ðº ðð°ð¯ð€ð¶ð³ð³ðŠð¯ðµðð¢ðŽð©ðð¢ð±. ðð ð®ðºðœð¹ð²: import java.util.*; public class MapExample {   public static void main(String[] args) {     // ðïžâ£ ðð®ððµð ð®ðœ - ðšð»ðŒð¿ð±ð²ð¿ð²ð±, ð®ð¹ð¹ðŒðð ðŒð»ð² ð»ðð¹ð¹ ðžð²ð     Map<Integer, String> hashMap = new HashMap<>();     hashMap.put(3, "Sachin");     hashMap.put(1, "Amit");     hashMap.put(2, "Ravi");     hashMap.put(null, "Unknown"); // Allowed     System.out.println("HashMap: " + hashMap);     // ð®ïžâ£ ðð¶ð»ðžð²ð±ðð®ððµð ð®ðœ - ð ð®ð¶ð»ðð®ð¶ð»ð ð¶ð»ðð²ð¿ðð¶ðŒð» ðŒð¿ð±ð²ð¿     Map<Integer, String> linkedHashMap = new LinkedHashMap<>();     linkedHashMap.put(3, "Sachin");     linkedHashMap.put(1, "Amit");     linkedHashMap.put(2, "Ravi");     System.out.println("LinkedHashMap: " + linkedHashMap);     // ð¯ïžâ£ ð§ð¿ð²ð²ð ð®ðœ - ðŠðŒð¿ðð²ð± ð¯ð ðžð²ð, ð»ðŒ ð»ðð¹ð¹ ð®ð¹ð¹ðŒðð²ð±     Map<Integer, String> treeMap = new TreeMap<>();     treeMap.put(3, "Sachin");     treeMap.put(1, "Amit");     treeMap.put(2, "Ravi");     System.out.println("TreeMap: " + treeMap);     // ð°ïžâ£ ðð®ððµðð®ð¯ð¹ð² - ð§ðµð¿ð²ð®ð±-ðð®ð³ð² ð¯ðð ð»ðŒ ð»ðð¹ð¹ ð®ð¹ð¹ðŒðð²ð±     Map<Integer, String> hashtable = new Hashtable<>();     hashtable.put(3, "Sachin");     hashtable.put(1, "Amit");     hashtable.put(2, "Ravi");     System.out.println("Hashtable: " + hashtable);     // ð ððð²ð¿ð®ðð¶ð»ðŽ ðŒðð²ð¿ ð® ð ð®ðœ     for (Map.Entry<Integer, String> entry : hashMap.entrySet()) {       System.out.println(entry.getKey() + " -> " + entry.getValue());     }   } } ð¡ ð§ð¶ðœ: When you hear âð³ð®ðð ð¹ðŒðŒðžððœâ, think HashMap. When you need ðŒð¿ð±ð²ð¿, think LinkedHashMap or TreeMap. When you need ððµð¿ð²ð®ð± ðð®ð³ð²ðð, go for ConcurrentHashMap. Understanding these differences helps you write cleaner, faster, and more scalable code ðª #Java #HashMap #CollectionsFramework #LinkedHashMap #TreeMap #JavaInterviewPrep
Java Map Interface: Choosing the Right Map for Your Needs
More Relevant Posts
-
â¡ 10+ Approaches to Find Max or Min Value in Java 8 Streams â Master It Like a Pro ðª Working with Java 8 Streams? Here are 10 powerful and elegant ways to find the maximum or minimum value from a list â all clean, modern, and interview-ready ð ð§© Sample Data List<Integer> myList = Arrays.asList(10, 15, 8, 49, 25, 98, 98, 32, 15); ð¥ Find Maximum Value â 10 Approaches List<Integer> myList = Arrays.asList(10,15,8,49,25,98,98,32,15); 1ïžâ£ Using instance comparator (compareTo on elements) myList.stream().max(Integer::compareTo).get(); 2ïžâ£ Using static comparator (Integer.compare) myList.stream().max(Integer::compare).get(); 3ïžâ£ Using IntStream for primitive comparison myList.stream().mapToInt(Integer::intValue).max().getAsInt(); 4ïžâ£ Using reduce() with Integer::max myList.stream().reduce(Integer::max).get(); 5ïžâ£ Using Collectors.summarizingInt() for all stats myList.stream().collect(Collectors.summarizingInt(i -> i)).getMax(); 6ïžâ£ Using Comparator.comparingInt() (good for objects too) myList.stream().max(Comparator.comparingInt(Integer::intValue)).get(); 7ïžâ£ Using Comparator.naturalOrder() for clean syntax myList.stream().max(Comparator.naturalOrder()).get(); 8ïžâ£ Using Comparable::compareTo (generic Comparable) myList.stream().max(Comparable::compareTo).get(); 9ïžâ£ Using custom lambda comparator (manual compare logic) myList.stream().max((a,b) -> a>b ? 1 : (a<b ? -1 : 0)).get(); ð Using summaryStatistics() for one-line numeric max myList.stream().mapToInt(Integer::intValue).summaryStatistics().getMax(); ð Using sorted() + skip() to pick last element myList.stream().sorted().skip(myList.size()-1).findFirst().get(); ð Same Approaches for Find Minimum Value List<Integer> myList = Arrays.asList(10, 15, 8, 49, 25, 98, 98, 32, 15); 1ïžâ£ myList.stream().min(Integer::compareTo).get(); 2ïžâ£ myList.stream().min(Integer::compare).get(); 3ïžâ£ myList.stream().mapToInt(Integer::intValue).min().getAsInt(); 4ïžâ£ myList.stream().reduce(Integer::min).get(); 5ïžâ£ myList.stream().collect(Collectors.summarizingInt(i -> i)).getMin(); 6ïžâ£ myList.stream().min(Comparator.comparingInt(Integer::intValue)).get(); 7ïžâ£ myList.stream().min(Comparator.naturalOrder()).get(); 8ïžâ£ myList.stream().min(Comparable::compareTo).get(); 9ïžâ£ myList.stream().min((a, b) -> a > b ? 1 : (a < b ? -1 : 0)).get(); ð myList.stream().mapToInt(Integer::intValue).summaryStatistics().getMin(); ð myList.stream().sorted().findFirst().get(); ð¡ Quick Summary for Efficiency ð§ For numeric lists â mapToInt().max() or summaryStatistics() ð For objects â Comparator.comparing() ð For analytics â Collectors.summarizingInt() ðª For readability â reduce() or naturalOrder() âïž For demos â sorted().skip() (less efficient) ð Follow me for more Java 8, Streams, and interview-ready code tips! ð #Java #Java8 #Streams #CodingTips #FunctionalProgramming #InterviewPreparation #CleanCode #Developers #LinkedInLearning #CodeNewbie
To view or add a comment, sign in
-
Strings methods in Java 1ïžâ£ length() Definition: Returns the number of characters in a string (including spaces). ð¡ Why it matters: Useful for checking input length (like passwords, usernames) or controlling loops. Example: String name = "Rakshitha"; System.out.println(name.length()); // Output: 9 2ïžâ£ charAt() Definition: Returns the character at a given index (index starts from 0). ð¡ Why it matters: Helps to access or check specific characters, like the first letter of a name. Example: String word = "Java"; System.out.println(word.charAt(2)); // Output: v 3ïžâ£ toUpperCase() / toLowerCase() Definition: Converts all letters in a string to uppercase or lowercase. ð¡ Why it matters: Useful for ignoring case in comparisons or displaying consistent text. Example: String text = "Java"; System.out.println(text.toUpperCase()); // JAVA System.out.println(text.toLowerCase()); // java 4ïžâ£ equals() / equalsIgnoreCase() Definition: equals() compares two strings exactly, while equalsIgnoreCase() ignores case differences. ð¡ Why it matters: Used to compare user inputs like login IDs or names, case-sensitive or not. Example: String a = "Java"; String b = "java"; System.out.println(a.equals(b)); // false System.out.println(a.equalsIgnoreCase(b)); // true 5ïžâ£ contains() Definition: Checks if a string contains a certain sequence of characters. ð¡ Why it matters: Used to search or validate text (like checking if an email contains â@â). Example: String email = "rakshitha@gmail.com"; System.out.println(email.contains("@gmail.com")); // true Awesome ð Here are the next 5 common String methods in Java â explained simply with definition, why it matters, and example ð 6ïžâ£ substring() Definition: Extracts a part of the string between given start and end indexes. ð¡ Why it matters: Used to get a specific portion of text, like extracting username from an email. Example: String word = "JavaDeveloper"; System.out.println(word.substring(0, 4)); // Output: Java 7ïžâ£ replace() Definition: Replaces all occurrences of a character or substring with another value. ð¡ Why it matters: Useful for correcting text, filtering data, or formatting user input. Example: String text = "I love Java"; System.out.println(text.replace("Java", "Python")); // Output: I love Python 8ïžâ£ split() Definition: Splits a string into multiple parts based on a given delimiter and returns an array. ð¡ Why it matters: Used to break text into pieces, such as splitting CSV data or words in a sentence. Example: String data = "apple,banana,grape"; String[] fruits = data.split(","); System.out.println(fruits[1]); // Output: banana 9ïžâ£ trim() Definition: Removes all leading and trailing spaces from a string. ð¡ Why it matters: Essential for cleaning user input before saving or comparing values. Example: String name = " Rakshitha "; System.out.println(name.trim()); // Output: Rakshitha #Java #CoreJava #JavaProgramming #LearnJava #JavaDeveloper
To view or add a comment, sign in
-
ð ðšð»ð±ð²ð¿ððð®ð»ð±ð¶ð»ðŽ ððµð² ðð®ðð® ðð¶ðð ðð»ðð²ð¿ð³ð®ð°ð² â ð§ðµð² ðð²ð®ð¿ð ðŒð³ ð¢ð¿ð±ð²ð¿ð²ð± ððŒð¹ð¹ð²ð°ðð¶ðŒð»ð In Javaâs ððŒð¹ð¹ð²ð°ðð¶ðŒð» ðð¿ð®ðºð²ððŒð¿ðž, the List interface represents an ordered, index-based collection that allows duplicate elements. Itâs like your digital to-do list â you can add, remove, or access any task by its position. ðð²ð ð¶ðºðœð¹ð²ðºð²ð»ðð®ðð¶ðŒð»ð: ðð¿ð¿ð®ððð¶ðð â ð¥ðºð¯ð¢ð®ðªð€ ð¢ð³ð³ð¢ðºðŽ, ðšð³ðŠð¢ðµ ð§ð°ð³ ð§ð¢ðŽðµ ð³ð¢ð¯ð¥ð°ð® ð¢ð€ð€ðŠðŽðŽ ðð¶ð»ðžð²ð±ðð¶ðð â ð±ðŠð³ð§ðŠð€ðµ ð§ð°ð³ ð§ð³ðŠð²ð¶ðŠð¯ðµ ðªð¯ðŽðŠð³ðµðªð°ð¯ðŽ ð¢ð¯ð¥ ð¥ðŠððŠðµðªð°ð¯ðŽ ð©ð²ð°ððŒð¿ â ððŠðšð¢ð€ðº ðµð©ð³ðŠð¢ð¥-ðŽð¢ð§ðŠ ð·ðŠð³ðŽðªð°ð¯ (ð¯ð°ðµ ð€ð°ð®ð®ð°ð¯ððº ð¶ðŽðŠð¥ ðµð°ð¥ð¢ðº) ðŠðð®ð°ðž â ð€ðð¢ðŽðŽðªð€ ðððð ð¥ð¢ðµð¢ ðŽðµð³ð¶ð€ðµð¶ð³ðŠ ð£ð¶ðªððµ ð°ð¯ ððŠð€ðµð°ð³ Each serves a specific purpose depending on whether you value speed, memory efficiency, or thread safety. ðð ð®ðºðœð¹ð² ððŒð±ð² import java.util.*; public class ListExamples {   public static void main(String[] args) {     // ðð¿ð¿ð®ððð¶ðð ðð ð®ðºðœð¹ð²     List<String> arrayList = new ArrayList<>();     arrayList.add("Java");     arrayList.add("Python");     arrayList.add("C++");     arrayList.add("Python"); // duplicates allowed     System.out.println("ArrayList: " + arrayList);     // ðð¶ð»ðžð²ð±ðð¶ðð ðð ð®ðºðœð¹ð²     List<String> linkedList = new LinkedList<>();     linkedList.add("Spring");     linkedList.add("Hibernate");     linkedList.addFirst("Java EE");     System.out.println("LinkedList: " + linkedList);     // ð©ð²ð°ððŒð¿ ðð ð®ðºðœð¹ð²     Vector<Integer> vector = new Vector<>();     vector.add(10);     vector.add(20);     vector.add(30);     System.out.println("Vector: " + vector);     // ðŠðð®ð°ðž ðð ð®ðºðœð¹ð²     Stack<String> stack = new Stack<>();     stack.push("Apple");     stack.push("Banana");     stack.push("Cherry");     System.out.println("Stack before pop: " + stack);     stack.pop();     System.out.println("Stack after pop: " + stack);   } } ð¢ðððœðð: ðð³ð³ð¢ðºððªðŽðµ: [ðð¢ð·ð¢, ððºðµð©ð°ð¯, ð++, ððºðµð©ð°ð¯] ððªð¯ð¬ðŠð¥ððªðŽðµ: [ðð¢ð·ð¢ ðð, ðð±ð³ðªð¯ðš, ððªð£ðŠð³ð¯ð¢ðµðŠ] ððŠð€ðµð°ð³: [10, 20, 30] ððµð¢ð€ð¬ ð£ðŠð§ð°ð³ðŠ ð±ð°ð±: [ðð±ð±ððŠ, ðð¢ð¯ð¢ð¯ð¢, ðð©ðŠð³ð³ðº] ððµð¢ð€ð¬ ð¢ð§ðµðŠð³ ð±ð°ð±: [ðð±ð±ððŠ, ðð¢ð¯ð¢ð¯ð¢] ð¡ In real-world applications, Lists manage user records, logs, orders, and much more. Choosing the right implementation can make a big difference in performance. #Java #OOP #CollectionFramework #ArrayList #LinkedList #Stack #Vector #JavaDeveloper
To view or add a comment, sign in
-
In Java, when we want to work with a unique set of data, say String, the Set data structure comes readily to mind. Thereâs one subtle thing about the Set data structure that if care is not taken, might lead you to begin to debug an inexistent issue. One subtle thing thatâs quick to forget about HashSet is that the order of insertion isnât guaranteed. I was left chasing my tail recently only to remember the nature of HashSet in Java. Say we did the below: Set<String> names = Set.of(âPromiseâ, âOberoroâ, âAkeniâ); If you: System.out.println(names); A couple of times, you would get different outcomes not consistent in the way you added the data. Same as using a HashSet and adding data to it. In my case, I wanted to use the Set in the order in which the data were inserted but while debugging, I would be seeing the last inserted data first ð. I thought someone was jinxing me until I remembered that orderliness isnât guaranteed in Set. Oops ð¬ poor me! If you want orderliness and uniqueness then go for LinkedHashSet. Set<String> names = new LinkedHashSet<>(); names.add(âPromiseâ); names.add(âOberoroâ); names.add(âAkeniâ); This way, the order of insertion will always be guaranteed and you donât have to be fooling around like I did. But if order of insertion isnât important to you then you can use HashSet without issues. The fact that the HashSet isnât ordered is not a weakness, itâs a design decision made to optimize for speed, which makes insertion, deletion, and look up much faster than its counterparts(LinkedHashset and Treeset) as those would have the overheads of maintaining additional data structure. Itâs also worth noting that HashSet under the hood uses Hash table, thatâs how itâs able to achieve uniqueness. LinkedHashSet uses hash table + linked list. TreeSet uses Red-Black tree to ensure data are sorted in natural or specified order. Ever had the experience of debugging something that when you eventually figured it out, made you want to punch yourself in the face? Kindly share letâs learn from you ð #softwareengineering #programming #coding
To view or add a comment, sign in
-
-
In Java, there are several ways to create and run threads, Spring Boot also have @Async annotation to run method code as thread. 1. Extending the Thread class You can create a subclass of Thread and override the run() method. â Example: class MyThread extends Thread { @Override public void run() { System.out.println("Thread running " + Thread.currentThread().getName()); } } public class Main { public static void main(String[] args) { MyThread t1 = new MyThread(); t1.start(); } } ð§© 2. Implementing the Runnable interface â Example: class MyRunnable implements Runnable { @Override public void run() { System.out.println("Thread running using Runnable interface: " + Thread.currentThread().getName()); } } public class Main { public static void main(String[] args) { Thread t1 = new Thread(new MyRunnable()); t1.start(); } } ð¢ Why preferred: Allows you to extend another class (since Java supports only single inheritance). â¡ 3. Using Anonymous Class You can create and start a thread in one line using an anonymous inner class. â Example: public class Main { public static void main(String[] args) { Thread t1 = new Thread(new Runnable() { @Override public void run() { System.out.println("Thread running using Anonymous class"); } }); t1.start(); } } ð¡ 4. Using Lambda Expression (Java 8+) â Example: public class Main { public static void main(String[] args) { Thread t1 = new Thread(() -> { System.out.println("Thread running using Lambda expression"); }); t1.start(); } } âïž 5. Using ExecutorService (Thread Pool) For multiple or managed threads, use an Executor Service. â Example: import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Main { public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(2); executor.submit(() -> System.out.println("Thread 1 using ExecutorService")); executor.submit(() -> System.out.println("Thread 2 using ExecutorService")); executor.shutdown(); } } ð¢ Advantages: Reuses threads (avoids overhead of creating new threads repeatedly) Supports async tasks and better error handling ð§ 6. Using Callable and Future (for return values) Callable is like Runnable, but can return a value and throw exceptions. â Example: import java.util.concurrent.*; public class Main { public static void main(String[] args) throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); Callable<String> task = () -> { return "Result from thread: " + Thread.currentThread().getName(); }; Future<String> future = executor.submit(task); System.out.println(future.get()); executor.shutdown(); } }
To view or add a comment, sign in
-
ððð¯ð ðððŠðšð«ð² ððð§ðð ððŠðð§ð: ððððð€, ðððð© ðð§ð ððð«ððð ð ððšð¥ð¥ðððð¢ðšð§ Memory is fundamental for Java applications. To handle data effectively, Java divides its memory into two main areas: ð¡âð ð ð¡ððð and ð¡âð âððð. Each plays a specific role in storing and managing data, impacting both performance.  1. ðŠðð®ð°ðž ð ð²ðºðŒð¿ð The stack is a special area of memory used for temporary data and method calls. Every time a method is called in Java, the JVM creates a stack frame to hold the methodâs local variables, parameters and references to objects stored in the heap.  ðŸððð ðð ðð ðððð ? ðžFor storing primitive types ðžFor storing references to objects in the heap  ðŸððð ðð ðððððð ðð ððð ððððð? ðžLocal variables ðžMethod parameters ðžReturn addresses ðžReferences to heap objects  ð¬ðððððð: ðð¢ðððð ðððð ð ðð¡ððððžð¥ððððð {    ðð¢ðððð ð ð¡ðð¡ðð ð£ððð ðððð(ðð¡ðððð[] ðððð ) {        ððð¡ ð = 10;          // ð ð¡ðððð ðð ð ð¡ððð        ððð¡ ð = 20;          // ð ð¡ðððð ðð ð ð¡ððð        ððð¡ ð ð¢ð = ð + ð;     // ð ð¡ðððð ðð ð ð¡ððð        ððŠð ð¡ðð.ðð¢ð¡.ððððð¡ðð(ð ð¢ð);    } } ð²ðð ðððððð: ðžStack memory is fast, working in LIFO (Last In, First Out) order. ðžData is temporary â once the method finishes, the stack frame is removed automatically. ðžStack size is limited, so too many method calls can cause a StackOverflowError.  2. ðð²ð®ðœ ð ð²ðºðŒð¿ð  While the stack stores temporary data and method calls, the heap is where Java objects and instance variables live. Every time you create a new object using the new keyword, Java allocates space for it in the heap.  ð¬ðððððð: ðððð ðð ðððð ðð = ððð€ ðððð ðð("ðœðâð"); // ðððððð¡ ð ð¡ðððð ðð âððð Here, the variable person is stored on the stack, while the actual Person object resides in the heap. Heap memory is slower because managing dynamic memory is more complex, but Garbage Collector automatically frees unreferenced objects.  ð²ðð ðððððð: ðžHeap stores objects and instance variables ðžData can live longer than the method that created it  ðð®ð¿ð¯ð®ðŽð² ððŒð¹ð¹ð²ð°ððŒð¿ In Java, the Garbage Collector (GC) automatically removes objects in the heap that are no longer referenced. This means you donât have to manually free memory. ð²ðð ðððððð: ðžFrees memory for unused objects ðžRuns in background, letting developers focus on code  In conclusion, having a clear understanding of Javaâs memory structure helps developers make better decisions when optimizing applications. ðâð ð ð¡ððð manages temporary data and method calls, while ð¡âð âððð stores objects and instance variables, managed automatically by the Garbage Collector. Understanding how these memory areas work helps developers write more stable and memory-safe programs.
To view or add a comment, sign in
-
-
Record class in Java A record in Java is a special kind of class introduced to reduce boilerplate code when you need an immutable data carriers. Automatically generates: private final fields A canonical constructor equals(), hashCode() toString() accessor methods (getters without get prefix) --- Example: Traditional Employee Class (Before Java 14) public class Employee { private int id; private String name; private double salary; public Employee(int id, String name, double salary) { this.id = id; this.name = name; this.salary = salary; } public int getId() { return id; } public String getName() { return name; } public double getSalary() { return salary; } @Override public String toString() { return "Employee{id=" + id + ", name='" + name + "', salary=" + salary + "}"; } @Override public boolean equals(Object o) { // } @Override public int hashCode() { // } } . Too much boilerplate (getters, constructor, toString, equals, hashCode). --- Example: Employee Record (After Java 16) public record Employee(int id, String name, double salary) { } Thatâs it! Java automatically generates: Constructor Getters (id(), name(), salary()) equals(), hashCode() toString() --- Example usage: public class Main { public static void main(String[] args) { Employee emp = new Employee(101, "Sreenu", 55000); System.out.println(emp.name()); // Output: Sreenu System.out.println(emp); // Output: Employee[id=101, name=Sreenu, salary=55000.0] } } --- Canonical Constructor (Full Constructor) Records provide a canonical constructor automatically, but you can define it manually if you need validation: public record Employee(int id, String name, double salary) { public Employee { if (salary < 0) throw new IllegalArgumentException("Salary must be positive"); } } --- Compact Constructor Example public record Employee(int id, String name, double salary) { public Employee { if (name == null || name.isBlank()) { throw new IllegalArgumentException("Name cannot be blank"); } } } -- Entity Example (JPA) Usually, JPA entities are mutable, so records are not recommended for entities that Hibernate modifies. But you can use them as read-only projections: public record EmployeeEntity(Long id, String name, Double salary) { } Or use a traditional entity and record DTO for response. Example: @Entity @Table(name = "employees") public class EmployeeEntity { @Id private Long id; private String name; private Double salary; // getters, setters, constructors } Then convert it into DTO using record: public record EmployeeDTO(Long id, String name, Double salary) { } EmployeeDTO dto = new EmployeeDTO(entity.getId(), entity.getName(), entity.getSalary());
To view or add a comment, sign in
-
âð» JAVA THREADS CHEAT SHEET ð¹ ð§ What is a Thread? ð The smallest unit of execution in a process. Each thread runs independently but shares memory & resources with others. ð§© Enables multitasking and parallel execution. ð¹ âïž What is a Process? ð An executing instance of a program. Each process has its own memory space and can run multiple threads. ð§µ Types of Threads ð€ 1ïžâ£ User Threads â Created by users or apps. â JVM waits for them before exit. ð¡ Example: Thread t = new Thread(() -> System.out.println("User Thread")); t.start(); ð» 2ïžâ£ Daemon Threads âïž Background threads (e.g., Garbage Collector). â JVM doesnât wait for them. ð¡ Example: Thread d = new Thread(() -> {}); d.setDaemon(true); d.start(); ð Creating Threads ðž Extending Thread: class MyThread extends Thread { public void run(){ System.out.println("Running..."); } } new MyThread().start(); ðž Implementing Runnable: new Thread(() -> System.out.println("Runnable running...")).start(); ð Thread Lifecycle ð§© NEW â RUNNABLE â RUNNING â WAITING/BLOCKED â TERMINATED ð¹ïž Common Thread Methods ð§© Method â¡ Use start() Start a thread run() Thread logic sleep(ms) Pause execution join() Wait for thread interrupt() Interrupt thread setDaemon(true) Make daemon thread ð Synchronization Prevents race conditions when multiple threads share data. synchronized void increment() { count++; } ð¬ Thread Communication Use wait(), notify(), and notifyAll() for coordination. ð§ Must be called inside a synchronized block. â¡ Executor Framework (Thread Pooling) Efficient thread reuse for better performance. ExecutorService ex = Executors.newFixedThreadPool(3); ex.submit(() -> System.out.println("Task executed")); ex.shutdown(); ð Pro Tips â Prefer Runnable / ExecutorService â Handle InterruptedException â Avoid deprecated methods (stop(), suspend()) â Use java.util.concurrent for safe multithreading ð¢ Boost Your Skills ð #Java #Threads #Multithreading #Concurrency #JavaDeveloper #JavaInterview #JavaCoding #JavaProgrammer #CodeNewbie #ProgrammingTips #DeveloperCommunity #CodingLife #LearnJava #JavaCheatSheet #ThreadPool #TechInterview #SoftwareEngineer #CodeWithMe #JavaExperts #BackendDeveloper #JavaLearning #JavaBasics #OOP #CodeDaily #CodingJourney #DevCommunity #JavaLovers #TechCareers #CodeSmarter #100DaysOfCode
To view or add a comment, sign in
-
-
ðŸ ð»ðð ð®ðððð ð±ððð ðºðððððððððððð ðŽðððððð aka âWhen your ðððð refuse to leave homeâ ð¬ ðºðððð ðºðððð Friday evening at Office a dev happily sends a User object from one microservice to another. All seems peacefulâŠuntil suddenly ðš ð£ðð¯ð.ð¢ðš.ððšðððð«ð¢ðð¥ð¢ð³ððð¥ððð±ððð©ðð¢ðšð§: ððšðŠ.ðŠð¢ðð«ðšð¬ðšðð.ðð©ð©.ðŠðšððð¥ð¬.ðð¬ðð« Thatâs the moment when coffee stopped helping, and debugging began. âð» ð§ ðŸðððâð ð¹ððððð ð®ðððð ð¶ð? #ððð«ð¢ðð¥ð¢ð³ððð¢ðšð§â Converting your Java object into bytes so it can travel (across a network, file, or queue). #ððð¬ðð«ð¢ðð¥ð¢ð³ððð¢ðšð§ â Rebuilding that object from bytes. ð°ð ððððð: Your object: âIâm heading to Azure Service Bus ð©ïžâ JVM: âHold on! Whereâs your Serializable passport? ðâ âïž ð»ðð ðªðððððð ð©ðð class ðð¬ðð«{ private String name; private String email; } When this travels across services ð£ Boom NotSerializableException â ð»ðð ð¹ððððð ð·ððð import java.io.Serializable; class User implements Serializable { ððððððð ðððððð ððððð ðððð ðððððððœðððððððŒð°ð« = 1ð³; private String name; private String email; } Now your POJO can safely journey through REST APIs, Kafka, or message queues like a pro. ð ð¿ ð©ðððð: ðºðððððð©ððð ð¹ð¬ðºð» Spring Boot uses Jackson under the hood for automatic ðððð (ð ð)ððððððððððððð. @ðððððð©ð©ð¢ð§ð ("/user") public ðð¬ðð« ð ðððð¬ðð«() { return new ðð¬ðð«("abc", "abc@gmail.com"); } ð±ðððððð ðððð ððð ððð ð±ðºð¶ðµ ððððð - ð©ðð ðððððð ðð ððð ððððð â ïž ð Circular references (bidirectional JPA relationships) ð Missing @ð±ðððð°ððððð for sensitive data ð Debugging Checklist â Verify if class implements Serializable ð Check nested objects for serialization support ð§© Ensure ðððððððœðððððððŒð°ð«Â is consistent after class changes ð Enable ðððððð.ððððððð.ððððððððððððð logs â¡ Use @ð±ðððð°ððððð smartly to avoid recursion ð§Ÿ ð©ððð ð·ðððððððð ðºðððððð âïž Implement ððð«ð¢ðð¥ð¢ð³ððð¥ð for persistent/transmittable objects âïž Always include a ð¬ðð«ð¢ðð¥ððð«ð¬ð¢ðšð§ððð âïž Prefer ðððð¬Â over Entities in APIs âïž Mark confidential fields as ðð«ðð§ð¬ð¢ðð§ð âïž Validate ðððð mapping via ððð£ðððððð©ð©ðð« ð¬ ðš ðžðððð ðððð ððð ð«ðð ð¹ððð âMy #ðððð refused to travel until I gave it a passport turns out that passport was #ððð«ð¢ðð¥ð¢ð³ððð¥ð!â ð #JavaDeveloper #BackendDeveloper #FullStackDeveloper #SoftwareEngineering #TechInterview #CodingInterview #InterviewPreparation #TechCareer #ProgrammerLife #ITJobs #SpringBoot #SpringFramework #JavaProgramming #CoreJava #AdvancedJava #Microservices #RESTAPI #SpringSecurity #JavaTips #JavaCommunity #Docker #Kubernetes #Containerization #DevOpsTools #CI_CD #TechInnovation Tushar Desai
To view or add a comment, sign in
-
Decoding Data: A Simple Guide to Java Data Types ð Understanding data types is foundational for writing effective and efficient Java code. They tell the compiler what kind of values a variable can hold and what operations can be performed on it. In Java, data types are broadly categorized into two groups: Primitive and Non-Primitive (Reference) types. Let's break them down! 1. Primitive Data Types (The Building Blocks) These are the most basic data types, directly supported by the language. They hold simple values and are always stored in memory where the variable is declared (on the stack). Numbers: byte, short, int, long: For whole numbers (integers) of increasing size. (int is the most commonly used!) float, double: For numbers with decimal points (floating-point numbers). (double is generally preferred for precision.) Characters: char: For single characters, like 'A', 'b', or '5'. Booleans: boolean: For true or false values. Essential for logic and control flow! 2. Non-Primitive Data Types (The References / Objects) Also known as "Reference Types," these are more complex. They don't store the actual values directly but rather references (memory addresses) to objects that store the data. They are created by the programmer or defined by Java. String: A sequence of characters (e.g., "Hello, World!"). While it looks like a primitive, String is actually a class in Java and thus a non-primitive type. Arrays: A collection of values of the same data type (e.g., int[] numbers = {1, 2, 3};). Classes & Interfaces: These are custom data types you define yourself (e.g., Car, Employee). They allow you to create complex objects that encapsulate data and behavior. Why does this matter? Choosing the right data type helps optimize memory usage, prevent errors, and ensures your program behaves as expected. For instance, using an int for an age makes more sense than a double. What data type do you find yourself using most often? Share your thoughts! #Java #Programming #DataTypes #SoftwareDevelopment #TechBasics #CodingTips #Developers
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