Headline: Cracking the Core Java Interview: 4 Concepts You Must Know 🔍 1. What is an Anonymous Class? It’s a local class without a name, declared and instantiated in a single expression. Use Cases: Perfect for event listeners in GUI apps (like ActionListener in Swing) or when you need a quick, one-off implementation of an interface/abstract class. 2. What is a Marker Interface? It’s an interface with no methods or fields. It signals metadata to the JVM or compiler. Examples: Serializable (marks class for conversion to byte stream) and Cloneable (marks class as eligible for Object.clone()). 3. How to Create an Immutable Class? Think of String or Wrapper classes. Follow these rules: • Declare the class final (or use private constructors). • Make all fields private and final. • No setter methods. • If holding a mutable object (like Date/Collection), return a defensive copy in the getter. 4. Can Static Methods Be Overridden? No. Static methods are hidden, not overridden. Overriding relies on runtime object type (polymorphism), but static methods are resolved at compile-time based on the reference type. --- Q1: Is the Runnable interface a Marker Interface? (Think about it!) A: No. Runnable declares the run() method, so it is a Functional Interface, not a Marker Interface. Q2: If you have an Immutable class containing a List, how do you protect it in the getter? A: Return Collections.unmodifiableList(this.list) to prevent the caller from adding/removing elements. Q3: In the code Parent p = new Child(); p.staticMethod(); whose static method gets called? A: Parent’s method. The method belongs to the class, not the object. 💬 Which of these concepts trips you up the most? Let me know in the comments! #Java #Programming #CodingInterview #SoftwareEngineering #TechTips #CoreJava
Java Interview Prep: Anonymous Classes, Marker Interfaces & Immutable Objects
More Relevant Posts
-
🚨 Java Interview Trap Can the 'main()' method be "overloaded" in Java? Most developers quickly answer No. The `main()` method is just another static method, so Java allows method overloading. Example: public class Test { public static void main(String[] args) { System.out.println("Original main"); main(10); } public static void main(int x) { System.out.println("Overloaded main with int: " + x); } } Output: Original main Overloaded main with int: 10 However, there is an important rule. The JVM only looks for one specific entry point: public static void main(String[] args) Or public static void main(String... args) So even though main() can be overloaded, the JVM will only start execution from the standard signature. Any other overloaded main() must be called manually from inside the program. Sometimes the most basic Java method still hides the best interview traps. #Java #JavaInterview #JVM #SoftwareEngineering #Developers #Programming
To view or add a comment, sign in
-
This was a question I was recently asked in an interview: Can we override the main() method in Java? The short answer is: No, the main() method cannot be overridden. Why? Method overriding happens when a subclass provides a new implementation of a non-static method from the parent class. However, the main() method in Java is declared as static: public static void main(String[] args) Static methods belong to the class, not to objects. Because of this, they are resolved at compile time, not at runtime. Since method overriding relies on runtime polymorphism, static methods — including main() — cannot be overridden. Instead, if a subclass defines another main() method with the same signature, it is simply method hiding, not overriding. Example: class Parent { public static void main(String[] args) { System.out.println("Parent main method"); } } class Child extends Parent { public static void main(String[] args) { System.out.println("Child main method"); } } Both classes have their own main() methods, but they are not overriding each other. The method that runs depends on which class you execute. #Java #InterviewQuestions #BackendDevelopment #Programming #SoftwareDevelopment
To view or add a comment, sign in
-
-
🚨 One Java Interview Question Many Developers Still Get Wrong equals() vs hashCode() Most developers know these methods exist in Java, but many don’t fully understand why they must work together. Let’s break it down 👇 🔹 equals() • Used to compare the logical equality of two objects • By default, it compares memory references, not values • We override it when we want to compare object content 🔹 hashCode() • Returns an integer hash value for the object • Used internally by HashMap, HashSet, and HashTable • Helps Java quickly locate objects in hash buckets ⚠️ Important Rule If two objects are equal using equals(), they must return the same hashCode(). Otherwise, collections like HashSet or HashMap may behave incorrectly. 💡 Example Issue You add two logically equal objects into a HashSet, but because their hashCode values are different, both get stored. Result? Duplicate objects inside a Set. ✅ Takeaway Whenever you override equals(), always override hashCode() as well. This small rule can prevent subtle and hard-to-debug issues in real applications. 💬 Have you ever faced a bug related to equals() and hashCode()? #Java #SoftwareDevelopment #Programming #JavaDeveloper #CodingInterview #BackendDevelopment
To view or add a comment, sign in
-
🚀 Day 26 – Core Java | Method Overloading, Command Line Arguments & Encapsulation Today’s session connected multiple powerful concepts that directly impact interview performance. 🔹 Method Overloading – Deep Understanding We revisited the 3 compiler rules: 1️⃣ Method Name 2️⃣ Number of Parameters 3️⃣ Type of Parameters If all three match → ❌ Duplicate Method Error If no exact match → ✅ Type Promotion If multiple matches possible → ❌ Ambiguity We also explored: ✔ How type promotion works internally ✔ Why ambiguity happens ✔ Real example: System.out.println() is overloaded ✔ Yes — even the main() method can be overloaded Important insight: JVM always executes public static void main(String[] args). 🔹 Command Line Arguments Understood how: javac Demo.java java Demo ABC 123 Arguments are stored in String[] args They are always stored as String type Accessed using args[index] Size is dynamic Also clarified common mistakes like: ArrayIndexOutOfBoundsException 🔹 Introduction to Object-Oriented Programming (OOPS) Started the most important phase of Java. OOPS = Object-Oriented Programming System Built on 4 Pillars: ✔ Encapsulation ✔ Inheritance ✔ Polymorphism ✔ Abstraction Every real-world application is built on these principles. 🔹 Encapsulation – First Pillar Encapsulation = Providing security to important data + Providing controlled access Implemented using: ✔ private → Security ✔ Setter → Set data ✔ Getter → Get data Real-world analogy: Just like a bank protects balance and allows access only through controlled operations. We implemented: Private instance variable Setter with validation Getter to retrieve value Security + Control = Proper Encapsulation 💡 Biggest Takeaway Syntax is easy. Understanding compiler behavior, JVM flow, and memory access control builds real developer confidence. From here onwards, we dive deep into OOPS. Consistency now = Confidence in interviews later 🚀 #Day26 #CoreJava #MethodOverloading #Encapsulation #OOPS #JavaInterview #DeveloperJourney
To view or add a comment, sign in
-
Today I focused on one of the most important topics in Java: Strings. Strings may look simple, but they are one of the most asked topics in interviews and heavily used in real-world applications. Here’s what I learned today 👇 🔹 1️⃣ What is a String? A String is a sequence of characters. It is a class, not a primitive type. It belongs to the java.lang package. 🔹 2️⃣ String Creation Methods ✔ Using String literal String s1 = "Java"; ✔ Using new keyword String s2 = new String("Java"); 🔹 3️⃣ String Constant Pool (SCP) Java stores string literals in a special memory area called the String Constant Pool to optimize memory usage. 🔹 4️⃣ == vs equals() One of the most important interview concepts: == → compares memory reference .equals() → compares content Always use .equals() for comparing strings. 🔹 5️⃣ Why Strings are Immutable? Strings cannot be changed after creation. Reasons: ✔ Security ✔ Thread safety ✔ Memory efficiency ✔ HashCode caching 🔹 6️⃣ String vs StringBuilder vs StringBuffer String → Immutable StringBuilder → Mutable & Fast StringBuffer → Mutable & Thread-safe For frequent modifications, StringBuilder is preferred. #Day3 #Java #LearningJourney #PlacementsPreparation #DSA #Programming #ComputerScience #JavaDeveloper
To view or add a comment, sign in
-
🚀 Java Core Concepts – Interview Questions & Answers 📌 Question: What is the purpose of a default constructor? A constructor is a special method used to initialize objects when they are created. A default constructor: ✔ Does not take any parameters ✔ Is automatically provided by the compiler if no constructor is defined ✔ Initializes instance variables with default values 🔹 What does it do? 👉 The compiler provides a default constructor. 👉 Instance variables get default values (0, null, false, etc.). 🔹 Important Points: ✔ If you define any constructor, the compiler will NOT create a default constructor automatically. ✔ A default constructor can also be explicitly written. ✔ It is mainly used for object initialization with default state. 💡 Interview Tip: Default constructor ≠ No-argument constructor (though both look similar). A no-arg constructor is explicitly written by the programmer. 👉 Follow Ashok IT School for daily Java interview questions 👉 Comment “JAVA” for more concepts 👉For Java Course Details Visit : https://lnkd.in/gwBnvJPR . #Java #CoreJava #JavaInterviewQuestions #OOPS #Constructors #Programming #CodingInterview #AshokIT
To view or add a comment, sign in
-
-
Revisiting core Java interview concepts often reveals interesting edge cases. Here’s one worth thinking about. What will be the output of the following Java code? class A { static void test() { System.out.println("A"); } } class B extends A { static void test() { System.out.println("B"); } } A a = new B(); a.test(); How would you approach this? Share your reasoning in the comments. #Java #OOPs #Polymorphism #JavaInterview #Coding #Programming #SoftwareTesting
To view or add a comment, sign in
-
🚀 Java Backend Interview Series – Question #44 Q44. What is the difference between HashSet and TreeSet in Java? Both HashSet and TreeSet are part of the Java Set interface, meaning: ✔ They do not allow duplicate elements ✔ They are commonly used when you need unique data However, they behave very differently in terms of ordering, performance, and internal implementation. Let’s break it down 👇 🔹 1️⃣ HashSet HashSet stores elements using a hash table. Example: Set<Integer> set = new HashSet<>(); set.add(30); set.add(10); set.add(20); System.out.println(set); 📌 Possible Output: [20, 10, 30] Key characteristics: ❌ No ordering guarantee ⚡ Very fast operations Average O(1) time complexity for add, remove, contains Allows one null element Best used when performance matters and ordering is not required. 🔹 2️⃣ TreeSet TreeSet stores elements using a Red-Black Tree (self-balancing binary search tree). Example: Set<Integer> set = new TreeSet<>(); set.add(30); set.add(10); set.add(20); System.out.println(set); 📌 Output: [10, 20, 30] Key characteristics: ✔ Elements are automatically sorted Uses natural ordering or custom Comparator Time complexity O(log n) ❌ Does NOT allow null values Best used when sorted data is required. 🔹 Real-world Example Use HashSet when: ✔ Removing duplicates from a large dataset ✔ Fast lookup is required Use TreeSet when: ✔ You need sorted elements ✔ You want operations like first(), last(), ceiling(), floor() 🎯 Interview Tip If an interviewer asks: 👉 “Which one is faster: HashSet or TreeSet?” The correct answer is: HashSet is faster, but TreeSet provides sorted data. 💬 Follow-up Interview Question How does TreeSet maintain sorting internally, and what happens if you insert objects that do not implement Comparable? #Java #JavaCollections #HashSet #TreeSet #JavaDeveloper #BackendDevelopment #CodingInterview #TechInterview #SoftwareEngineering #SpringBoot #Microservices #Programming #DeveloperCommunity #CodingTips #CleanCode #DataStructures
To view or add a comment, sign in
-
-
🚨 Java Interview Trap 2 Why is "Vector" rarely used in modern Java? Many developers quickly answer: “Because it’s outdated.” But the real reason is more interesting 👇 Vector was introduced in JDK 1.0, even before the Collections Framework existed. It behaves like a dynamic array and internally stores elements using an array. Some key facts: • Default capacity = 10 • Capacity usually doubles when full • All methods are synchronized • This makes Vector thread-safe by default Example: import java.util.Vector; public class Test { public static void main(String[] args) { Vector<Integer> numbers = new Vector<>(); numbers.add(10); numbers.add(20); numbers.add(30); System.out.println(numbers); } } Because every method is synchronized, multiple threads can safely modify a Vector. But there is a trade-off. Synchronization introduces performance overhead, especially in single-threaded applications. That’s why most modern Java applications prefer: • ArrayList • Collections.synchronizedList() • CopyOnWriteArrayList But here is the real interview question 👇 When the internal array inside a Vector becomes full, Java creates a new array with double the size and copies all elements into it. What do you think happens to the old array? 1️⃣ It stays in memory 2️⃣ It gets reused 3️⃣ It becomes eligible for GC Drop the correct answer in the comments 👇 Sometimes the oldest Java classes still hide the best interview traps. #Java #JavaInterview #Collections #JVM #SoftwareEngineering #Developers #Programming
To view or add a comment, sign in
-
Top 10 Most Asked Java Interview Questions 1. What is the difference between HashMap and ConcurrentHashMap? HashMap is not thread-safe and can cause data inconsistency in concurrent environments. ConcurrentHashMap uses fine-grained locking and CAS operations to allow safe concurrent reads and writes. 2. What is the difference between final, finally, and finalize? final → keyword used for variables, methods, and classes to restrict modification. finally → block used in exception handling to execute cleanup code. finalize → method used by GC before object collection (deprecated and rarely used). 3. What happens when hashCode() and equals() are not implemented properly? If equal objects produce different hashCodes, collections like HashMap behave incorrectly. This leads to duplicate keys and degraded lookup performance. 4. What is the difference between ArrayList and LinkedList? ArrayList uses a dynamic array and provides fast random access. LinkedList uses a doubly linked structure and is efficient for insertions and deletions. 5. What is the difference between Thread and Runnable? Thread is a class that represents a thread of execution. Runnable is an interface used to define the task that a thread executes. Using Runnable improves flexibility because it separates the task from thread management. 6. What causes memory leaks in Java? Common causes include: - Static collections holding references - Unclosed resources - ThreadLocal misuse - Listeners not removed Heap dumps and tools like MAT help identify leaks. 7. What is the difference between synchronized and Lock? synchronized is simpler and managed by JVM. Lock provides advanced features like tryLock(), fairness policies, and interruptible locks. 8. What is the difference between checked and unchecked exceptions? Checked exceptions must be handled at compile time. Unchecked exceptions occur at runtime and usually indicate programming errors. 9. What is the difference between fail-fast and fail-safe iterators? Fail-fast iterators throw ConcurrentModificationException if the collection is modified during iteration. Fail-safe iterators operate on a copy of the collection. 10. What is the JVM and what are its main components? JVM is the runtime that executes Java bytecode. Main components include: - Heap - Stack - Method Area - Garbage Collector - JIT Compiler #Java #JavaInterview #BackendEngineering #SpringBoot #CodingInterview #SoftwareEngineering
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