☕ Java Core Concepts – Interview Question 📌 How is String creation using new() different from a literal? In Java, Strings can be created in two ways, and they behave differently in memory: 🔹 String Literal ("abc") • Stored in the String Pool (inside Heap) • JVM checks if the value already exists • If yes → returns reference of existing object • If no → creates a new object in the pool ✅ Memory efficient (reuses objects) 🔹 Using new Keyword (new String("abc")) • Always creates a new object in Heap memory • Does NOT reuse objects from String Pool ❌ Less memory efficient (creates duplicate objects) 🔹 Example: String s1 = "hello"; String s2 = "hello"; // reuses same object String s3 = new String("hello"); // new object in heap 🔹 Key Difference: ✔ Literal → Reuses existing objects (String Pool) ✔ new → Always creates a new object 💡 In Short: String literals save memory using the String Pool, while new always creates a fresh object, even if the value already exists. 👉For Java Course Details Visit : https://lnkd.in/gwBnvJPR . #Java #CoreJava #String #JavaInterview #Programming #Coding #TechSkills#Ashokit
Java String Creation: Literal vs new Keyword
More Relevant Posts
-
Interview Question: What is the Diamond Problem in Java? The Diamond Problem arises in languages that support multiple inheritance, where a class inherits from two classes that both derive from a common superclass. This creates ambiguity when both parent classes define the same method. The question becomes: which method should be used? Java avoids this issue by not supporting multiple inheritance with classes. However, with interfaces and default methods, a similar situation can occur. Example: interface A { default void show() { System.out.println("A"); } } interface B { default void show() { System.out.println("B"); } } class Test implements A, B { public static void main(String[] args){ Test t = new Test(); t.show(); // Compilation error! } } Since both interfaces provide the same method, Java forces the class to override it explicitly. Solution with Specific Interface Call: class Test implements A, B { public void show() { A.super.show(); // calling method from interface A B.super.show(); // calling method from interface B } } 👉 This way, we can explicitly choose or combine behavior from both interfaces. #Java #OOP #InterviewQuestions #BackendDevelopment #Programming
To view or add a comment, sign in
-
-
⏳ Day 13 – 1 Minute Java Clarity – String Immutability in Java Strings look simple… but there’s something powerful happening behind the scenes 📌 What is String Immutability? In Java, once a String object is created, it cannot be changed. 👉 Instead of modifying the existing string, Java creates a new object. 📌 Example: String str = "Hello"; str.concat(" World"); System.out.println(str); 👉 Output: Hello ❌ (not "Hello World") 💡 Why? Because concat() creates a new object, but we didn’t store it. ✔ Correct way: str = str.concat(" World"); System.out.println(str); // Hello World ✅ 💡 Real-time Example: Think of a username in a system: String username = "user123"; username.toUpperCase(); Even after calling toUpperCase(), the original value stays "user123" unless reassigned. 📌 Why Strings are Immutable? ✔ Security (used in passwords, URLs) ✔ Thread-safe (no synchronization issues) ✔ Performance optimization using String Pool ⚠️ Important: Too many string modifications? Use StringBuilder instead. 💡 Quick Summary ✔ Strings cannot be modified after creation ✔ Operations create new objects ✔ Always reassign if you want changes 🔹 Next Topic → Type casting in Java Have you ever faced issues because of String immutability? 👇 #Java #JavaProgramming #Strings #CoreJava #JavaDeveloper #BackendDeveloper #Coding #Programming #SoftwareEngineering #LearningInPublic #100DaysOfCode #ProgrammingTips #1MinuteJavaClarity
To view or add a comment, sign in
-
-
Day 9 of Java Series ☕💻 Today’s topic is BufferedReader — a powerful way to take fast input in Java 🚀 🧠 What is BufferedReader? BufferedReader is a class in Java used to read text efficiently from input streams (like keyboard or file). It reads data in chunks (buffer) instead of character-by-character → faster performance ⚡ ⚙️ Why Use BufferedReader? ✔ Faster than Scanner ✔ Efficient for large input ✔ Reduces I/O operations ✔ Used in competitive programming 🔗 How it Works? 👉 Works with InputStreamReader to convert bytes into characters System.in → InputStreamReader → BufferedReader 💻 Example Code: import java.io.*; public class Main { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter your name: "); String name = br.readLine(); System.out.println("Hello " + name); } } ⚡ Important Methods: readLine() → Reads full line read() → Reads single character close() → Closes stream ⚠️ Important Notes: Does NOT parse input automatically Must handle exceptions (IOException) Needs conversion for numbers 👉 Example: Java id="br2" Copy code int num = Integer.parseInt(br.readLine()); 🎯 Why Important? ✔ Used in interviews & CP ✔ Improves performance ✔ Important for backend & file handling 🚀 Pro Tip: Use BufferedReader + StringTokenizer for ultra-fast input in competitive programming 🔥 📢 Hashtags: #Java #BufferedReader #JavaSeries #Coding #Programming #Developers #LearnJava #Tech
To view or add a comment, sign in
-
-
Java Puzzle for Today What will be the output of this program? String a = "Java"; String b = "Java"; String c = new String("Java"); System.out.println(a == b); System.out.println(a == c); System.out.println(a.equals(c)); Take a moment and guess before scrolling. Most beginners think the output will be: true true true But the actual output is: true false true Why does this happen? Because Java stores string literals in a special memory area called the String Pool. So when we write: String a = "Java"; String b = "Java"; Both variables point to the same object in the String Pool. But when we write: String c = new String("Java"); Java creates a new object in heap memory, even if the value is the same. That’s why: - "a == b" → true (same object) - "a == c" → false (different objects) - "a.equals(c)" → true (same value) Lesson: Use "equals()" to compare values, not "==". Small Java details like this can save you from real bugs in production. #Java #Programming #JavaPuzzle #Coding #SoftwareDevelopment
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
-
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
-
-
Thread Life Cycle in Java 1. NEW (Thread Created) 👉 Meaning: Thread object is created, but not started yet. Example: Thread t = new Thread(() -> { System.out.println("Running"); }); 📌 State: t.getState(); // NEW 2. RUNNABLE (Ready + Running) 👉 Meaning: Thread is ready to run and may be executing. ⚠️ In Java: RUNNING is part of RUNNABLE OS decides when it runs Example: t.start(); // Goes to RUNNABLE 📌 State: RUNNABLE 3. BLOCKED (Waiting for Lock) 👉 Meaning: Thread is waiting to acquire monitor lock. Example: synchronized(obj) { // other thread holds lock } If lock busy → BLOCKED. 4. WAITING (Waiting Indefinitely) 👉 Meaning: Thread waits until another thread wakes it. Caused by: wait() join() park() Example: obj.wait(); // WAITING 5. TIMED_WAITING (Waiting for Time) 👉 Meaning: Thread waits for a fixed time. Caused by: sleep(1000) wait(1000) join(1000) Example: Thread.sleep(1000); // TIMED_WAITING 6. TERMINATED (Dead) 👉 Meaning: Thread finished execution. Example: run() ends → TERMINATED #Java #Multithreading #interview #sde #interviewpreparation #ThreadLifecycle
To view or add a comment, sign in
-
☕ Java Core Concepts – Interview Question 📌 What is a Constructor? In Java, a Constructor is a special method used to initialize objects when they are created. 🔹 Key Features: ✔ Called automatically when an object is created ✔ Name must be same as the class name ✔ No return type (not even void) ✔ Used to initialize instance variables ✔ Can be overloaded (multiple constructors with different parameters) 🔹 Types of Constructors: • Default Constructor – No parameters • Parameterized Constructor – Accepts arguments 🔹 Example: class Student { String name; // Constructor Student(String n) { name = n; } void display() { System.out.println(name); } public static void main(String[] args) { Student s = new Student("Tharun"); s.display(); } } 💡 In Short: A constructor is used to set up an object’s initial state at the time of creation. 👉For java Course Details Visit : https://lnkd.in/gwBnvJPR . #Java #CoreJava #Constructor #JavaInterview #Programming #Coding #TechSkills
To view or add a comment, sign in
-
-
🚫 Most Common Java OOP Mistake (Even in Interviews) Many developers expect this to print 20: class Shape { int x = 10; void draw() { System.out.println("Shape draw"); } } class Circle extends Shape { int x = 20; void draw() { System.out.println("Circle draw"); } } public class Test { public static void main(String[] args) { Shape s = new Circle(); System.out.println(s.x); // ❌ prints 10 s.draw(); // ✅ prints "Circle draw" } } Why this happens? 👉 Java treats variables and methods differently: Methods → runtime (object decides) Variables → compile time (reference decides) So: s.draw() → uses Circle (object type) s.x → uses Shape (reference type) Golden Rule 👉 “Methods are polymorphic, variables are not.” This tiny concept is one of the most common sources of confusion in OOP—and a favorite interview trap. #Java #OOP #Programming #CodingInterview #SoftwareDevelopment
To view or add a comment, sign in
-
Day 7 Java Logic: Count characters that are NOT next to whitespace While practicing Java, I tried an interesting logic problem: 👉 Count the number of characters in a string that are neither immediately before nor immediately after a whitespace. For example: "My name is Madhukar" We don’t count characters that touch a space on either side. Here’s the Java program I wrote: // Online Java Compiler // Use this editor to write, compile and run your Java code online class Main { public static void main(String[] args) { String s ="My name is Madhukar"; char [] charArray=s.toCharArray(); int count=0; for(int i=0 ;i<charArray.length;i++) { if(charArray[i]==' ') continue; boolean whiteSpacePresentAfterCharacter=(i<charArray.length-1 && charArray[i+1]==' '); boolean whiteSpacePresentBeforeCharacter=(i>0 && charArray[i-1]==' '); if(!whiteSpacePresentAfterCharacter && !whiteSpacePresentBeforeCharacter) { count++; } } System.out.println("Number of chacarters before and after whitespace:"+count); } } O/P:Number of chacarters before and after whitespace:10 #Java #CodingPractice #ProblemSolving #Programming
To view or add a comment, sign in
-
More from this author
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