Static Block vs Instance Block in Java Static Block: - Runs once per class - Executes when the class is loaded into memory - Used for static initialization Instance Block: - Runs every time an object is created - Executes before the constructor - Used for common object setup Execution Order (IMPORTANT): 1. Static variables 2. Static blocks 3. Instance variables 4. Instance blocks 5. Constructor Example: class A { static { System.out.println("Static Block"); } { System.out.println("Instance Block"); } A() { System.out.println("Constructor"); } public static void main(String[] args) { new A(); new A(); } } Output: Static Block Instance Block Constructor Instance Block Constructor What Interviewers Are Testing: - Not syntax - But understanding of: - Class loading - Object creation lifecycle - Execution flow Connect me - https://lnkd.in/ghA7B-Mr #Java #SDET #InterviewPrep #OOP
Java Static vs Instance Block Execution Order
More Relevant Posts
-
🚀 Java Streams Interview Question Given a list of integers, remove duplicates and return a sorted list using Stream API. import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(5, 3, 8, 1, 3, 5, 9, 2, 8); List<Integer> sortedUniqueNumbers = numbers.stream() .distinct() .sorted() .collect(Collectors.toList()); System.out.println(sortedUniqueNumbers); } } Output: [1, 2, 3, 5, 8, 9] 🔹 distinct() removes duplicate elements 🔹 sorted() arranges the elements in ascending order 🔹 collect(Collectors.toList()) converts the stream back to a list #Java #JavaStreams #CodingInterview #Programming #Developers #SoftwareEngineering #BackendDevelopment
To view or add a comment, sign in
-
⚡ map vs flatMap in Java (Stream API) Definition: map() → Transforms each element 1:1 flatMap() → Transforms and flattens nested structures 🤔 Why use? 1. map() - When output is a single value per input - Simple transformations 2. flatMap() - When each element produces multiple values (collections/streams) - Avoid nested structures like List<List<T>> 💻 Example List<List<Integer>> list = Arrays.asList( Arrays.asList(1, 2), Arrays.asList(3, 4), Arrays.asList(5, 6) ); // map() → creates nested structure List<Stream<Integer>> mapResult = list.stream() .map(inner -> inner.stream()) .collect(Collectors.toList()); // flatMap() → flattens into single stream List<Integer> flatMapResult = list.stream() .flatMap(inner -> inner.stream()) .collect(Collectors.toList()); 🔄 Flow map() List<List> → Stream<List> → Stream<Stream> flatMap() List<List> → Stream<List> → Stream 🧠 Rule of Thumb 👉 If your transformation returns a single value → use map() 👉 If it returns a collection/stream → use flatMap() 👉 If you are preparing for Java backend interviews, connect & follow - I share short, practical backend concepts regularly. #Java #Backend #Streams #Java8 #CodingInterview #InterviewPrep #SoftwareEngineering
To view or add a comment, sign in
-
-
💡 Java Interview Question How do you find the common elements from three lists in Java? Here’s a simple example: ✅ Two approaches: Using retainAll() with Set Using Java 8 Streams public class CommonElementFrom3List { public static void main(String[] args){ List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5); List<Integer> list2 = Arrays.asList(3, 4, 5, 6, 7); List<Integer> list3 = Arrays.asList(5, 6, 7, 8, 3); Set<Integer> common = new HashSet<>(list1); common.retainAll(list2); common.retainAll(list3); System.out.println(common); List<Integer> list = list1.stream() .filter(list2::contains) .filter(list3::contains) .distinct() .collect(Collectors.toList()); System.out.println(list); } } 📌 Output: [3, 5] ❓ Question for you: Which approach would you prefer in a real-world scenario and why? Also, how would you handle duplicate elements efficiently? #Java #CodingInterview #JavaDeveloper #Programming #TechLearning
To view or add a comment, sign in
-
Today I deep-dived into one of the most important Core Java interview topics: **String Internals** 🔥 Here are some key learnings: ✅ **String Pool (SCP)** Java stores string literals in a special pool to reuse objects and save memory. ```java String a = "Java"; String b = "Java"; ``` Both references point to the same pooled object. ✅ **Heap vs Pool** ```java String s = new String("Java"); ``` This creates a separate heap object, even if `"Java"` already exists in the pool. ✅ **equals() vs ==** * `==` checks reference * `equals()` checks content ✅ **Compile-time vs Runtime Concatenation** ```java "Ja" + "va" // compile-time → pooled a + "va" // runtime → new object ``` ✅ **intern() Method** Returns the pooled reference of a string. ```java String s = new String("Java").intern(); ``` ✅ **Why String is Immutable?** Because it enables: * Security * Thread safety * String Pool reuse * Stable hashCode for HashMap keys The more I learn Java internals, the more I realize interviews are less about syntax and more about understanding what happens behind the scenes. #Java #CoreJava #Programming #SoftwareEngineering #InterviewPreparation #Developers #Coding #JVM #LearningJourney
To view or add a comment, sign in
-
-
🚀 Java Streams Interview Gem: Find Duplicate Numbers in a List Working with collections is common, but identifying duplicates efficiently is a must-have skill for any Java developer 💡 Here’s how you can find duplicate numbers using Java Streams 👇 🔹 Approach: We use a Set to track elements and filter duplicates while streaming the list. 🔹 Code: import java.util.*; import java.util.stream.*; public class FindDuplicates { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 2, 5, 6, 3, 7, 1); Set<Integer> seen = new HashSet<>(); Set<Integer> duplicates = numbers.stream() .filter(n -> !seen.add(n)) .collect(Collectors.toSet()); System.out.println("Duplicate Numbers: " + duplicates); } } 🔹 Output: Duplicate Numbers: [1, 2, 3] 🔹 How it works? ✔ seen.add(n) returns false if the element is already present ✔ We filter those elements → duplicates ✔ Collect them into a Set to avoid repeated duplicates 💥 Alternative (Using Grouping): 🔥 Mastering Streams = Cleaner + More Functional Code #Java #JavaStreams #CodingInterview #Developers #Programming #Tech #100DaysOfCode
To view or add a comment, sign in
-
Day 9 Java Practice: Find the First Non-Repeated Character in a String While practicing Java, I worked on a classic string problem: 👉 Find the first non-repeated character in a given string. For example, in the string "swiss", the first character that does not repeat is 'w'. To solve this, I used a LinkedHashMap to store character counts while preserving insertion order. Then I iterated through the map to find the first character with count = 1. ================================================== // Online Java Compiler // Use this editor to write, compile and run your Java code online import java.util.*; class Main { public static void main(String[] args) { String s="swiss"; char[] words=s.toCharArray(); Map<Character,Integer>map=new LinkedHashMap<Character,Integer>(); for(char word:words) { map.put(word,map.getOrDefault(word,0)+1); } for(Map.Entry<Character,Integer>entry:map.entrySet()) { if(entry.getValue()==1) { System.out.println("First non-repeated character in the string is:"+entry.getKey()); break; } } } } Output:First non-repeated character in the string is:w This was a good exercise to understand: Character frequency counting Importance of insertion order using LinkedHashMap String traversal logic #AutomationTestEngineer #Selenium #Java #CodingPractice #ProblemSolving
To view or add a comment, sign in
-
-
🔀 𝐂𝐨𝐧𝐜𝐮𝐫𝐫𝐞𝐧𝐭𝐌𝐨𝐝𝐢𝐟𝐢𝐜𝐚𝐭𝐢𝐨𝐧𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧 𝙞𝙣 𝙅𝙖𝙫𝙖 Why does it happen? This is one exception many developers face while working with collections 𝐖𝐡𝐚𝐭 𝐢𝐬 𝐂𝐨𝐧𝐜𝐮𝐫𝐫𝐞𝐧𝐭𝐌𝐨𝐝𝐢𝐟𝐢𝐜𝐚𝐭𝐢𝐨𝐧𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧? ➡️ It occurs when we modify a collection while iterating over it 📃 Example 𝐢𝐦𝐩𝐨𝐫𝐭 𝐣𝐚𝐯𝐚.𝐮𝐭𝐢𝐥.*; 𝐩𝐮𝐛𝐥𝐢𝐜 𝐜𝐥𝐚𝐬𝐬 𝐃𝐞𝐦𝐨 { 𝐩𝐮𝐛𝐥𝐢𝐜 𝐬𝐭𝐚𝐭𝐢𝐜 𝐯𝐨𝐢𝐝 𝐦𝐚𝐢𝐧(𝐒𝐭𝐫𝐢𝐧𝐠[] 𝐚𝐫𝐠𝐬) { 𝐋𝐢𝐬𝐭<𝐈𝐧𝐭𝐞𝐠𝐞𝐫> 𝐥𝐢𝐬𝐭 = 𝐧𝐞𝐰 𝐀𝐫𝐫𝐚𝐲𝐋𝐢𝐬𝐭<>(); 𝐥𝐢𝐬𝐭.𝐚𝐝𝐝(𝟏); 𝐥𝐢𝐬𝐭.𝐚𝐝𝐝(𝟐); 𝐥𝐢𝐬𝐭.𝐚𝐝𝐝(𝟑); 𝐟𝐨𝐫 (𝐈𝐧𝐭𝐞𝐠𝐞𝐫 𝐢 : 𝐥𝐢𝐬𝐭) { 𝐢𝐟 (𝐢 == 𝟐) { 𝐥𝐢𝐬𝐭.𝐫𝐞𝐦𝐨𝐯𝐞(𝐢); // 𝐜𝐚𝐮𝐬𝐞𝐬 𝐞𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧 } } } } ⚠️ 𝐖𝐡𝐲 𝐝𝐨𝐞𝐬 𝐭𝐡𝐢𝐬 𝐡𝐚𝐩𝐩𝐞𝐧? Internally, Java collections use an Iterator When we modify the collection directly: ❌ Structure changes ❌ Iterator gets confused Throws ➡️ 𝐂𝐨𝐧𝐜𝐮𝐫𝐫𝐞𝐧𝐭𝐌𝐨𝐝𝐢𝐟𝐢𝐜𝐚𝐭𝐢𝐨𝐧𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧 Ways to Fix ➡️ Use Iterator 𝐈𝐭𝐞𝐫𝐚𝐭𝐨𝐫<𝐈𝐧𝐭𝐞𝐠𝐞𝐫> 𝐢𝐭 = 𝐥𝐢𝐬𝐭.𝐢𝐭𝐞𝐫𝐚𝐭𝐨𝐫(); 𝐰𝐡𝐢𝐥𝐞 (𝐢𝐭.𝐡𝐚𝐬𝐍𝐞𝐱𝐭()) { 𝐢𝐟 (𝐢𝐭.𝐧𝐞𝐱𝐭() == 𝟐) { 𝐢𝐭.𝐫𝐞𝐦𝐨𝐯𝐞(); // 𝐬𝐚𝐟𝐞 } } ➡️ Use removeIf() (Java 8) list.removeIf(i -> i == 2); ▪️Always avoid modifying a collection directly during iteration ▪️Use safe methods provided by Java (use iterator) Have you ever faced this exception in your project? 🤔 How did you fix it? #Java #JavaDeveloper #JavaBackend #Programming #TechJourney #LearnBySharing #JavaConcepts #Collections #InterviewPrep #Developers
To view or add a comment, sign in
-
Interesting Java Interview Question Recently, an interviewer asked a very logical question: Why does Hashtable not allow null key or null value in Java? At first it sounds simple, but the logic behind it is interesting. In Hashtable, when we retrieve a value using get(key), the method returns null in two situations: 1. The key does not exist in the table 2. The key exists but its value is null If Hashtable allowed null values, the system would not be able to distinguish between these two cases. This ambiguity could create logical issues, especially since Hashtable is a synchronized (thread safe) collection. To avoid this confusion, the designers of Java decided that Hashtable will not allow null keys or null values. Example: import java.util.Hashtable; public class Demo { public static void main(String[] args) { Hashtable<String,String> table = new Hashtable<>(); table.put("A","Java"); // valid table.put("B",null); // throws NullPointerException } } In contrast, HashMap allows one null key and multiple null values, because it handles key existence checks differently. Interview questions like this really test how deeply we understand Java Collections internally, not just how to use them. #Java #JavaInterview #JavaCollections #Hashtable #HashMap #Learning #javaJob
To view or add a comment, sign in
-
☕ Java Interview Question 📌 Why can’t we create a generic array in Java? In Java, generic arrays are restricted because arrays and generics handle type information differently. 🔹 Key Reason: ✔ Arrays are Reified • Arrays store and check their element type at runtime ✔ Generics use Type Erasure • Generic type information is removed during compilation ✔ Type Safety Conflict • Runtime cannot verify the actual generic type inside an array 🔹 What Problem Can Occur? • It may allow invalid assignments at runtime • Can lead to ArrayStoreException or unsafe behavior 🔹 Example: • new T[10] is not allowed because T is unknown at runtime 💡 In Short: Java prevents generic array creation to maintain type safety between compile-time generics and runtime array checks. 👉For Java Course Details Visit : https://lnkd.in/gwBnvJPR . #Java #JavaInterview #Generics #TypeErasure #Programming #InterviewPreparation #CoreJava#ashokit
To view or add a comment, sign in
-
-
🧠 Java Interview Question 👉 How to find duplicate characters in a String? Example: Input: "programming" Output: g, r, m Simple approach using HashMap: import java.util.HashMap; public class DuplicateCharacter { public static void main(String[] args) { String str = "programming"; HashMap<Character, Integer> map = new HashMap<>(); for (char c : str.toCharArray()) { map.put(c, map.getOrDefault(c, 0) + 1); } for (char c : map.keySet()) { if (map.get(c) > 1) { System.out.println(c); } } } } 💡 Logic: Count frequency of each character and print duplicates. 👉 Have you solved this in a different way? #Java #SpringBoot #Coding #InterviewQuestions #BackendDeveloper
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