🚀 Java Series – Day 2 📌 Variables & Data Types in Java 🔹 What is it? A variable is a container used to store data in memory, and data types define what kind of value a variable can store. Java mainly has two types of data types: • Primitive Data Types – int, double, char, boolean, etc. • Non-Primitive Data Types – String, Arrays, Objects, etc. 🔹 Why do we use it? Variables help programs store and manipulate data during execution. For example: In a banking application, a variable can store a user's account balance, name, or transaction amount. Also, Java stores data in different memory areas: • Stack Memory – Stores primitive variables and method calls. • Heap Memory – Stores objects like Strings, arrays, and custom objects. This separation helps Java manage memory efficiently. 🔹 Example: public class Main { public static void main(String[] args) { int age = 22; // Primitive type (stored in stack) double salary = 50000.50; String name = "Raushan"; // Object stored in heap System.out.println(name + " is " + age + " years old."); } } 💡 Key Takeaway: Understanding variables and memory (Stack vs Heap) helps you write efficient and optimized Java programs. What do you think about this? 👇 #Java #CoreJava #JavaDeveloper #Programming #BackendDevelopment
Java Variables & Data Types Explained
More Relevant Posts
-
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
To view or add a comment, sign in
-
-
3 Java Concepts Many Developers Still Confuse 1. Collection (Interface): "Collection" is the root interface of the Java Collection Framework. It represents a group of objects. Examples: - List - Set - Queue Collection<String> names = new ArrayList<>(); names.add("Java"); names.add("Spring"); Think of it as the foundation for data structures. 2. Collections (Utility Class): "Collections" is a helper class that provides static utility methods to work with collections. Common methods: - sort() - reverse() - shuffle() - synchronizedList() List<Integer> numbers = Arrays.asList(5,3,9,1); Collections.sort(numbers); So: Collection → Interface Collections → Utility class 3. Stream API (Java 8): "Stream API" allows functional-style operations on collections. Instead of loops, you can process data declaratively. Example: List<Integer> numbers = Arrays.asList(1,2,3,4,5); numbers.stream() .filter(n -> n % 2 == 0) .forEach(System.out::println); 💡 Simple way to remember Collection → Data structure interface Collections → Utility/helper methods Stream API → Data processing pipeline Java keeps evolving, but mastering these fundamentals makes a huge difference in writing clean and efficient code. #Java #CoreJava #StreamAPI #JavaDeveloper #Programming
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
-
-
🔍 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
-
-
Stop Forgetting to Close Resources in Java 🚨 If you've worked with files, database connections, or streams in Java, you've probably written code like this: BufferedReaderbr=null; try { br=newBufferedReader(newFileReader("data.txt")); System.out.println(br.readLine()); } catch (IOExceptione) { e.printStackTrace(); } finally { if (br!=null) { br.close(); // manually closing resource } } This works... but it's easy to forget closing the resources. And may lead to memory leaks and performance issues. Enter try-with-resources(Java 7+) ✨ The try-with-resources statement is a feature introduced in Java 7 that ensures resources are automatically closed after they are no longer needed, thereby preventing resource leaks and reducing boilerplate code. 🧩Code: try (BufferedReaderbr=newBufferedReader(newFileReader("data.txt"))) { System.out.println(br.readLine()); } catch (IOExceptione) { e.printStackTrace(); } -> No finally block ->No manual closing Java automatically closes the resource after the try block finishes the execution. Why it's better ✅Less boilerplate code ✅Automatic resource cleanup ✅Safer and easier read ✅Prevents resource leaks 📌One important rule The resource must implement the AutoClosable interface. Examples: FileInputStream, BufferReader, Connection, Scanner #Java #ExceptionHandling #JavaDeveloper #CleanCode #Programming #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
-
-
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
-
-
🚀 Java Series – Day 24 📌 HashMap Internal Working in Java 🔹 What is it? HashMap is a data structure that stores data in key-value pairs. It uses a technique called hashing to store and retrieve data efficiently. 🔹 Why do we use it? HashMap provides fast operations (O(1) average time) for insert, delete, and search. For example: In an application, we can store: • User ID → User Details • Product ID → Product Info 🔹 How HashMap Works Internally: 1️⃣ Hashing - Key is converted into a hash code using "hashCode()" 2️⃣ Index Calculation - Hash code → index in array (bucket) 3️⃣ Bucket Storage - Data stored as Node (key, value) 4️⃣ Collision Handling - If two keys map to same index → collision - Java uses LinkedList / Tree (after threshold) 5️⃣ Resize (Rehashing) - When size increases → capacity doubles 🔹 Example: import java.util.*; public class Main { public static void main(String[] args) { Map<Integer, String> map = new HashMap<>(); map.put(1, "Apple"); map.put(2, "Banana"); map.put(3, "Mango"); System.out.println(map.get(2)); // Banana } } 💡 Key Takeaway: HashMap works using hashing + buckets + collision handling to achieve fast performance. What do you think about this? 👇 #Java #HashMap #Collections #JavaDeveloper #Programming #BackendDevelopment
To view or add a comment, sign in
-
-
☕ Mastering the Java Collections Framework (JCF) Are you team ArrayList or LinkedList? Choosing the right data structure isn't just about syntax—it’s about performance, scalability, and clean code. The Java Collections Framework is the backbone of data manipulation in Java. Understanding the hierarchy is the first step toward writing efficient back-end systems. 🔍 Key Takeaways from this Visual Guide: List: Use when order matters and you need index-based access (ArrayList, LinkedList). Set: Your go-to for ensuring uniqueness. No duplicates allowed here! (HashSet, TreeSet). Map: The power of Key-Value pairs. Essential for fast lookups and data mapping (HashMap, TreeMap). Queue/Deque: Perfect for managing flow, especially in FIFO (First-In-First-Out) scenarios. 💡 Pro-Tip for Interviews: Don't mix up Comparable and Comparator! Comparable is for "Natural Ordering" (defined within the class itself). Comparator is for "Custom Ordering" (defined externally), giving you total control over how you sort your objects. 🛠️ Don’t Replay the Wheel The Collections utility class is your best friend. From sort() to shuffle() and synchronizedList(), it provides thread-safe and optimized methods to handle your data groups with one line of code. What’s your most-used Collection in your current project? Do you prefer the speed of a HashMap or the sorted elegance of a TreeMap? Let’s discuss in the comments! 👇 #Java #BackendDevelopment #CodingTips #SoftwareEngineering #DataStructures #JavaCollections #TechCommunity #CleanCode
To view or add a comment, sign in
-
-
**Understanding Heap Area and String Constant Pool (SCP) in Java** When learning Java memory management, two important concepts are **Heap Memory** and the **String Constant Pool (SCP)**. 🔹 **Heap Area** The Heap is the runtime memory area where **objects are stored**. Key points: ✔ Objects are created using the **new keyword** ✔ Shared among all threads ✔ Managed by the **Garbage Collector** ✔ Stores instance variables and objects Example: String s1 = new String("Java"); Here, the object `"Java"` is created in the **Heap memory**. --- 🔹 **String Constant Pool (SCP)** The **String Constant Pool** is a special area inside the Heap that stores **string literals**. Purpose: ✔ Avoids creating duplicate string objects ✔ Improves memory efficiency Example: String s1 = "Java"; String s2 = "Java"; In this case, both `s1` and `s2` refer to the **same object in the String Constant Pool**. --- 🔹 Small Code Example String s1 = new String("Java"); String s2 = "Java"; String s3 = "Java"; System.out.println(s1 == s2); // false System.out.println(s2 == s3); // true Explanation: s1 creates a new object in Heap, while s2 and s3 share the same object in the String Constant Pool. Understanding how Java manages memory helps developers write efficient and optimized applications. #Java #JavaDeveloper #Programming #SoftwareDevelopment
To view or add a comment, sign in
-
Day 2 — Java Problem Solving Worked on a practical scenario involving JSON parsing and data transformation using Java. Problem: Given a JSON array of people, convert it into Java objects, filter entries where age is greater than 25, and extract the names into a list. Input: [ {"name":"Amit","age":25}, {"name":"Rohit","age":30} ] Approach: Used Jackson ObjectMapper to deserialize JSON into a List of Person objects Applied TypeReference to correctly handle generic type conversion Leveraged Java Streams for processing: filter() to apply the age condition map() to extract names collect() to gather results into a List Outcome: Valid Names: [Rohit] Key Takeaway: Understanding how to handle generic types during deserialization and combining it with Streams leads to clean, readable, and efficient data processing. #Java #BackendDevelopment #JavaStreams #Jackson #ProblemSolving
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
https://github.com/raushansingh7033/core-java