🚀 Can you find the first non-repeating character in a string? Here’s a simple Java approach 👇 String str = "aabbcd"; for(int i = 0; i < str.length(); i++) { boolean unique = true; for(int j = 0; j < str.length(); j++) { if(i != j && str.charAt(i) == str.charAt(j)) { unique = false; break; } } if(unique) { System.out.println(str.charAt(i)); break; } } 💡 Output: c 🔍 How it works: For each character, we check if it appears anywhere else in the string If it appears → not unique ❌ If it does NOT appear → first non-repeating character ✅ 👉 Time Complexity: O(n²) 💭 Interview Insight: This question is commonly asked to test your understanding of: ✔ Strings ✔ Nested loops ✔ Logic building 📌 Bonus: Can you optimize this to O(n) using HashMap? 👀 Drop your approach in comments 👇 #Java #Coding #DSA #InterviewPrep #Developers #100DaysOfCode
Find First Non-Repeating Character in Java String
More Relevant Posts
-
🔥 Day 8: equals() vs == in Java (Very Important Interview Topic) This is one of the most commonly asked Java interview questions — and also one of the most misunderstood! 👇 🔹 == (Double Equals) Compares memory/reference location Checks if two objects point to the same memory String a = new String("Java"); String b = new String("Java"); System.out.println(a == b); // false ❌ 🔹 equals() Method Compares actual content (values) Defined inside Object class (can be overridden) String a = new String("Java"); String b = new String("Java"); System.out.println(a.equals(b)); // true ✅ 🔹 String Special Case (String Pool) String x = "Hello"; String y = "Hello"; System.out.println(x == y); // true ✅ 👉 Because both refer to same object in String Pool 💡 Pro Tip: Always use equals() for comparing object values — especially Strings! 📌 Final Thought: "== checks if objects are the same, equals() checks if values are the same." #Java #Programming #Coding #JavaDeveloper #InterviewPrep #Tech #Learning #Day8 #JavaBasics
To view or add a comment, sign in
-
-
🚀 Java Basic That Many Ignore: What is String[] args in main()? 🤔 We write this every day: public static void main(String[] args) { System.out.println("Hello"); } 👉 But what exactly is args? 💡 args = Command Line Arguments It is an array of Strings passed when running your program 👉 Example: public class Test { public static void main(String[] args) { System.out.println(args[0]); } } Run this: java Test Hello 👉 Output: Hello 🤯 Important Points: args is just a variable name (you can change it) It is always an array of String It can be empty (no arguments passed) 🔥 Fun Fact: public static void main(String[] xyz) 👉 This also works! 😄 ⚠️ Be careful: System.out.println(args[0]); ❌ If no argument → ArrayIndexOutOfBoundsException 💡 Safe way: if (args.length > 0) { System.out.println(args[0]); } Small concept… but important for interviews & real-world usage 💪 #Java #Programming #Coding #JavaDeveloper #InterviewPrep #Developers
To view or add a comment, sign in
-
🚀 Java Interview Trap: Why "finally" Can Hide Exceptions 🤯 This is a dangerous one that many developers miss Example: public class Test { public static void main(String[] args) { try { throw new RuntimeException("Error in try"); } finally { throw new RuntimeException("Error in finally"); } } } 👉 Output: Exception in thread "main" java.lang.RuntimeException: Error in finally 🤔Where did the original exception go? 💡 What’s happening? - Exception thrown in try ❌ - finally block executes - New exception in finally overrides the original 👉 Original exception is LOST 😱 🔥 Why this is dangerous? - You lose actual root cause - Debugging becomes very hard - Production issues become confusing ✅ Better Approach: try { throw new RuntimeException("Error in try"); } catch (Exception e) { throw e; // preserve original } finally { System.out.println("Cleanup done"); } ⚠️ Interview Twist: try { return 10; } finally { throw new RuntimeException("Oops"); } 👉 Method will NOT return 10 ❌ 👉 Exception will be thrown instead 😳 💥 Golden Rule: ❌ Never throw exceptions from finally ❌ Avoid return in finally ✅ Use it only for cleanup 🎯 Pro Tip: Use try-with-resources instead of complex finally blocks #Java #JavaInterview #CodingInterview #Developers #Programming #TechTips
To view or add a comment, sign in
-
🚀 LinkedHashMap = Built-in LRU Cache in Java If you’ve ever implemented an LRU Cache in interviews, this is your shortcut 👇 What is it? LinkedHashMap maintains insertion order (or access order) using a doubly linked list + hash table. With a small tweak, it behaves exactly like an LRU Cache. Why use it? • No need to manually manage DLL + HashMap • O(1) get & put operations • Clean and interview-friendly implementation How it works (LRU mode) Set accessOrder = true → recently accessed items move to the end Example 👇 import java.util.*; class LRUCache<K, V> extends LinkedHashMap<K, V> { private final int capacity; public LRUCache(int capacity) { super(capacity, 0.75f, true); // accessOrder = true this.capacity = capacity; } @Override protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return size() > capacity; // remove least recently used } } Usage 👇 LRUCache<Integer, String> cache = new LRUCache<>(3); cache.put(1, "A"); cache.put(2, "B"); cache.put(3, "C"); cache.get(1); // access → 1 becomes recent cache.put(4, "D"); // removes key 2 (LRU) Flow 🧠 1️⃣ Insert → goes to end 2️⃣ Access → moves to end 3️⃣ Capacity full → remove from start (LRU) Result Efficient LRU cache in just ~10 lines of code ✅ Rule of Thumb 👉 If interviewer asks LRU → First say DLL + HashMap, then optimize using LinkedHashMap 👉 If you are preparing for Java backend interviews, connect & follow - I share short, practical backend concepts regularly. #Java #DSA #BackendDevelopment #SystemDesign #CodingInterview
To view or add a comment, sign in
-
-
Interview Question: What happens inside the JVM when you create a String in Java? When a String is created in Java, the JVM handles memory allocation and storage differently depending on how the String is defined. 🔹 Case 1: Using String Literal String s1 = "Hello"; String s2 = "Hello"; 👉 Here’s what happens: JVM checks the String Constant Pool If "Hello" already exists → it reuses the same object No new object is created for s2 👉 Both s1 and s2 point to the same memory location 🔹 Case 2: Using new Keyword String s3 = new String("Hello"); 👉 Here’s what happens: JVM creates a new object in heap memory It also ensures "Hello" exists in the String Pool So now there are two objects: One in Heap One in String Pool 🔹 Case 3: Using intern() String s4 = new String("Hello").intern(); 👉 What happens: JVM returns the reference from the String Pool Avoids duplicate objects Main Points To Remember: String literals are stored in the String Constant Pool new String() always creates a new object in heap The String Pool optimizes memory by reusing values intern() ensures reference from the pool #Java #JVM #InterviewQuestions #Programming #BackendDevelopment
To view or add a comment, sign in
-
-
🌟 Hello Shining Stars!!! 🙏 💡 Java Type Promotion Hierarchy (Must-Know for Developers) Understanding type promotion is key to avoiding subtle bugs in Java 👇 🔼 Hierarchy (Widening Conversion): byte → short → int → long → float → double char → int → long → float → double ⚡ Golden Rules: 👉 byte, short, and char are automatically promoted to int in expressions 👉 Result = largest data type in the expression 👉 ✅ Promotion (widening) is automatic 👉 ❌ De-promotion (narrowing) is NOT automatic — requires explicit casting 🚨 Edge Case Examples (Tricky but Important): byte a = 10; byte b = 20; byte c = a + b; // ❌ Compilation Error // a + b becomes int → cannot store in byte without casting int x = 130; byte b = (byte) x; // ⚠️ Explicit cast (data loss) // Output will be -126 due to overflow char ch = 'A'; System.out.println(ch + 1); // Output: 66 // 'A' → 65 → promoted to int 🧠 Method vs Constructor Promotion (Important Interview Point): void test(int x) { System.out.println("int method"); } void test(double x) { System.out.println("double method"); } test(10); // Calls int method (exact match preferred over promotion) 👉 In methods, Java allows type promotion during overload resolution 👉 But constructors don’t “prefer” promotion the same way — exact match is prioritized, and ambiguous cases can lead to compilation errors 🎯 Takeaway: Java silently promotes smaller types, but it never automatically demotes them — and overload resolution can surprise you! #Java #Programming #Developers #Coding #InterviewPrep #TechTips 👍 Like | 🔁 Repost | 🔄 Share | 💬 Comment | 🔔 Follow | 🤝 Connect to grow together
To view or add a comment, sign in
-
🔥 Day 14: Immutable Class (How String is Immutable in Java) One of the most important concepts in Java — especially for interviews 👇 🔹 What is an Immutable Class? 👉 Definition: An immutable class is a class whose objects cannot be changed once created. 🔹 Example: String String s = "Hello"; s.concat(" World"); System.out.println(s); // Hello (not changed) 👉 Why Because String is immutable 🔹 How String Becomes Immutable? ✔ String class is final (cannot be extended) ✔ Internal data is private & final ✔ No methods modify the original object ✔ Any change creates a new object 🔹 Behind the Scenes String s1 = "Hello"; String s2 = s1.concat(" World"); System.out.println(s1); // Hello System.out.println(s2); // Hello World 👉 s1 remains unchanged 👉 s2 is a new object 🔹 Why Immutability is Important? ✔ Thread-safe (no synchronization needed) ✔ Security (safe for sharing data) ✔ Caching (String Pool optimization) ✔ Reliable & predictable behavior 🔹 How to Create Your Own Immutable Class? ✔ Make class final ✔ Make fields private final ✔ No setters ✔ Initialize via constructor only ✔ Return copies of mutable objects 🔹 Real-Life Analogy 📦 Like a sealed box — once created, you cannot change what’s inside. 💡 Pro Tip: Use immutable objects for better performance and safety in multi-threaded applications. 📌 Final Thought: "Immutability = Safety + Simplicity + Performance" #Java #Immutable #String #Programming #JavaDeveloper #Coding #InterviewPrep #Day14
To view or add a comment, sign in
-
-
𝗝𝗮𝘃𝗮 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗧𝗿𝗮𝗽: 𝗜𝗻𝘁𝗲𝗴𝗲𝗿 𝗖𝗮𝗰𝗵𝗶𝗻𝗴 & 𝗪𝗿𝗮𝗽𝗽𝗲𝗿 𝗚𝗼𝘁𝗰𝗵𝗮𝘀 𝗘𝘅𝗽𝗹𝗮𝗶𝗻𝗲𝗱! Consider this simple code: class Main { public static void main(String[] args) { Integer a = 128; Integer b = 128; System.out.println(a == b); // ? System.out.println(a.equals(b)); // ? } } 🔍 Output: false true 🤔 Why does this happen? Java internally caches Integer objects in the range -128 to 127. ✅ Within range → same object → == is true ❌ Outside range → new objects → == is false 👉 == compares references (memory address) 👉 .equals() compares actual values 🔥 What about other wrapper classes? ✔ Cached Wrappers: Integer → -128 to 127 Byte → all values cached Short → -128 to 127 Long → -128 to 127 Character → 0 to 127 Boolean → only true & false (always cached) 👉 Example: Integer x = 100; Integer y = 100; System.out.println(x == y); // true ✅ ❗ NOT Cached: Float Double 👉 Example: Float f1 = 10.0f; Float f2 = 10.0f; System.out.println(f1 == f2); // false ❌ Double d1 = 10.0; Double d2 = 10.0; System.out.println(d1 == d2); // false ❌ 💥 Why no caching for Float/Double? Extremely large range of values Precision & representation complexity Not memory-efficient to cache 📌 Golden Rule: 👉 Never use == for wrapper comparison 👉 Always use .equals() or unbox to primitive 🚀 Pro Tip: You can extend Integer cache using JVM option: -XX:AutoBoxCacheMax=<value> 🎯 Interview Insight: This is a classic trap to test: Java memory concepts Autoboxing & unboxing Object vs primitive understanding 💡 Bonus Tip: Be careful with null values when unboxing: Integer i = null; int j = i; // Throws NullPointerException ⚠️ #Java #Programming #InterviewPrep #JavaTips #Coding #Developers #TechCareers
To view or add a comment, sign in
-
📘 Follow me for daily Java, Spring Boot, SQL & System Design MCQs to crack MNC interviews 🚀 ✅ Correct Answer: C) [A, B, C] This question tests how LinkedHashSet behaves with duplicates and insertion order in the Java Collections Framework. Set<String> set = new LinkedHashSet<>(); set.add("A"); set.add("B"); set.add("C"); set.add("A"); System.out.println(set); 🧠 Key Rules of LinkedHashSet It implements the Set concept → no duplicate elements allowed. It maintains insertion order. If you try to add a duplicate, it is ignored silently (no error). ▶ Step-by-step Execution set.add("A"); → [A] set.add("B"); → [A, B] set.add("C"); → [A, B, C] set.add("A"); → Duplicate, ignored → [A, B, C] 📌 Final Output [A, B, C] #JavaMCQ #CodingMCQ #InterviewPreparation #MNCInterview #CodeAnalysis #ConceptClarity #JavaLearning #ServletJSP #JDBC #OracleDB #DeveloperMindset #PracticeCoding
To view or add a comment, sign in
-
-
🚀 Java Deep Dive: "try-with-resources" Closing Order (Real Example) 🔥 Most developers know it auto-closes resources… But the ORDER? That’s where interviews get tricky 😏 👉 Real-world example: import java.io.*; public class Main { public static void main(String[] args) throws Exception { try (FileInputStream fis = new FileInputStream("test.txt"); InputStreamReader isr = new InputStreamReader(fis); BufferedReader br = new BufferedReader(isr)) { System.out.println("Reading file..."); } } } 💡 Output: Reading file... (then resources close automatically) 👉 Actual closing order: BufferedReader InputStreamReader FileInputStream Why reverse order? Because Java follows LIFO (Last In, First Out) 👉 Last opened → First closed 🔥 Understand the chain: Open order: FileInputStream → InputStreamReader → BufferedReader Close order: BufferedReader → InputStreamReader → FileInputStream ⚠️ Interview Tip: Always remember dependency: - Outer resource depends on inner ones - So it must close FIRST 💬 One-liner to remember: “Resources open in sequence… but close in reverse.” #Java #JavaInterview #Coding #ExceptionHandling #IO #Programming #Developers #TechTips
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