Java Interview Question That Confuses Almost Everyone (Including Me) “Is Java pass by value or pass by reference?” Here’s the clarity I finally reached: Java is ALWAYS pass by value. No exceptions. But the confusion begins when we deal with objects. What actually happens with objects? When you pass an object to a method: Java passes a copy of the reference (address) Both references point to the same object in memory Two key scenarios: ✔ Modify object data → Changes are visible outside void modify(Test t) { t.x = 50; } Because both references point to the same object. ❌ Change the reference → No effect outside void change(Test t) { t = new Test(); t.x = 100; } Because now only the copied reference points to a new object. The mental model that clicked for me: Change object data → visible Change reference → no impact outside Final takeaway: Java is pass by value — but for objects, the value being passed is a reference. A huge thanks to PW Institute of Innovation and Syed Zabi Ulla sir for explaining this concept so thoroughly and clearly. #Java #SoftwareEngineering #Coding #ProgrammingConcepts #JavaDeveloper #TechInterviews#Java #Programming #SoftwareDevelopment #JavaDeveloper #CodingTips #Tech #BackendDevelopment #LearnToCode
Java Pass by Value or Reference Explained
More Relevant Posts
-
🚀 Java Backend Interview Series – Day 7 Think you know Java 8 well? Let’s go beyond basics 👇 ⚡ Java 8 Advanced (No Basics): 1️⃣ What is Spliterator and how is it used internally? 2️⃣ Difference between Iterator and Spliterator? 3️⃣ What are the different types of method references? 4️⃣ How does `map()` differ from `flatMap()` with real use cases? 5️⃣ What is Optional chaining and how does it prevent NullPointerException? 6️⃣ What is CompletableFuture and how is it different from Future? 7️⃣ How do you combine multiple CompletableFutures? 8️⃣ What is lazy evaluation in streams? 9️⃣ How do streams handle short-circuit operations? 🔟 What are the performance impacts of using streams vs loops? 💡 Java 8 isn’t about syntax—it’s about thinking in functional style 📌 Save this for revision 👇 Comment “NEXT” for Day 8 #Java #Java8 #Streams #FunctionalProgramming #BackendDevelopment #InterviewPrep #Developers #Coding
To view or add a comment, sign in
-
🚀 Java Puzzle: Why this prints "100" even after using "final"? 🤯 Looks like a bug… but it’s actually Java behavior 👇 👉 Example: final int[] arr = {1, 2, 3}; arr[0] = 100; System.out.println(arr[0]); // 100 😮 👉 Wait… "final" but still changing? 🤔 💡 Reality of "final": - "final" → reference cannot change - NOT → object data cannot change 👉 So: - ❌ "arr = new int[]{4,5,6}" → not allowed - ✅ "arr[0] = 100" → allowed --- 🔥 Now the REAL twist 😳 final StringBuilder sb = new StringBuilder("Java"); sb.append(" Developer"); System.out.println(sb); // Java Developer 😮 👉 Again changing despite "final" 🔥 Golden Rule: 👉 "final" means: - You cannot point to a new object - But you CAN modify the existing object 💡 Common misconception: 👉 Many think "final = constant" (NOT always true) 💬 Did you also think "final" makes everything immutable? #Java #JavaDeveloper #Programming #Coding #100DaysOfCode #TechTips #JavaTips #InterviewPrep #Developers #SoftwareEngineering
To view or add a comment, sign in
-
🚀 Comparable in Java — Why & When to Use It? Sorting objects in Java becomes simple when you understand Comparable. Let’s break it down 👇 🔹 What is Comparable? Comparable is used to define the natural (default) sorting order of objects within a class. 🔹 Why Use Comparable? ✔ To define a default sorting logic inside the class ✔ Makes sorting easy using "Collections.sort()" or "Arrays.sort()" ✔ Avoids writing external sorting logic again and again 🔹 When to Use Comparable? ✔ When objects have a natural order (like ID, age, name) ✔ When sorting is required frequently ✔ When you want a single standard sorting rule 🔹 Steps to Implement Comparable 1️⃣ Implement "Comparable<T>" in your class 2️⃣ Override "compareTo()" method 3️⃣ Define comparison logic (this vs other object) 4️⃣ Use "Collections.sort()" to sort objects 💡 Key Insight: «Comparable = Natural sorting (inside the class)» 🔥 Mastering this makes your code cleaner and interview-ready #Java #CoreJava #Comparable #Sorting #Collections #Programming #CodingInterview #Developers #SoftwareDevelopment #LearnJava 🚀
To view or add a comment, sign in
-
-
🚀 Java Interview Series – Day 25 What is the finally block in Java? The finally block is used to execute important code regardless of whether an exception occurs or not. It is always executed after the try and catch blocks (except in rare cases like JVM shutdown). 🔹 Where it fits: • try → code that may throw exception • catch → handles exception • finally → always executes Why is this important? ✔ Ensures resource cleanup ✔ Prevents resource leaks ✔ Guarantees execution of critical code 💡 Example: When working with: Database connections File streams Network sockets Even if an exception occurs, the finally block ensures resources are properly closed. ⚡ Key Insight: In modern Java, try-with-resources is often preferred as it automatically handles resource closing—but finally is still important to understand. 💬 Interview Tip: Always mention: “Executes always” Resource cleanup use cases Difference from try-with-resources Handling failures properly is what separates beginner code from production-ready systems. #Java #JavaDeveloper #ExceptionHandling #FinallyBlock #CleanCode #BackendDevelopment #SoftwareEngineering #TechInterview #CodingInterview #SystemDesign #Developers #LearningInPublic #CareerGrowth #IndiaJobs #USJobs #UKJobs #AustraliaJobs
To view or add a comment, sign in
-
-
Mastering the Foundation: The java.lang.Object Class in Java 🚀 Did you know that every class in Java—whether you define it or it’s pre-defined—inherits from the Object class? Residing in the java.lang package, the Object class is the ultimate superclass in the Java hierarchy. Understanding it is more than just theory; it’s essential for writing clean, robust, and efficient code. The Object class provides 11 important methods that every Java object possesses by default. While some are meant to be overridden to add specific behavior, others are marked as final for safety. Key Methods to Keep in Mind: toString(): Provides a string representation of the object. equals() & hashCode(): Essential for comparing objects and using them in hash-based collections (like HashMap). clone(): Used for creating exact copies of objects. finalize(): Called by the Garbage Collector before reclaiming memory. Multithreading Essentials: Methods like wait(), notify(), and notifyAll() play a critical role in synchronization and managing thread communication. Pro Tip: Interviewers love questions about Object class methods because they reveal your understanding of Java’s core architecture. Don't just memorize the list—understand why and how to override these methods correctly! #Java #SoftwareEngineering #BackendDevelopment #JavaDeveloper #ProgrammingFundamentals #TechCommunity #CodingInterview #Springboot
To view or add a comment, sign in
-
Most Java developers write multithreaded code every day. But most of us don't know what happens inside the JVM when two threads hit the same counter — and things get quiet. I've been preparing deeply for senior Java interviews and decided to document everything I learned about multithreading from scratch. Not just definitions — real internals. Here's what Module 02 covers: 🔹 Multithreading 🔹 Process vs. Program vs. Thread 🔹 Thread lifecycle (all 6 states — and why there's no RUNNING state) 🔹 Race conditions — why count++ is never safe 🔹 synchronized — object lock vs class lock (most devs miss this) 🔹 ReentrantLock — tryLock, fairness, reentrancy explained 🔹 ReadWriteLock — when to separate reads from writes 🔹 Deadlock, Livelock, Starvation — all three with code and fixes 🔹 wait() / notify() — the producer-consumer pattern the right way 🔹 volatile vs Atomic — visibility vs atomicity (not the same thing) 🔹 ABA problem — why CAS isn't always enough 🔹 ExecutorService + ThreadPoolExecutor internals 🔹 Callable, Future — handling results and exceptions from threads 🔹 CompletableFuture — full methods guide (thenApply, thenCombine, exceptionally…) 🔹 ThreadLocal — usage, and the memory leak trap in thread pools This is Part 03 of my Java Interview Prep series. Part 01 covered JVM Internals, and Part 02 covered OOPs Internals - Find the post link in the comments. More modules on Collections, Streams, Spring Boot, etc., are coming. If you're preparing for a senior Java role or want to understand what's really happening when your threads collide, finally, this is for you. #Java #Multithreading #JavaConcurrency #InterviewPrep #CoreJava #BackendDevelopment #JavaDeveloper #LearningInPublic
To view or add a comment, sign in
-
Java Concept Check — Answer Explained 💡 Yesterday I posted a question: Which combination of Java keywords cannot be used together while declaring a class? Options were: A) public static B) final abstract C) public final D) abstract class ✅ Correct Answer: B) final abstract Why? In Java: 🔹 abstract class - Cannot be instantiated (no direct object creation) - Must be extended by another class Example: abstract class A { } 🔹 final class - Cannot be extended by any other class - Object creation is allowed Example: final class B { } The contradiction If we combine them: final abstract class A { } We create a conflict: - "abstract" → class must be inherited - "final" → class cannot be inherited Because these two rules contradict each other, Java does not allow this combination, resulting in a compile-time error. Thanks to everyone who participated in the poll 👇 Did you get the correct answer? #Java #BackendDevelopment #JavaDeveloper #Programming
To view or add a comment, sign in
-
Most Java developers write code. Very few write good Java code🔥 Here are 10 Java tips every developer should know 👇 1. Prefer interfaces over implementation → Code to "List" not "ArrayList" 2. Use "StringBuilder" for string manipulation → Avoid creating unnecessary objects 3. Always override "equals()" and "hashCode()" together → Especially when using collections 4. Use "Optional" wisely → Avoid "NullPointerException", but don’t overuse it 5. Follow immutability where possible → Makes your code safer and thread-friendly 6. Use Streams, but don’t abuse them → Readability > fancy one-liners 7. Close resources properly → Use try-with-resources 8. Avoid hardcoding values → Use constants or config files 9. Understand JVM basics → Memory, Garbage Collection = performance impact 10. Write meaningful logs → Debugging becomes 10x easier Clean code isn't about writing more. It’s about writing smarter. Which one do you already follow? 👇 #Java #JavaDeveloper #SoftwareEngineering #BackendDevelopment #SpringBoot #CleanCode #Programming #Developers #TechTips #CodingLife
To view or add a comment, sign in
-
-
🔥 Day 15: Functional Interfaces & Lambda Expressions (Java) One of the core concepts behind modern Java (introduced in Java 8) — clean, concise, and powerful 👇 🔹 1. Functional Interface 👉 Definition: An interface that contains exactly one abstract method. ✔ Can have multiple default/static methods ✔ Annotated with @FunctionalInterface (optional but recommended) Examples: ✔ Runnable ✔ Callable ✔ Comparator 🔹 2. Lambda Expression 👉 Definition: A short way to implement a functional interface without creating a class. 🧠 Think of it as: “function without name” 🔹 Traditional Way vs Lambda 👉 Without Lambda: Runnable r = new Runnable() { public void run() { System.out.println("Hello Java"); } }; 👉 With Lambda: Runnable r = () -> System.out.println("Hello Java"); 🔹 Syntax (parameters) -> expression Examples: (int a, int b) -> a + b x -> x * x () -> System.out.println("Hi") 🔹 Why Use Lambda? ✔ Less boilerplate code ✔ Improves readability ✔ Enables functional programming ✔ Works perfectly with Streams 🔹 Built-in Functional Interfaces ✔ Predicate<T> → returns boolean ✔ Function<T, R> → transforms data ✔ Consumer<T> → performs action ✔ Supplier<T> → provides data 🔹 When to Use? ✔ When interface has one abstract method ✔ With collections & streams ✔ For cleaner and shorter code 💡 Pro Tip: Use lambda expressions with Streams to write powerful one-line operations 🚀 📌 Final Thought: "Write less code, do more work — that’s the power of Lambda." #Java #Lambda #FunctionalProgramming #Java8 #Programming #JavaDeveloper #Coding #InterviewPrep #Day15
To view or add a comment, sign in
-
-
🚀 Day 2 – Subtle Java Behavior That Can Surprise You Today I explored the difference between "==" and ".equals()" in Java — and it’s more important than it looks. String a = "hello"; String b = "hello"; System.out.println(a == b); // true System.out.println(a.equals(b)); // true Now this: String c = new String("hello"); System.out.println(a == c); // false System.out.println(a.equals(c)); // true 👉 "==" compares reference (memory location) 👉 ".equals()" compares actual content 💡 The catch? Because of the String Pool, sometimes "==" appears to work correctly… until it doesn’t. This small misunderstanding can lead to tricky bugs, especially while working with collections or APIs. ✔ Rule I’m following: Always use ".equals()" for value comparison unless you explicitly care about references. #Java #BackendDevelopment #JavaBasics #LearningInPublic
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