Interview Question: What is Autoboxing and Unboxing in Java? Autoboxing and Unboxing are concepts in Java that handle the conversion between primitive data types and their corresponding wrapper classes. Autoboxing is the automatic conversion of a primitive type into its wrapper object. Unboxing is the reverse process, where a wrapper object is converted back into a primitive type. Example: int a = 10; // Autoboxing Integer obj = a; // Unboxing int b = obj; System.out.println(a + " " + obj + " " + b); 👉 Here, Java automatically converts: int → Integer (Autoboxing) Integer → int (Unboxing) Usage in Collections: import java.util.ArrayList; ArrayList<Integer> list = new ArrayList<>(); list.add(10); // Autoboxing int value = list.get(0); // Unboxing 👉 Collections store objects, so autoboxing makes it seamless to use primitives. ⚠️ Important Edge Case: Integer obj = null; int x = obj; // Throws NullPointerException 👉 During unboxing, if the wrapper object is null, it results in a runtime error. #Java #InterviewQuestions #Programming #BackendDevelopment #SoftwareEngineering
Mihir Kumar Shrestha’s Post
More Relevant Posts
-
💡 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
-
☕ Java Interview Question 📌 Why can’t we create a generic array in Java? In Java, generic arrays are restricted because arrays and generics handle type information differently. 🔹 Key Reason: ✔ Arrays are Reified • Arrays store and check their element type at runtime ✔ Generics use Type Erasure • Generic type information is removed during compilation ✔ Type Safety Conflict • Runtime cannot verify the actual generic type inside an array 🔹 What Problem Can Occur? • It may allow invalid assignments at runtime • Can lead to ArrayStoreException or unsafe behavior 🔹 Example: • new T[10] is not allowed because T is unknown at runtime 💡 In Short: Java prevents generic array creation to maintain type safety between compile-time generics and runtime array checks. 👉For Java Course Details Visit : https://lnkd.in/gwBnvJPR . #Java #JavaInterview #Generics #TypeErasure #Programming #InterviewPreparation #CoreJava#ashokit
To view or add a comment, sign in
-
-
🚀 Java Streams Interview Question Given a list of integers, remove duplicates and return a sorted list using Stream API. import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(5, 3, 8, 1, 3, 5, 9, 2, 8); List<Integer> sortedUniqueNumbers = numbers.stream() .distinct() .sorted() .collect(Collectors.toList()); System.out.println(sortedUniqueNumbers); } } Output: [1, 2, 3, 5, 8, 9] 🔹 distinct() removes duplicate elements 🔹 sorted() arranges the elements in ascending order 🔹 collect(Collectors.toList()) converts the stream back to a list #Java #JavaStreams #CodingInterview #Programming #Developers #SoftwareEngineering #BackendDevelopment
To view or add a comment, sign in
-
☕ Java Interview Question 📌 Explain the LinkedList class in Java In Java, LinkedList is a collection class that stores elements using a doubly linked list structure. 🔹 Key Features ✔ Maintains insertion order ✔ Allows duplicate elements ✔ Non-synchronized by default 🔹 Implementation ✔ Implements List and Deque interfaces ✔ Can be used as a list, queue, or stack 🔹 Performance ✔ Fast insertion and deletion in the middle ✔ Slower random access compared to ArrayList 🔹 Syntax • LinkedList<Type> list = new LinkedList<>(); 💡 In Short: LinkedList is best when frequent insertions and deletions are needed instead of fast indexing 🚀☕ 👉For JAVA Course Details Visit : https://lnkd.in/gwBnvJPR . #Java #LinkedList #JavaInterview #Collections #Programming #InterviewPreparation #TechSkills
To view or add a comment, sign in
-
-
🚀 Java Streams Interview Gem: Find Duplicate Numbers in a List Working with collections is common, but identifying duplicates efficiently is a must-have skill for any Java developer 💡 Here’s how you can find duplicate numbers using Java Streams 👇 🔹 Approach: We use a Set to track elements and filter duplicates while streaming the list. 🔹 Code: import java.util.*; import java.util.stream.*; public class FindDuplicates { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 2, 5, 6, 3, 7, 1); Set<Integer> seen = new HashSet<>(); Set<Integer> duplicates = numbers.stream() .filter(n -> !seen.add(n)) .collect(Collectors.toSet()); System.out.println("Duplicate Numbers: " + duplicates); } } 🔹 Output: Duplicate Numbers: [1, 2, 3] 🔹 How it works? ✔ seen.add(n) returns false if the element is already present ✔ We filter those elements → duplicates ✔ Collect them into a Set to avoid repeated duplicates 💥 Alternative (Using Grouping): 🔥 Mastering Streams = Cleaner + More Functional Code #Java #JavaStreams #CodingInterview #Developers #Programming #Tech #100DaysOfCode
To view or add a comment, sign in
-
Interview Question: What is Static Binding and Dynamic Binding in Java? Binding in Java refers to the process of linking a method call to its implementation. It is broadly classified into Static Binding and Dynamic Binding. 🔹 Static Binding (Also known as Early Binding / Compile-Time Binding) Static Binding occurs when the method call is resolved at compile time. It is used for: static methods final methods private methods method overloading class Test { static void show() { System.out.println("Static Binding"); } public static void main(String[] args) { Test obj = new Test(); obj.show(); } } 👉 Here, the method to be executed is determined at compile time, so it does not depend on the object. 🔹 Dynamic Binding (Also known as Late Binding / Runtime Binding) Dynamic Binding occurs when the method call is resolved at runtime. It is used in method overriding. class Parent { void show() { System.out.println("Parent method"); } } class Child extends Parent { void show() { System.out.println("Child method"); } } public class Test { public static void main(String[] args) { Parent obj = new Child(); obj.show(); } } 👉 Output: Child method Even though the reference is of type Parent, the method is executed based on the actual object type at runtime. #Java #OOP #InterviewQuestions #BackendDevelopment #Programming
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
-
🚀 Comparable vs Comparator in Java — Stop Confusing Them! If you're preparing for Java interviews or strengthening your core concepts, understanding the difference between Comparable and Comparator is a must. Let’s break it down simply 👇 --- 🔹 Comparable (Natural Ordering) - Used to define the default sorting logic of a class - Implemented inside the same class - Uses "compareTo()" method ✅ Example: class Student implements Comparable<Student> { int marks; public int compareTo(Student s) { return this.marks - s.marks; } } 👉 Here, sorting is based on marks by default --- 🔹 Comparator (Custom Ordering) - Used to define multiple sorting logics - Implemented in a separate class or lambda - Uses "compare()" method ✅ Example: Comparator<Student> sortByName = (s1, s2) -> s1.name.compareTo(s2.name); 👉 Now you can sort by name, age, or anything! --- ⚡ Key Differences Feature| Comparable| Comparator Package| java.lang| java.util Method| compareTo()| compare() Logic| Single (default)| Multiple (custom) Modification| Inside class| Outside class --- 💡 Pro Tip: Use Comparable when you have a natural sorting order Use Comparator when you need flexibility & multiple sorting options --- 🔥 Mastering these concepts not only helps in interviews but also improves how you design scalable Java applications. #Java #DSA #Programming #CodingInterview #JavaDeveloper #Learning #Tech
To view or add a comment, sign in
-
💥 Java Interview Question You Must Master! 👉 What is Object Cloning and how do you achieve it in Java? This is a core Java concept that tests your understanding of object memory, copying, and OOP principles 🔥 . 💡 1. What is Object Cloning? Object Cloning is the process of creating an exact copy of an existing object 👉 Instead of manually copying values, Java provides a built-in way to duplicate objects . ⚙️ 2. How to Achieve Object Cloning? To enable cloning in Java: ✔️ Implement Cloneable interface (marker interface) ✔️ Override the clone() method from Object class 👉 Basic syntax: protected Object clone() throws CloneNotSupportedException { return super.clone(); } . 🔍 3. What Happens Internally? ✔️ clone() performs field-to-field copying ✔️ Default behavior → Shallow Copy . ⚖️ 4. Types of Cloning (Very Important) 🔹 Shallow Copy ✔️ Copies object ❌ References are shared 👉 Changes in one object may affect the other 🔹 Deep Copy ✔️ Copies object + nested objects ✔️ Fully independent 👉 Requires manual implementation . ⚠️ 5. Important Rules ✔️ clone() is protected in Object class ✔️ Must override to make it accessible ✔️ If Cloneable is NOT implemented → ❌ CloneNotSupportedException . 🔥 6. Key Points for Interviews ✔️ Cloneable is a marker interface ✔️ Default cloning = shallow copy ✔️ Deep copy must be handled manually ✔️ Avoid cloning for complex objects . 🎯 7. Best Practices (Real-World Insight) 👉 Many developers prefer: ✔️ Copy Constructors ✔️ Factory Methods 💡 Because clone() can be tricky and error-prone . 🎯 Perfect Interview Answer “Object cloning in Java is the process of creating a copy of an object using the clone() method. The class must implement Cloneable interface. By default, cloning creates a shallow copy, and deep copy must be implemented manually for nested objects.” . 💬 Let’s discuss: Do you use clone() or copy constructors in real-world projects? 👇 Comment your answer . . #Java #CoreJava #JavaInterview #OOP #ObjectOrientedProgramming #Programming #Developers #Coding #SoftwareDevelopment #JavaDeveloper #TechLearning #InterviewPreparation #CodingInterview #DeveloperLife #LearnToCode
To view or add a comment, sign in
-
-
🚀 Java Interview Series – Day 4 What is Polymorphism in Java? Polymorphism means “one name, many forms.” In Java, it allows the same method or interface to behave differently based on the context. There are two main types: • Compile-time Polymorphism (Method Overloading) Same method name, different parameters • Runtime Polymorphism (Method Overriding) Subclass provides its own implementation of a method Why is this important? ✔ Improves code flexibility ✔ Enables dynamic behavior ✔ Makes systems extensible and scalable 💡 Example: A Payment system can have a method pay(). Different implementations like CreditCardPayment, UPIPayment, or NetBankingPayment can override this method and provide their own behavior. This allows you to write generic code while supporting multiple implementations. ⚡ Key Insight: Runtime polymorphism (via method overriding) is heavily used in frameworks like Spring for building flexible and loosely coupled systems. 💬 Interview Tip: Don’t just define polymorphism—always give: Both types (compile-time & runtime) A real-world example And mention flexibility in system design Polymorphism is one of the core reasons why Java applications can scale and evolve without major rewrites. Follow along for more deep dives into Java concepts. #Java #JavaDeveloper #OOP #Polymorphism #SoftwareEngineering #BackendDevelopment #CleanCode #TechInterview #CodingInterview #SystemDesign #Developers #LearningInPublic #CareerGrowth #IndiaJobs #USJobs #UKJobs #AustraliaJobs
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