📅 Day 42 – Java Learning | Object Class: equals() & hashCode() Today I learned about two very important methods from the Java Object class: equals() and hashCode(). Understanding these methods is essential when working with collections like HashMap, HashSet, and when comparing objects properly. 🔹 equals() Method The equals() method is used to compare the content of two objects. By default, the Object class compares memory references, but we can override it to compare object values. Example concept: == → compares references equals() → compares content (when overridden) 🔹 hashCode() Method hashCode() returns a unique integer value representing the object. This method is mainly used in hash-based collections such as: HashMap HashSet Hashtable 🔹 Contract Between equals() and hashCode() There are important rules to follow: 1️⃣ If two objects are equal using equals(), their hashCode must be the same. 2️⃣ If two objects have the same hashCode, they may or may not be equal. 3️⃣ Sometimes JVM may generate the same hashCode for different objects → this is called Hash Collision. 4️⃣ Whenever we override equals(), we must also override hashCode(). 🔹 Example Scenario Two objects with the same data: Ex obj1 = new Ex("nazriya","nazim",33); Ex obj2 = new Ex("nazriya","nazim",33); If equals() and hashCode() are properly overridden: obj1.equals(obj2) → ✅ true obj1.hashCode() == obj2.hashCode() → ✅ same value This ensures correct behavior in hash-based collections. 💡 Key Learning: Proper implementation of equals() and hashCode() is crucial for data consistency and performance in Java collections. 🙏 Special thanks to my mentor Suresh Bishnoi from Kodewala Academy for guiding us through these core Java concepts. #Day42 #100DaysOfCode #Java #BackendDevelopment #JavaDeveloper #LearningJourney #Kodewala
Java Object Class: equals() & hashCode() Essentials
More Relevant Posts
-
DAY 29: CORE JAVA 🔗 Constructor Chaining in Java using "super()" (Inheritance) While learning Java OOP concepts, one interesting topic I explored is Constructor Chaining in Inheritance. 📌 What is Constructor Chaining? Constructor chaining is the process of calling one constructor from another constructor. In inheritance, a child class constructor calls the parent class constructor using "super()". This ensures that the parent class variables are initialized before the child class variables. ⚙️ Key Points to Remember • "super()" is used to call the parent class constructor. • It must be the first statement inside the child constructor. • If we don’t explicitly write "super()", Java automatically calls the parent class default constructor. • This mechanism ensures proper initialization of objects in inheritance hierarchy. 💡 Example Scenario Parent Class: class Test1 { int x = 100; int y = 200; } Child Class: class Test2 extends Test1 { int a = 300; int b = 400; } When an object of "Test2" is created, Java first calls the parent constructor, initializes "x" and "y", and then initializes "a" and "b". 📊 Execution Flow 1️⃣ Object of child class is created 2️⃣ Child constructor calls "super()" 3️⃣ Parent constructor executes first 4️⃣ Control returns to child constructor This concept is very important for understanding object initialization, inheritance hierarchy, and memory allocation in Java. 🚀 Learning these small internal mechanisms of Java helps build a strong foundation in Object-Oriented Programming. TAP Academy #Java #OOP #ConstructorChaining #Inheritance #JavaProgramming #SoftwareDevelopment #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 30 | Core Java Learning Journey 📌 Topic: Map Hierarchy in Java Today, I explored the Map Hierarchy in Java Collections Framework — understanding how different Map interfaces and classes are structured and related. 🔹 What is Map in Java? ✔ Map is an interface that stores key-value pairs ✔ Each key is unique and maps to a specific value ✔ It is part of java.util package 🔹 Map Hierarchy (Understanding Structure) ✔ Map (Root Interface) ⬇ ✔ SortedMap (extends Map) ⬇ ✔ NavigableMap (extends SortedMap) ⬇ ✔ TreeMap (implements NavigableMap) 🔹 Important Implementing Classes ✔ HashMap • Implements Map • Does NOT maintain order • Allows one null key ✔ LinkedHashMap • Extends HashMap • Maintains insertion order ✔ TreeMap • Implements NavigableMap • Stores data in sorted order • Does NOT allow null key ✔ Hashtable • Implements Map • Thread-safe (synchronized) • Does NOT allow null key/value 🔹 Key Differences ✔ HashMap → Fast, no ordering ✔ LinkedHashMap → Maintains insertion order ✔ TreeMap → Sorted data ✔ Hashtable → Thread-safe but slower 📌 When to Use What? ✅ Use HashMap → when performance is priority ✅ Use LinkedHashMap → when insertion order matters ✅ Use TreeMap → when sorting is required ✅ Use Hashtable → when thread safety is needed 💡 Key Takeaway: Understanding Map hierarchy helps in choosing the right data structure based on use-case rather than just coding blindly. 🙏 Special thanks to Vaibhav Barde Sir for the guidance! 🔥 #CoreJava #JavaLearning #JavaDeveloper #Map #HashMap #TreeMap #LinkedHashMap #Hashtable #JavaCollections #Programming #LearningJourney
To view or add a comment, sign in
-
-
🚀 Exploring Built-in Methods of ArrayList in Java As part of my continuous learning in Java, I explored the powerful built-in methods of ArrayList that make data handling efficient and flexible. Understanding these methods is essential for writing clean and optimized code. Here’s a quick overview of some commonly used ArrayList methods 👇 🔹 1. add() Adds an element to the list list.add("Java"); 🔹 2. add(index, value) Inserts an element at a specific position list.add(1, "Python"); 🔹 3. addAll() Adds all elements from another collection list.addAll(otherList); 🔹 4. retainAll() Keeps only common elements between two collections list.retainAll(otherList); 🔹 5. removeAll() Removes all elements present in another collection list.removeAll(otherList); 🔹 6. set() Replaces an element at a specific index list.set(0, "C++"); 🔹 7. get() Retrieves an element by index list.get(0); 🔹 8. size() Returns the number of elements list.size(); 🔹 9. trimToSize() Trims capacity to match current size list.trimToSize(); 🔹 10. isEmpty() Checks if the list is empty list.isEmpty(); 🔹 11. contains() Checks if an element exists list.contains("Java"); 🔹 12. indexOf() Returns the first occurrence index list.indexOf("Java"); 🔹 13. lastIndexOf() Returns the last occurrence index list.lastIndexOf("Java"); 🔹 14. clear() Removes all elements from the list list.clear(); 🔹 15. subList(start, end) Returns a portion of the list list.subList(1, 3); 💡 Key Takeaway: Mastering these built-in methods helps in efficiently managing collections and solving real-world problems with ease. Consistency in practicing such concepts builds a strong foundation in Java development 💻✨ #Java #ArrayList #CollectionsFramework #Programming #Developers #LearningJourney #CodingSkills #KeepGrowing TAP Academy
To view or add a comment, sign in
-
-
Day 39 of Learning Java: Downcasting & instanceof Explained Clearly 1. What is Downcasting? Downcasting is the process of converting a parent class reference → child class reference. It is the opposite of Upcasting. 👉 Key Points: Requires explicit casting Used to access child-specific methods Only works if the object is actually of the child class Example: class A {} class B extends A {} A ref = new B(); // Upcasting B obj = (B) ref; // Downcasting 💡 Here, ref actually holds a B object, so downcasting is safe. 2. When Downcasting Fails If the object is NOT of the target subclass → it throws: ClassCastException 📌 Example: A ref = new A(); B obj = (B) ref; // Runtime Error 👉 This is why we need a safety check! 3. instanceof Keyword (Safety Check ) The instanceof keyword is used to check whether an object belongs to a particular class before casting. 📌 Syntax: if (ref instanceof B) { B obj = (B) ref; } 💡 Prevents runtime errors and ensures safe downcasting. 4. Real-World Example class SoftwareEngineer { void meeting() { System.out.println("Attending meeting"); } } class Developer extends SoftwareEngineer { void coding() { System.out.println("Writing code"); } } class Tester extends SoftwareEngineer { void testing() { System.out.println("Testing application"); } } 📌 Manager Logic using instanceof: void review(SoftwareEngineer se) { if (se instanceof Developer) { Developer dev = (Developer) se; dev.coding(); } else if (se instanceof Tester) { Tester t = (Tester) se; t.testing(); } } 💡 This is a real use of polymorphism + safe downcasting 5. Key Rules to Remember ✔ Downcasting requires upcasting first ✔ Always use instanceof before downcasting ✔ Helps access child-specific behavior ✔ Wrong casting leads to runtime exceptions 💡 My Key Takeaways: Upcasting gives flexibility, Downcasting gives specificity instanceof is essential for writing safe and robust code This concept is widely used in real-world applications, frameworks, and APIs #Java #OOP #LearningInPublic #100DaysOfCode #Programming #Developers #JavaDeveloper #CodingJourney
To view or add a comment, sign in
-
-
🚀 From Writing Code to Understanding Memory — My Java Learning (Post #3) 🧠💻 In my previous posts, I shared what I learned about Access Modifiers and Non-Access Modifiers. This time, I wanted to go a bit deeper into something I’ve been using without really thinking about it: 👉 Where do variables and objects actually live in Java? Here’s my current understanding 👇 🧠 Java doesn’t directly use memory — it runs inside the JVM, which manages how data is stored in RAM. The three main areas I focused on: 🔹 Stack Memory (Execution Area) ⚡ Used for method calls and local variables. public class Main { public static void main(String[] args) { int x = 10; int y = 20; } } Here, x and y are stored in the Stack. ✔️ Fast ✔️ Temporary ✔️ Automatically cleared after execution 🔹 Heap Memory (Object Storage) 📦 Used for storing objects and instance variables. class Student { int age; } public class Main { public static void main(String[] args) { Student s1 = new Student(); s1.age = 25; } } What clicked for me here: 👉 s1 is just a reference (stored in Stack) 👉 The actual object is stored in Heap 🔹 Static Variables (Class-Level Memory) 🏫 This part confused me at first 👀 class Student { static String schoolName = "ABC School"; } ✔️ Not stored in Stack ✔️ Not inside objects in Heap 👉 Stored in a special area (Method Area) 👉 Only ONE copy exists and is shared across all objects 💡 Real-world example that helped me: Think of a university system 🎓 • Students → Objects (Heap) • Student ID → Reference (Stack) • University Name → Static variable (shared across all students) 📌 Key takeaways: ✔️ Stack = execution (temporary data) ✔️ Heap = object storage ✔️ Static = class-level shared data ✔️ JVM manages memory (physically stored in RAM) This topic really changed how I look at Java code. Earlier, I was just writing programs — now I’m starting to understand what happens behind the scenes 🔍 I’m currently focusing on strengthening my Core Java fundamentals, and I’d really appreciate any feedback, corrections, or guidance from experienced developers here 🙌 🚀 Next, I’m planning to explore Garbage Collection and how JVM manages memory efficiently. #JavaDeveloper #BackendEngineering #JavaInternals #SoftwareDevelopment #TechLearning #CodeNewbie
To view or add a comment, sign in
-
-
🚀 Learning Core Java – Understanding Inheritance Today I explored another important pillar of Object-Oriented Programming — Inheritance. Inheritance is the concept where one class acquires the properties (variables) and behaviors (methods) of another class. It is achieved using the extends keyword in Java. This helps in code reusability, reduces duplication, and builds a relationship between classes. ⸻ 🔹 Types of Inheritance in Java Java supports several types of inheritance: ✔ Single Inheritance One class inherits from one parent class. ✔ Multilevel Inheritance A chain of inheritance (Grandparent → Parent → Child). ✔ Hierarchical Inheritance Multiple classes inherit from a single parent class. ✔ Hybrid Inheritance A combination of multiple types. ⸻ 🔎 Important Concept 👉 In Java, every class has a parent class by default, which is the Object class. Even if we don’t explicitly extend any class, Java automatically extends: java.lang.Object This means: • Every class in Java inherits methods like toString(), equals(), hashCode(), etc. • The Object class is the root of the class hierarchy. ⸻ 🚫 Not Supported in Java (via classes) ❌ Multiple Inheritance One class inheriting from multiple parent classes is not supported in Java (to avoid ambiguity). 👉 However, it can be achieved using interfaces. ❌ Cyclic Inheritance A class inheriting from itself (directly or indirectly) is not allowed. ⸻ 💡 Key Insight Inheritance promotes: ✔ Code reuse ✔ Better organization ✔ Logical relationships between classes And remember: 👉 All classes in Java ultimately inherit from the Object class. ⸻ Understanding inheritance is essential for building scalable and maintainable Java applications. Excited to keep strengthening my OOP fundamentals! 🚀 #CoreJava #Inheritance #ObjectOrientedProgramming #JavaDeveloper #ProgrammingFundamentals #LearningJourney #SoftwareEngineering #TechLearning
To view or add a comment, sign in
-
-
🚀 Mastering Java Collections – Array vs ArrayList vs LinkedList vs ArrayDeque As part of my Java learning journey at Tap Academy, I explored the core differences between Array, ArrayList, LinkedList, and ArrayDeque. Understanding when to use each is crucial for writing efficient and optimized code. 🔹 1. Array Fixed size (defined at creation) Supports primitive + object types Stored in continuous memory Fast access → O(1) No built-in methods (limited operations) Cannot resize dynamically Allows duplicates & null Can be multi-dimensional 👉 Best when: Size is fixed Performance is critical Working with primitive data 🔹 2. ArrayList Dynamic (resizable array) Default capacity → 10 Allows duplicates, null, heterogeneous data Maintains insertion order Fast access → O(1) Insertion (middle) → O(n) (shifting) Rich built-in methods Stored in continuous memory 👉 Best when: Frequent data access/searching Need dynamic resizing Need utility methods 🔹 3. LinkedList Doubly linked list structure Dynamic size Allows duplicates, null, heterogeneous data Maintains insertion order Insertion/deletion → O(1) Access → O(n) (traversal) Uses dispersed memory (nodes) Implements List + Deque 👉 Best when: Frequent insertions/deletions Queue/Deque/Stack operations 🔹 4. ArrayDeque Resizable circular array Default capacity → 16 Allows duplicates & heterogeneous data ❌ Does not allow null No index-based access Fast insertion/deletion → O(1) Faster than Stack & LinkedList for queue operations Implements Deque 👉 Best when: Need fast operations at both ends Implementing stack/queue efficiently 🔥 Key Takeaway 👉 Use the right structure based on use case: Array → Fixed size + performance ArrayList → Fast access LinkedList → Frequent modifications ArrayDeque → Best for queue/stack operations Choosing the right data structure directly impacts performance, memory, and scalability. Grateful to Tap Academy for building strong fundamentals in Java Collections 🚀 🙌 Special thanks to the amazing trainers at TAP Academy: kshitij kenganavar Sharath R MD SADIQUE Bibek Singh Hemanth Reddy Vamsi yadav Harshit T Ravi Magadum Somanna M G Rohit Ravinder TAP Academy #TapAcademy #Week13Learning #CoreJava #CollectionsFramework #ArrayList #LinkedList #ArrayDeque #DataStructures #JavaFundamentals #LearningByDoing #FullStackJourney #VamsiLearns
To view or add a comment, sign in
-
-
𝗗𝗮𝘆 𝟰𝟯 𝗮𝘁 TAP Academy | 𝗝𝗮𝘃𝗮 𝗘𝘅𝗰𝗲𝗽𝘁𝗶𝗼𝗻 𝗛𝗶𝗲𝗿𝗮𝗿𝗰𝗵𝘆 Today’s learning focused on how Java structures exceptions and how we can handle them effectively to build robust applications. 𝗝𝗮𝘃𝗮 𝗘𝘅𝗰𝗲𝗽𝘁𝗶𝗼𝗻 𝗛𝗶𝗲𝗿𝗮𝗿𝗰𝗵𝘆 The hierarchy begins with Object, followed by Throwable. Throwable splits into two main branches: • Error: Represents serious system-level issues that applications typically cannot recover from (e.g., OutOfMemoryError, StackOverflowError). • Exception: Represents conditions that can be handled by the program. Exceptions are further divided into: • Checked Exceptions: Must be handled or declared using the throws keyword (e.g., IOException, SQLException). • Unchecked Exceptions (Runtime Exceptions): Occur during runtime and are not enforced by the compiler (e.g., ArithmeticException, ArrayIndexOutOfBoundsException). 𝗘𝗿𝗿𝗼𝗿𝘀 𝘃𝘀 𝗘𝘅𝗰𝗲𝗽𝘁𝗶𝗼𝗻𝘀 • Errors usually occur at runtime due to system limitations and are not meant to be handled in normal applications. • Exceptions occur due to logical or input-related issues and can be handled gracefully using try-catch. Examples: • StackOverflowError: Caused by deep or infinite recursion. • OutOfMemoryError: Occurs when JVM cannot allocate required memory. • ArithmeticException: Division by zero scenario. 𝗖𝗵𝗲𝗰𝗸𝗲𝗱 𝘃𝘀 𝗨𝗻𝗰𝗵𝗲𝗰𝗸𝗲𝗱 𝗘𝘅𝗰𝗲𝗽𝘁𝗶𝗼𝗻𝘀 • Checked: Compile-time verification ensures handling or declaration. • Unchecked: No compile-time enforcement; handling is optional but recommended. 𝗧𝗿𝘆-𝗖𝗮𝘁𝗰𝗵 𝗥𝘂𝗹𝗲𝘀 • try cannot exist without catch or finally. • Valid combinations: - try-catch - try-catch-finally - try-finally • Nested try-catch blocks are allowed. 𝗖𝘂𝘀𝘁𝗼𝗺 𝗘𝘅𝗰𝗲𝗽𝘁𝗶𝗼𝗻𝘀 • Created by extending Exception (for checked) or RuntimeException (for unchecked). • Must be explicitly thrown using the throw keyword. • JVM does not throw custom exceptions automatically. • Ducking (throws keyword) passes responsibility to the caller. 𝗜𝗺𝗽𝗼𝗿𝘁𝗮𝗻𝘁 𝗠𝗲𝘁𝗵𝗼𝗱𝘀 • getMessage(): Returns exception message. • printStackTrace(): Provides detailed debugging information including stack trace. Sharath R kshitij kenganavar Harshit T Dinesh K Sonu Kumar Ravikant Agnihotri Ayush Tiwari MIDHUN M Hari Krishnan R.S #Java #ExceptionHandling #Programming #JavaDeveloper #Coding #SoftwareDevelopment #LearnJava #Developers #JVM #Debugging #CodingJourney #BackendDevelopment #Tech #JavaLearning #SoftwareEngineering #CodingLife #DeveloperSkills #ProgrammingLife #JavaConcepts #CareerGrowth #TechSkills #LearnToCode #DeveloperJourney #JavaBasics #ComputerScience #EngineeringStudents #JavaCommunity #SkillDevelopment #ITCareer #CodingDaily
To view or add a comment, sign in
-
-
🚀 Mastering Stack in Java: A Common Mistake & Learning Moment! While working on a classic problem—Balanced Brackets using Stack—I came across a subtle but important mistake that many learners (and even developers!) tend to make. 🔍 The Problem Check whether a given string of brackets like {[()]} is balanced or not. 💡 The Mistake Using: 👉 remove() instead of pop() At first glance, it seems fine… but here’s the catch: ❌ remove() → removes element from anywhere in the stack ✅ pop() → removes the top element (LIFO principle) And Stack is all about Last In First Out! ⚠️ Why this matters? Without proper matching and order, your logic may incorrectly validate unbalanced expressions. 🧠 Key Learnings ✔ Always follow LIFO in stack problems ✔ Match opening & closing brackets correctly ✔ Check for empty stack before popping ✔ Validate final stack is empty 💻 Correct Java Program import java.util.*; public class StackBasedProgram { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = 4; while (n-- > 0) { String token = sc.next(); Stack<Character> st = new Stack<>(); boolean isBalanced = true; for (char c : token.toCharArray()) { if (c == '{' || c == '(' || c == '[') { st.push(c); } else if (c == '}' || c == ')' || c == ']') { if (st.isEmpty()) { isBalanced = false; break; } char top = st.pop(); if ((c == '}' && top != '{') || (c == ')' && top != '(') || (c == ']' && top != '[')) { isBalanced = false; break; } } } if (!st.isEmpty()) { isBalanced = false; } System.out.println(isBalanced); } } } ✨ Takeaway Small mistakes in method selection can completely change program behavior. Understanding the core concept is more important than just making the code run! 📌 This is a great exercise for students learning: Data Structures (Stack) Problem Solving Debugging skills 💬 Have you ever made a small mistake that taught you a big concept? Share your experience! #Java #DataStructures #Stack #Coding #Programming #Debugging #Learning #InterviewPreparation #Developers #ProblemSolving
To view or add a comment, sign in
-
🚀 Day 27 | Core Java Learning Journey 📌 Topic: Vector & Stack in Java Today, I learned about Vector and Stack, two important Legacy Classes in Java that are part of the early Java library and later became compatible with the Java Collections Framework. 🔹 Vector in Java ✔ Vector is a legacy class that implements the List interface ✔ Data structure: Growable (Resizable) Array ✔ Maintains insertion order ✔ Allows duplicate elements ✔ Allows multiple null values (not "NILL" ❌ → correct term is null ✔) ✔ Can store heterogeneous objects (different data types using Object) ✔ Synchronized by default (thread-safe, but slower than ArrayList) 📌 Important Methods of Vector • add() – add element • get() – access element • remove() – delete element • size() – number of elements • capacity() – current capacity of vector 💡 Note: Due to synchronization overhead, ArrayList is preferred in modern Java. 🔹 Stack in Java ✔ Stack is a subclass (child class) of Vector ✔ It is also a Legacy Class ✔ Data structure: LIFO (Last In, First Out) 📌 Core Methods of Stack • push() – add element to top • pop() – remove top element • peek() – view top element without removing 📌 Additional Useful Methods • isEmpty() – check if stack is empty • search() – find element position 💡 Note: In modern Java, Deque (ArrayDeque) is preferred over Stack for better performance. 📌 Key Difference: Vector vs Stack ✔ Vector → General-purpose dynamic array ✔ Stack → Specialized for LIFO operations 💡 Understanding these legacy classes helps in learning how Java data structures evolved and why modern alternatives are preferred today. Special thanks to Vaibhav Barde Sir for the guidance! #CoreJava #JavaLearning #JavaDeveloper #Vector #Stack #JavaCollections #Programming #LearningJourney
To view or add a comment, sign in
-
More from this author
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