#Interview-146: Java - What is String Constant Pool? String Constant Pool in Java is a special memory area inside the heap where Java stores string literals. Whenever we create a string like: String s1 = "Hello"; String s2 = "Hello"; Java doesn’t create two separate objects. Instead, it checks the String Constant Pool, and if the value already exists, it reuses the same object. So here, both s1 and s2 actually point to the same memory location. It’s mainly for memory optimization. Since strings are widely used and are immutable in Java, reusing them saves memory and improves performance. Now compare this with using new: String s3 = new String("Hello"); In this case, Java creates a new object in heap memory, even if "Hello" already exists in the pool. So: • "Hello" → goes to String Pool • new String("Hello") → creates a separate object outside the pool Important concept: immutability - Strings in Java are immutable, which means once created, their value cannot be changed. That’s what makes pooling safe—because no one can modify the shared string. #interviewprep #interview #testing #qajobs #jobs #jobsearch #jobseekers #hiring #hiringnow #lookingforjob #manualtesting #testautomation #bdd #cucumber #testng #etltesting #performance #apitesting #softwaretesting #manualtester #qatester
Java String Constant Pool Optimization
More Relevant Posts
-
💡 Java Tip: Arrays.asList() vs List.of() — Not the Same! Many Java developers use Arrays.asList() and List.of() interchangeably, assuming both create immutable lists. 👉 That assumption can silently break your code. Here’s the actual difference: 🔹 Arrays.asList() ✅ Elements are mutable (set() works) ❌ Size is fixed (add() / remove() throws exception) 🔁 Backed by the original array ✅ Allows null List<Integer> list = Arrays.asList(1, 2, 3); list.set(0, 10); // ✅ works list.add(4); // ❌ UnsupportedOperationException ------------------------------- 🔹 List.of() (Java 9+) ❌ Completely immutable ❌ No add / remove / set ❌ Does NOT allow null List<Integer> list = List.of(1, 2, 3); list.set(0, 10); // ❌ UnsupportedOperationException ------------------------------ ✅ Best Practice (when you need mutability): List<Integer> list = new ArrayList<>(List.of(1,2,3,4,5)); This gives you: ✔ Initial elements ✔ Full mutability ✔ Dynamic capacity growth 📌 Key takeaway: Arrays.asList() → fixed-size but partially mutable List.of() → truly immutable Small distinctions like these make a big difference in production code, interviews, and debugging sessions. #Java #JavaCollections #CleanCode #BackendDevelopment #SoftwareEngineering #InterviewPrep #LearningEveryDay
To view or add a comment, sign in
-
🚀 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
-
Java Developer Interview (3–4 Years Experience) – Here’s a concise list of questions I was asked along with one-liner answers -- Java 17 Features LTS version with features like records, sealed classes, pattern matching, and improved performance. -- what changes done in Java 17 for GC -- Java 8 Features Introduced lambda, streams, functional interfaces, Optional, and new Date-Time API. -- Functional Interface An interface with exactly one abstract method, used for lambda expressions. -- Static Method Use Cases Used for utility methods, shared logic, and when no object state is required. -- Method Reference Shorthand for lambda expressions using :: to directly refer to methods. -- Ways to Create Thread Thread class, Runnable, Lambda, Callable + Future, CompletableFuture. -- CompletableFuture Used for asynchronous programming and combining independent tasks. -- Stream API (Intermediate vs Terminal) Intermediate → lazy transformations; Terminal → triggers execution and gives result. -- map vs flatMap map = one-to-one transformation; flatMap = one-to-many + flattening. -- Memory Issues in Java 8 Heap OOM, Metaspace OOM, memory leaks, GC overhead, stack overflow. -- YAML vs Properties YAML is hierarchical and readable; properties are flat key-value pairs. -- Externalized Configuration (Spring Boot) Store config outside code using properties, YAML, env variables, or command-line. -- Circuit Breaker Prevents cascading failures by stopping calls to failing services and using fallback. -- Orchestration vs Choreography Orchestration = central control; Choreography = event-driven decentralized flow. -- Transaction Propagation Defines how transactions behave when one method calls another (e.g., REQUIRED, REQUIRES_NEW). -- Merging Arrays (Java 8) Use Stream/CompletableFuture to combine arrays cleanly. #java #interviewexperience ##interviewexperience #springboot #backenddeveloper #careergrowth #experiencedhire #javadeveloper
To view or add a comment, sign in
-
This are 5 tricky questions than made me in my last interview for a java developer position. 😅 How many of these would you answer right on the spot? 1️⃣ String Pool Mania String s1 = "Java"; String s2 = "Java"; String s3 = new String("Java"); System.out.println(s1 == s2); System.out.println(s1 == s3); System.out.println(s1.equals(s3)); What is the output? 2️⃣ Why can't static methods be overriding and only hidden ? 3️⃣ What happens if two threads update the same key ? 4️⃣ Why does Java support multiple inheritance of type (interfaces) but not multiple inheritance of state (classes)? 5️⃣ Dependency Injection: Field vs. Constructor 🏗️ In a Spring Boot environment, why is Constructor Injection universally preferred over @Autowired on a field? Give me one reason that isn't "it's easier for unit testing." #Java #JavaDevelopment #JavaInterview #ProgrammingLife #BackendDeveloper #CodingQuiz #LearnToCode #JavaCommunity #TechInterview #ProgrammingTricks
To view or add a comment, sign in
-
#Interview-134: Java: Can we have a catch block without a try block, or a try block without a catch block? In Java, a catch block cannot exist without a try block – that is simply not allowed. The catch block is meant to handle exceptions thrown from the corresponding try, so without try, it has no purpose and won’t even compile. Now coming to the second part - can we have a try block without a catch? Yes, we can, but only if we use a finally block. So the valid combinations in Java are: 1. try + catch 2. try + catch + finally 3. try + finally 4.Just try alone (not allowed) Example of valid try without catch: try { int data = 10 / 0; } finally { System.out.println("This will always execute"); } Even though an exception occurs, the finally block will still execute. So - a catch block must always follow a try, but a try block can exist without a catch only if it is followed by a finally block. #interviewprep #interview #testing #qajobs #jobs #jobsearch #jobseekers #hiring #hiringnow #lookingforjob #manualtesting #testautomation #bdd #cucumber #testng #etltesting #performance #apitesting #softwaretesting #manualtester #qatester
To view or add a comment, sign in
-
🚀 Day 3 of Java Series 👉 Find common elements between two lists using Streams import java.util.*; import java.util.stream.*; public class CommonElementsExample { public static void main(String[] args) { List<Integer> list1 = List.of(10, 20, 30, 40, 50); List<Integer> list2 = List.of(30, 40, 60, 70); Set<Integer> set2 = new HashSet<>(list2); List<Integer> common = list1.stream() .filter(set2::contains) .toList(); System.out.println(common); // [30, 40] } } 💡 What’s happening here? ✔ Convert one list into a HashSet → O(1) lookup ✔ Stream through list1 ✔ Filter only elements present in list2 ✔ Collect result into a list ⚡ Key Insight: Using List.contains() leads to O(n²) complexity Using HashSet reduces it to O(n + m) 🧠 Interview Tip: Always optimize lookups using HashSet when dealing with search operations 📌 Output: [30, 40] ❓Can you think of a way to handle duplicates in both lists? #Java #Streams #CodingInterview #Developers #JavaDeveloper #Learning #Tech
To view or add a comment, sign in
-
This Java code looks fine… but crashes 👇 List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); for (String s : list) { if (s.equals("A")) { list.remove(s); } } 💥 Throws: "ConcurrentModificationException" Why? You can't modify a list while iterating using a for-each loop. ✅ Fix: Use "Iterator" Iterator<String> it = list.iterator(); while (it.hasNext()) { if (it.next().equals("A")) { it.remove(); } } Classic interview question 🔥 #Java #Collections #BugFix
To view or add a comment, sign in
-
🚀 Java Interview Series – Day 22 What is an Interface in Java? An interface in Java is a contract that defines what a class should do, but not how it should do it. It contains method declarations (by default public and abstract) that implementing classes must define. 🔹 Key characteristics: • Cannot have concrete method implementations (before Java 8) • Supports multiple inheritance • Helps achieve abstraction • Promotes loose coupling Why is this important? ✔ Enables flexible and scalable system design ✔ Allows multiple implementations of the same contract ✔ Makes code easier to test and maintain 💡 Example: A Payment interface can define a method pay(). Different classes like CreditCardPayment, UPIPayment, and NetBankingPayment implement it differently. ⚡ Key Insight: Modern Java (8+) allows: default methods (with implementation) static methods inside interfaces This makes interfaces more powerful than before. 💬 Interview Tip: Always mention: Interface = contract Multiple inheritance Real-world use case Java 8 enhancements Interfaces are at the heart of frameworks like Spring and are heavily used in building scalable and loosely coupled systems. #Java #JavaDeveloper #OOP #Interface #Abstraction #SoftwareEngineering #BackendDevelopment #CleanCode #TechInterview #CodingInterview #SystemDesign #Developers #LearningInPublic #CareerGrowth #IndiaJobs #USJobs #UKJobs #AustraliaJobs
To view or add a comment, sign in
-
-
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
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
-
More from this author
-
What is Agentic QA
Software Testing Studio | WhatsApp 91-6232667387 18h -
Interview #442: Postman - How do you manage different environments like QA, UAT, and Production?
Software Testing Studio | WhatsApp 91-6232667387 1d -
Interview #441: How do you compare API response data with database data?
Software Testing Studio | WhatsApp 91-6232667387 2d
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