Java calls itself Object-Oriented. But here's the catch nobody tells beginners. Primitive data types like int, char, float? They are NOT objects in Java. That makes Java an IMPURE object-oriented language. So how do we fix that? → Wrapper Class. --- 🔷 WHAT IS A WRAPPER CLASS? A Wrapper Class converts a primitive data type INTO an object — and back. int x = 5; Integer ob = new Integer(x); // primitive → object ✅ Now "ob" is a full Java object living on the Heap. "x" is just a primitive sitting in the Stack. Same value. Completely different in how Java treats them. --- 🔷 EVERY PRIMITIVE HAS A WRAPPER: int → Integer short → Short long → Long byte → Byte float → Float double → Double char → Character boolean → Boolean Notice the pattern? Wrapper class names are just Capitalized versions — except int → Integer and char → Character. --- ⚖️ WRAPPER vs PRIMITIVE — The Trade-off: ✅ Wrapper Class: → Program becomes 100% pure object-oriented → Can be used where objects are required (Collections, generics) → Has useful built-in methods ❌ Wrapper Class Disadvantage: → Execution speed decreases (object overhead) ✅ Primitive Data Type: → Faster in execution → Less memory usage ❌ Primitive Disadvantage: → Program becomes impure object-oriented → Cannot be used in Collections directly --- 🧠 Real-world use case: ArrayList<int> ❌ — doesn't work ArrayList<Integer> ✅ — works perfectly That's wrapper class saving you every single time you use a Collection in Java. --- Wrapper class = the bridge between primitives and the object world. Once you understand this, Java Collections make 10x more sense. 💡 Save this. Share it with a Java learner. 🔖 #Java #WrapperClass #OOP #Programming #LearnToCode #JavaDeveloper #Skillup #ComputerScience
Java's Object-Oriented Secret: Wrapper Classes
More Relevant Posts
-
🤔 Do you know the size of char in Java? 🚀 Java Data Types — Tiny Choices, Massive Impact And more importantly… ❓ Is it the same as in C? While learning Java, I came across something interesting: ❓ Why do we need so many data types…? At first, it felt like just syntax. But slowly, I realized they actually define how data behaves inside a program. 👉 Every data type affects: • Memory usage (in bytes) • Value limits (range) • Precision (for decimals) • Runtime behavior (overflow, rounding) 🔹 Primitive Data Types (The Real Foundation) These are the basic ones we use everywhere. Integer Types: • byte (1 byte) → -128 to 127 • short (2 bytes) → -32,768 to 32,767 • int (4 bytes) → most commonly used • long (8 bytes) → for large values 💡 I realized choosing between int and long is not random — it depends on the use case Floating Types: • float (4 bytes) → ~6–7 digits precision • double (8 bytes) → ~15–16 digits precision 💡 Using the wrong one can affect accuracy Other Primitives: • char → 2 bytes (UTF-16 Unicode) • boolean → true/false ⚠️ One thing that surprised me: 👉 In C: char = 1 byte 👉 In Java: char = 2 bytes This is because Java supports Unicode characters. 🔹 Reference Types Then there are non-primitive types: • String • Arrays • Objects • Interfaces 👉 These don’t store actual values 👉 They store references (addresses in memory) ⚙️ What I’m Learning At first, data types looked very basic. But now I’m starting to see: 💥 They affect memory 💥 They affect accuracy 💥 They can even cause bugs if used incorrectly 🧠 A Small Thought Next time I write: int count = 10; I’m trying to think: 👉 Do I really need int? 👉 What if the value increases? Still learning, but this made me look at “basics” differently. 🔥 It’s interesting how even small things like data types can impact bigger systems. #Java #Programming #Learning #CodingJourney #ComputerScience
To view or add a comment, sign in
-
-
🚀 Mastering Prefix Sum & Suffix Sum in Java (DSA) Understanding Prefix Sum and Suffix Sum is a game-changer in Data Structures & Algorithms. These concepts help optimize problems that involve range sums and reduce time complexity significantly. 🔹 What is Prefix Sum? Prefix Sum is an array where each element at index `i` stores the sum of elements from index `0` to `i`. 👉 Formula: prefix[i] = prefix[i-1] + arr[i] 👉 Java Example: int[] arr = {1, 2, 3, 4, 5}; int n = arr.length; int[] prefix = new int[n]; prefix[0] = arr[0]; for(int i = 1; i < n; i++) { prefix[i] = prefix[i - 1] + arr[i]; } // Output: [1, 3, 6, 10, 15] 🔹 What is Suffix Sum ? Suffix Sum is an array where each element at index `i` stores the sum from index `i` to the end of the array. 👉 Formula: suffix[i] = suffix[i+1] + arr[i] 👉 Java Example: int[] arr = {1, 2, 3, 4, 5}; int n = arr.length; int[] suffix = new int[n]; suffix[n - 1] = arr[n - 1]; for(int i = n - 2; i >= 0; i--) { suffix[i] = suffix[i + 1] + arr[i]; } // Output: [15, 14, 12, 9, 5] 💡 Why is this important? ✔ Reduces time complexity from O(n²) → O(n) ✔ Used in range sum queries ✔ Helps in solving problems like equilibrium index, subarray sums, etc. Pro Tip: Once you understand prefix sums, try solving problems like: Subarray Sum Equals K Pivot Index Range Sum Query ✨ Consistency in DSA is the key. Small concepts like these build strong problem-solving foundations. #DSA #Java #Programming #Coding #SoftwareEngineering #SDET #Learning
To view or add a comment, sign in
-
🔍 HashMap Internal Working in Java (Simple Explanation) HashMap is one of the most commonly used data structures in Java for storing key-value pairs. Understanding how it works internally helps in writing better and more efficient code. Let’s break it down step by step. 💡 What is HashMap? HashMap stores data in key-value pairs and provides O(1) average time complexity for insertion and retrieval. ⚙️ How HashMap Works Internally When we insert data: map.put("user", 101); Internally, the following steps happen: 1️⃣ Hash Generation Java generates a hash for the key using the hash function. 2️⃣ Bucket Index Calculation Index is calculated using: index = hash & (n - 1) where n = number of buckets 3️⃣ Store in Bucket The value is stored in a bucket as a node: (key, value, hash) 4️⃣ Collision Handling If multiple keys map to the same bucket: 1. Stored using Linked List 2. Converted to Red-Black Tree when bucket size becomes large (Java 8) 5️⃣ Get Operation When map.get(key) is called: Hash is generated again Bucket index is found Linked List / Tree is searched Value is returned 📦 Important Internal Properties • Default Capacity = 16 • Load Factor = 0.75 • Resize happens when: size > capacity × loadFactor • On resize, capacity doubles and rehashing happens • Java 8 uses Red-Black Tree for better performance in collisions 📌 Time Complexity Average - O(1) for Get, Put and Remove operations Worst - O(n) for Get, Put and Remove operations (In Java 8 worst case improves to O(log n) due to Red black trees) 🧠 Rule of Thumb HashMap performance comes from hashing, bucket indexing, and efficient collision handling. 👉 If you are preparing for Java backend interviews, connect & follow - I share short, practical backend concepts regularly. #Java #HashMap #DataStructures #BackendDevelopment #JavaDeveloper #Programming
To view or add a comment, sign in
-
-
💡 Class, Object & the Hidden Power of Object Class in Java Most developers learn: 👉 Class = blueprint 👉 Object = instance …but stop there. The real understanding starts when you ask: ❓ What actually happens when you create an object? When you write: "User u = new User();" You're not just creating an instance — you're: ✔️ Allocating memory in the heap ✔️ Creating a runtime identity (not just data) ✔️ Linking it to methods defined in the class ✔️ Inheriting behavior from "Object" class automatically --- 🔍 The underrated hero: "java.lang.Object" Every class in Java silently extends the Object class. That means every object carries a built-in toolkit: ✔️ "equals()" → defines logical equality (not just memory) ✔️ "hashCode()" → decides how objects behave in HashMap/HashSet ✔️ "toString()" → controls how your object is represented ✔️ "clone()" → controls copying behavior 👉 If you don’t override these properly, your objects may break in real-world systems. --- ⚠️ Real-world impact most beginners miss: • Two objects with same data ≠ equal (unless "equals()" is overridden) • HashMap fails silently if "hashCode()" is wrong • Debugging becomes painful without "toString()" • Shallow vs deep copy issues come from Object-level behavior --- 🚀 The shift from beginner → developer happens when: You stop seeing objects as "data holders" …and start seeing them as: 👉 Identity + Behavior + Contract (via Object class) --- 📌 Takeaway: If you truly understand how Object class governs every object, you won’t just write Java code — you’ll control how your objects behave in the system. #Java #OOP #SoftwareEngineering #BackendDevelopment #CodingJourney #JavaDeepDive
To view or add a comment, sign in
-
💡 Java Deep Dive: How HashMap Works Internally? HashMap is one of the most used data structures in Java—but what happens behind the scenes? 👉 Step-by-step: 1️⃣ When you put(key, value): - Java calculates hashCode() of the key - Converts it into an index using hashing 2️⃣ Data Storage: - Stored in an array of buckets (Node[]) - Each bucket can store multiple entries 3️⃣ Collision Handling: - If multiple keys map to same index → collision - Java uses: ✔️ LinkedList (before Java 8) ✔️ Balanced Tree (after Java 8, if bucket size > 8) 4️⃣ Retrieval (get key): - HashMap recalculates hash - Finds bucket → then searches using equals() 💭 Why equals() + hashCode() both matter? ✔️ hashCode() → finds bucket ✔️ equals() → finds exact key inside bucket ⚠️ Performance: - Average: O(1) - Worst case: O(log n) (after Java 8) 🔥 Real Insight: Bad hashCode() implementation = more collisions = slower performance #Java #DataStructures #BackendDevelopment #CodingInterview #SpringBoot #SoftwareEngineering
To view or add a comment, sign in
-
🚫 Java is NOT a pure object-oriented language… and that’s exactly why it wins. When I first started exploring Java in depth, I believed everything was truly object-oriented—it felt like every piece of code revolved around classes. But the deeper I went, the more I realized the reality is far more nuanced… and way more interesting. Here’s the truth 👇 👉 A pure object-oriented language means everything is an object. No exceptions. Languages like Smalltalk follow this strictly. 👉 But Java? It bends the rules. ⚡ Primitive data types exist int, char, boolean, double — these are NOT objects. They don’t belong to any class and don’t inherit from anything. ⚡ Static methods & variables break OOP principles They belong to the class, not objects—so they bypass core concepts like polymorphism. ⚡ Wrapper classes exist… but as a workaround Yes, Integer, Double, etc. exist—but the fact we need them proves primitives aren't objects. So why does Java do this? Because Java chose performance + practicality over purity. Primitive types: ✔ Faster ✔ Memory efficient ✔ Less overhead than objects If Java forced everything to be an object, it would sacrifice speed—especially in large-scale systems. 💡 The takeaway: Java is an object-oriented language, but not purely object-oriented. And that’s not a flaw—it’s a design decision. 👉 In real-world engineering, balance beats ideology. — 💬 What’s your take—does this change how you look at Java? #Java #Programming #OOP #SoftwareEngineering #Coding
To view or add a comment, sign in
-
-
Peglib 0.2.0 + 0.2.1 -- Major code generation reliability release Peglib is a PEG parser library for Java, inspired by cpp-peglib. It lets you define parsers using PEG grammar syntax, with support for both runtime interpretation and standalone source code generation. These two releases focused on one goal: making the generated standalone parser produce identical results to the interpreted parser. Every time. What changed: -- Rewrote the CST/AST code generator from the ground up to structurally mirror the interpreter's control flow. Identified and fixed 7 behavioral divergences in whitespace handling, predicate evaluation, cut failure propagation, and token boundary tracking. -- Fixed generated parsers crashing with StackOverflowError when the whitespace directive references named rules like LineComment or BlockComment. Added a reentrant guard matching the interpreter's approach. -- Fixed generated Token nodes losing their rule names. Tokens from < > captures now carry the parent rule name (e.g., "SelectKW", "NumericType") instead of a generic "token". -- Fixed CST tree structure. Container expressions (ZeroOrMore, OneOrMore, Optional) now wrap their children in proper NonTerminal nodes instead of flattening them into the parent -- matching how the interpreter builds the tree. -- Added 40 conformance tests that run the same grammars and inputs through both the interpreted and generated parsers, asserting identical success/failure outcomes. These fixes were discovered while building a PostgreSQL SQL parser with peglib. The interpreted parser handled the full grammar correctly, but the generated standalone parser had subtle failures. Now both produce matching results on all 350 tests. Test count: 308 -> 350 pragmatica-lite dependency: 0.9.10 -> 0.24.0 Available on Maven Central: <groupId>org.pragmatica-lite</groupId> <artifactId>peglib</artifactId> <version>0.2.1</version> GitHub: https://lnkd.in/dgdjZahV #java #parsing #peg #opensource #compilers
To view or add a comment, sign in
-
I’m learning Java — and this week I went deep into the Java Collections Framework 🚀 Honestly, this is where coding becomes practical. Here’s what clicked for me 👇 🔹 Collections = How you actually manage data in real projects Instead of arrays, Java gives structured ways to store data: 👉 List 👉 Set 👉 Map Each solves a different problem 🔹 List → Ordered, allows duplicates ✔ ArrayList → fast access (read-heavy) ✔ LinkedList → fast insert/delete 👉 Default choice → ArrayList (most cases) 🔹 Set → No duplicates allowed ✔ HashSet → fastest (no order) ✔ LinkedHashSet → maintains insertion order ✔ TreeSet → sorted data 👉 Use this when uniqueness matters 🔹 Map → Key-Value pairs (most used in real systems) ✔ HashMap → fastest, most common ✔ LinkedHashMap → maintains order ✔ TreeMap → sorted keys 👉 Example: storing userId → userData 🔹 Iteration styles (very important in interviews) ✔ for-each → clean & simple ✔ Iterator → when removing elements ✔ forEach + lambda → modern Java 🔹 Streams API → Game changer 🔥 Instead of loops: 👉 filter → select data 👉 map → transform 👉 collect → store result Example flow: filter → map → sort → collect This makes code: ✔ cleaner ✔ shorter ✔ more readable 💡 Big realization: Choosing the wrong collection can silently affect performance (O(1) vs O(n) vs O(log n)) 📌 Best practices I noted: ✔ Use interfaces (List, not ArrayList) ✔ Use HashMap by default ✔ Use Streams for transformation ✔ Avoid unnecessary mutations 🤔 Curious question for you: In real projects, 👉 When do you actually choose LinkedList over ArrayList? I’ve rarely seen it used — would love real-world scenarios 👇 #Java #JavaCollections #JavaDeveloper #LearningInPublic #SoftwareDevelopment #CodingJourney
To view or add a comment, sign in
-
🗂️ Java Collections Framework When I first started Java, I just used ArrayList everywhere. 😅 Need a list? ArrayList. Need to store data? ArrayList. Need anything? ArrayList. Sound familiar? Then I discovered there's an entire UNIVERSE of data structures in Java — each built for a specific purpose. ━━━━━━━━━━━━━━━━━━━━━━ 🏗️ The Big Picture — Collections Hierarchy ━━━━━━━━━━━━━━━━━━━━━━ Java Collections has TWO separate hierarchies: 1️⃣ Collection (Iterable → Collection → List / Set / Queue) 2️⃣ Map (completely separate — Key-Value pairs) 📌 Collection Side: ▸ List → ordered, duplicates allowed → ArrayList, LinkedList, Vector, Stack ▸ Set → no duplicates → HashSet, LinkedHashSet, TreeSet ▸ Queue / Deque → FIFO / double-ended → PriorityQueue, ArrayDeque 📌 Map Side: ▸ HashMap → fast, unordered ▸ LinkedHashMap → insertion-order maintained ▸ TreeMap → sorted by keys ▸ Hashtable → legacy (avoid in new code) ━━━━━━━━━━━━━━━━━━━━━━ 🔑 The Golden Rule: ━━━━━━━━━━━━━━━━━━━━━━ Choosing the WRONG collection = slow code. Choosing the RIGHT collection = clean, efficient code. And that's exactly what this series is about. 🎯 📌 What's coming next in this series: ✅ ArrayList vs LinkedList — when does it actually matter? ✅ HashSet vs TreeSet — hashing vs sorting ✅ HashMap vs TreeMap vs LinkedHashMap ✅ Queue, Deque & PriorityQueue with real use cases ✅ Interview questions on Collections ━━━━━━━━━━━━━━━━━━━━━━ If you followed my OOPs series — this one is going to be even better. 🚀 Drop a 🙋 in the comments if you're in for this series!TAP Academy #Java #Collections #JavaDeveloper #Programming #DSA #100DaysOfCode #JavaSeries #SoftwareEngineering #LearningInPublic #LinkedInLearning#tapacademy
To view or add a comment, sign in
-
-
💻 Understanding Buffer Problem & Wrapper Classes in Java While working with Java input using scanner, many beginners face a tricky issue called the Buffer Problem when using Scanner. What happens? --->>When you use nextInt() or nextFloat(), it reads only the number and leaves the newline (\n) in the buffer. --->>So the next nextLine() gets skipped unexpectedly! ~Quick Fix: Always clear the buffer: int n = scan.nextInt(); scan.nextLine(); // clear buffer String name = scan.nextLine(); 🔄 Wrapper Classes in Java Java provides Wrapper Classes to convert primitive data types into objects. @Examples: int → Integer float → Float char → Character #These are super useful when: ✔ Converting String → primitive ✔ Working with collections (like ArrayList) ✔ Using built-in utility methods 🌍 Real-Time Example Imagine a job application system: User input: 101,John,50000 **To process this** 👇 String[] data = input.split(","); int id = Integer.parseInt(data[0]); String name = data[1]; int salary = Integer.parseInt(data[2]); Here, Wrapper Classes help convert text into usable data types. #Key Takeaways ✔ Always clear buffer when mixing nextInt() & nextLine() ✔ Wrapper classes make data conversion easy ✔ Essential for real-world input handling & backend systems #Mastering these small concepts builds a strong foundation in Java! TAP Academy #Java #Programming #OOP #JavaDeveloper #Coding #SoftwareDevelopment #LearnJava
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