Day 2/100 — Variables & Data Types in Java 🧱 Before you can write any meaningful Java program, you must understand one fundamental concept — how Java stores data in memory. That’s where variables and data types come in. A variable is simply a named container in memory. When you write int age = 25, you’re telling Java to reserve a space in memory, label it age, and store the value 25 inside it. A data type tells Java two things: • What type of value will be stored • How much memory should be allocated Java has 8 primitive data types: int → whole numbers double → decimal numbers char → a single character (always use single quotes) boolean → true or false long → large whole numbers float → decimal numbers with less precision byte → very small integers short → small integers ⚠️ One important thing beginners often miss: String is NOT a primitive data type. It’s a class, which is why it starts with a capital S. 3 rules you should always remember: ✔ Use single quotes (' ') for char ✔ Use double quotes (" ") for String ✔ long values should end with L → 123456789L ✔ float values should end with f → 3.14f 💻 Today's Challenge Declare 5 variables about yourself: • Name • Age • Height • City • Whether you are a student Use the correct data types for each one. Drop your code in the comments — I’ll check if the types are correct. 👇 #Java #100DaysOfJava #100DaysOfCode #CoreJava #LearnJava #JavaDeveloper #Programming
Java Variables & Data Types: Understanding Memory Storage
More Relevant Posts
-
Java Collection Framework – Post 3️⃣ (Final) Map Interface (HashMap, LinkedHashMap, TreeMap) 🔑 📌 A Map is a data structure that stores key–value pairs (K, V). •Each key is unique. •Duplicate keys are not allowed. •Duplicate values are allowed. •You access values using their unique keys. 📌 HashMap (Most Used) •Does not maintain order. •Stores data using hashing. •Provides fast performance. 🔎 How HashMap Works Internally (Put Method) 1️⃣ hashCode() is generated int hash = key.hashCode(); 2️⃣ Bucket index is calculated index = hash & (n - 1) 3️⃣ Entry is placed in bucket If bucket is empty → add entry. If not → use equals() to check key. 📌 Collision Handling •Same key → value is overwritten •Different keys, same index → collision 📌 In case of collision: Stored in Linked List From Java 8+, if entries > 8 → converted to Balanced Tree (Treeify). 📌 Other Implementations 1️⃣ LinkedHashMap •Maintains insertion order •Uses doubly linked list 2️⃣ TreeMap •Stores data in sorted order (by keys) •Uses Red-Black Tree Time complexity → O(log n) This completes the Java Collection Framework series. Grateful to my mentor Suresh Bishnoi Sir for explaining these concepts with clarity and real-world depth. If this series added value, consider sharing it and connect to stay updated with more Java concepts. #Java #JavaCollections #Map #HashMap #LinkedHashMap #TreeMap #CoreJava #JavaDeveloper #BackendDevelopment #DataStructures #InterviewPreparation #SoftwareEngineering
To view or add a comment, sign in
-
-
🔹 In Java, the Map hierarchy forms the foundation for key-value data structures: Map interface → HashMap, LinkedHashMap, TreeMap. Each has its own behavior and use-case in terms of ordering, and sorting. Many developers use HashMap daily, but do you know what happens behind the scenes? Let’s decode it 👇 HashMap Internals: Beyond Simple Key-Value Storage 1️⃣ Buckets & Nodes HashMap stores entries in an array of buckets. Each bucket contains nodes, and each node holds a key-value pair. 2️⃣ Hashing: The Core Mechanism Every key generates a hash code, which is used to compute the bucket index: index = (n - 1) & hash This ensures efficient data distribution and fast access. 3️⃣ Collision Handling When multiple keys map to the same bucket → collision occurs. Java handles collisions using: Linked List (Java < 8) Red-Black Tree (Java 8+, when bucket size > 8) 4️⃣ Insertion & Retrieval Insertion (put): hash → bucket → insert/update node Retrieval (get): hash → bucket → traverse nodes → match key 5️⃣ Resize & Load Factor Default capacity = 16, load factor = 0.75 When size > capacity × load factor, HashMap resizes (doubles capacity) to maintain performance 💡 Performance Insights Average case: O(1) ✅ Worst case: O(log n) after Java 8 ✅ Takeaway: A well-implemented hashCode() and equals() is key to fast, reliable HashMap performance. #Java #HashMap #DataStructures #Programming #SoftwareEngineering #CodingTips #DeveloperInsights
To view or add a comment, sign in
-
-
Most Java developers still write 15+ lines of boilerplate for a simple data class. Java Records changed everything. 🚀 Before Records (Java < 14): class Person { private final String name; private final int age; // constructor, getters, equals(), hashCode(), toString()... 😩 } After Records (Java 14+): record Person(String name, int age) {} That's it. Done. ✅ Key Takeaway 💡: Java Records auto-generate constructor, getters, equals(), hashCode(), and toString() — all immutable by default. Perfect for DTOs and data carriers! ⚠️ Remember: Records are immutable — you can't add setters. Use them when your data shouldn't change after creation. What's your go-to way to reduce boilerplate in Java — Records, Lombok, or something else? Drop it below! 👇 #Java #JavaDeveloper #CleanCode #JavaRecords #CodingTips #TodayILearned
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
-
-
⚡ Java 8 Lambda Expressions — Write Less, Do More Java 8 completely changed how we write code. What once required verbose boilerplate can now be expressed in a single, clean line 👇 🔹 Before Java 8 Runnable r = new Runnable() { public void run() { System.out.println("Hello World"); } }; 🔹 With Lambda Expression Runnable r = () -> System.out.println("Hello World"); 💡 What are Lambda Expressions? A concise way to represent a function without a name — enabling you to pass behavior as data. 🚀 Where Lambdas Really Shine ✔️ Functional Interfaces (Runnable, Comparator, Predicate) ✔️ Streams & Collections ✔️ Parallel Processing ✔️ Event Handling ✔️ Writing clean, readable code 📌 Real-World Example List<String> names = Arrays.asList("Java", "Spring", "Lambda"); // Using Lambda names.forEach(name -> System.out.println(name)); // Using Method Reference (cleaner) names.forEach(System.out::println); 🔥 Pro Tip Lambdas are most powerful when used with functional interfaces — that’s where Java becomes truly expressive. 💬 Java didn’t just become shorter with Lambdas — it became smarter and more functional. 👉 What’s your favorite Java 8+ feature? Drop a 🔥 or share below! #Java #Java8 #LambdaExpressions #Programming #BackendDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
-
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
To view or add a comment, sign in
-
-
🚀 **Mastering Java Collection Framework – The Backbone of Data Handling!** Understanding the **Collection Framework** is essential for every Java developer aiming to write efficient and scalable applications. 📌 **What is Collection Framework?** It allows us to manage a **group of elements and objects** effectively in Java. 💡 **Key Operations You Can Perform:** ✔️ Data Insertion ✔️ Deletion ✔️ Manipulation ✔️ Updation ✔️ Searching ✔️ Sorting 🔹 The Collection Framework internally supports **Generics**, which means: 👉 You can store different types of data and objects safely and efficiently. 📚 **Core Concept:** * `Collection` is an **interface** from the `java.util` package * It is the **root interface** of the collection hierarchy * Represents a group of objects (elements) ⚡ **Important Points:** 🔸 Some collections allow duplicates, others do not 🔸 Some are ordered, others are unordered 🔸 No direct implementation for Collection interface 🔸 Instead, Java provides implementations through sub-interfaces 📊 **Sub-Interfaces & Implementations:** 👉 **List** * ArrayList * LinkedList * Stack * Vector 👉 **Set** * HashSet * LinkedHashSet * TreeSet 👉 **Map** *(Not a direct subtype of Collection but part of framework)* * HashMap * LinkedHashMap * TreeMap * Hashtable #Java #JavaDeveloper #FullStackDeveloper #Programming #Coding #Developers #SoftwareEngineering #TechLearning #LearnJava #JavaCollections #DataStructures #CodingLife #ITCareer #DeveloperCommunity #ProgrammingTips #JavaTraining #CareerGrowth #TechSkills #SoftwareDeveloper #ShiftEduTech
To view or add a comment, sign in
-
-
Exploring Java Stack Data Structure 🚀 In this simple example, I used Java's Stack to store different data types using Object type. It helped me better understand: - LIFO (Last In First Out) principle - How Stack works in Java - Storing multiple data types in one structure Always learning, always improving. 💻 import java.util.Stack; public class Main { public static void main(String[] args) { Stack<Object> my_stack =new Stack<>(); my_stack.push(1.25); my_stack.push(78); my_stack.push(true); my_stack.push("engin"); my_stack.push(9999999L); my_stack.push('E'); System.out.println(my_stack); } } https://lnkd.in/d3hZN9B4 #Java #DataStructures #Programming #Learning
To view or add a comment, sign in
-
🚀 Java Series – Day 2 📌 Topic: Arrays.asList() vs List.of() 🔹 What is Arrays.asList()? It converts an array into a fixed-size list 👉 You can change elements but cannot add/remove 🔹 What is List.of()? It creates an immutable list 👉 No modification allowed at all 🔹 Key Differences ✔ Arrays.asList() • Fixed size list • set() allowed ✅ • add/remove ❌ • null allowed ✅ ✔ List.of() • Completely immutable • No add/remove/set ❌ • null NOT allowed ❌ 🔹 Example List<String> list1 = Arrays.asList("Java", "Python"); list1.set(1, "C++"); // ✅ Allowed List<String> list2 = List.of("Java", "Python"); list2.set(1, "C++"); // ❌ Error 🔹 Important Point 👉 Arrays.asList() → backed by array 👉 List.of() → safe & immutable 💡 Key Takeaway Use Arrays.asList() when working with arrays Use List.of() when you need fixed, safe data Consistency is the key 🔥 Day 2 complete ✅ What do you think about this? 👇 #Java #JavaDeveloper #Programming #BackendDevelopment #CodingJourney #100DaysOfCode
To view or add a comment, sign in
-
-
🚨 Ever faced this weird issue while filtering data by date? 👉 Consider a scenario: You’re using java.util.Date and applying a filter for a specific date… Expected result: Data should be returned Actual result: ❌ No data found! Even though the data exists in the database 🤯 After debugging, here’s what’s actually happening 👇 When filtering on: 📅 DD-MM-YYYY It internally becomes: ⏱ DD-MM-YYYY 00:00:00 IST (or) DD-MM-YYYY 05:30:00 UTC ⚠️ Because java.util.Date stores both date & time, and timezone comes into play during comparisons! 💡 That’s when I learned something new… 🔹 java.util.Date ⚠️ Legacy class ⏱ Stores date + time 🚫 Not thread-safe ❌ Less flexible → requires extra conversions (often to LocalDate/LocalDateTime) ❌ Can lead to subtle bugs like filtering mismatches 🔹 java.sql.Date ⚠️ Legacy class 🗄 Mainly for JDBC interaction 🔒 Supports only date (no time or timezone) ❌ Less flexible → tightly coupled with DB and requires conversion to LocalDate for real-world usage ✅ java.time.LocalDate ✨ Modern Java 8+ API 📅 Stores only date (no time, no timezone confusion) 🎯 Perfect for filtering & business logic 🔐 Thread-safe & clean to use 🔥 Final Takeaway: ✔ Choose the right date type based on use case ✔ Avoid unnecessary conversions ✔ Prefer LocalDate for predictable and bug-free behavior 💬 Have you faced similar issues with date handling? #Java #SpringBoot #BackendDevelopment
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
👏👏