Day 4 One of the questions from my recent interview was to reverse each word in a string. It’s a small problem, but it really makes you think about string manipulation and iteration. Simple problem, but good test of core concepts ================================================= // 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="Hello world from java language"; String [] words=s.split(" "); String revString=""; for(String w:words) { String reverseWord=""; for(int i=w.length()-1; i>=0;i--) { reverseWord=reverseWord+w.charAt(i); } revString=revString+reverseWord+" "; } System.out.println(revString); } } Output :olleH dlrow morf avaj egaugnal #Java #InterviewQuestion #CodingPractice #Learning #Developers
Reverse String Java Interview Question
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 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
-
A simple Java interview question 👇 class Main { public static void main(String[] args) { String name = "Hello"; String b = new String("Hello"); String c = name; String d = b; System.out.println(name == b); System.out.println(name == c); } } I was asked this in an interview and it’s a perfect example of how fundamentals matter more than complexity. Most people expect both outputs to be true. But the actual result is: false true 💡 Why? Because in Java: 🔹 "Hello" is stored in the String Pool (optimized memory) 🔹 new String("Hello") creates a new object in Heap 🔹 c = name → same reference 🔹 d = b → same reference ⚡ The key insight: == compares memory reference, not content 👉 name == b → false (different objects) 👉 name == c → true (same object) If you actually want to compare values: name.equals(b); // true 📌 What this question really tests: Not syntax. Not memorization. But your understanding of how Java handles memory. #Java #CodingInterview #SoftwareEngineering #Programming #Developers #TechCareers
To view or add a comment, sign in
-
💡 Java Interview Question – Immutable Strings Trap What will be the output? String s = "Java"; s.replace("J", "K"); System.out.println(s); 🤔 Options: A) Kava B) Java C) Compilation Error D) Runtime Exception --- ✅ Correct Answer: B) Java --- 🔍 Explanation: In Java, String is immutable. That means once a String object is created, it cannot be modified. 👉 The "replace()" method does not change the original string, it returns a new modified string. But here’s the catch 👇 s.replace("J", "K"); We are not assigning the result back to "s", so the original value remains unchanged. --- 💡 Correct way to modify: s = s.replace("J", "K"); System.out.println(s); // Output: Kava --- 🚀 Key Takeaway: Always remember: 👉 Strings in Java are immutable → Reassignment is required for changes --- #Java #JavaInterview #Coding #BackendDevelopment #Programming #InterviewPrep
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 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
-
🚀 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
-
🚀 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
To view or add a comment, sign in
-
Java interview question on Memory Leaks — here's everything you need to know! Had a great technical interview recently where Memory Leaks came up as a deep-dive topic. Here's a concise breakdown that I think every Java developer should know 🔍 What is a Memory Leak in Java? A memory leak happens when objects are no longer needed by the application, but the Garbage Collector (GC) cannot reclaim them — because references still exist. The JVM keeps them in heap, and over time, this causes OutOfMemoryError. ⚠️ Common Causes 1. Static fields holding object references 2. Unclosed resources (streams, connections, sessions) 3. Listeners / callbacks never removed 4. Inner classes holding implicit reference to outer class 5. ThreadLocal variables not cleaned up 6. Caches without eviction policies 🛠️ How to Detect It 1. JVisualVM / JConsole — monitor heap usage over time 2. Eclipse MAT (Memory Analyzer Tool) — analyze heap dumps 3. YourKit / JProfiler — commercial profilers, powerful for production 4. verbose:gc JVM flag — observe GC behavior 5. Heap dumps with jmap -dump:live,format=b,file=heap.hprof <pid> ✅ How to Fix / Prevent It 1. Use WeakReference / SoftReference for caches 2. Always close resources with try-with-resources 3. Remove listeners when done 4. Avoid unnecessary static references 5. Use tools like Caffeine / Guava Cache with TTL/max-size 6. Review ThreadLocal.remove() usage in thread pools Memory leaks are silent killers in production. If you're preparing for Java interviews — bookmark this. Drop a comment if you've faced memory leak issues in production. Let's learn together! 🙌 #Java #JavaDeveloper #MemoryLeak #JVM #PerformanceTuning #JavaInterview #SoftwareEngineering #Programming #TechInterview #BackendDevelopment #ProductionIssue #Interview #MemoryLeaks #Spring
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
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