The Two Pillars: Primitives vs. References Java clearly separates its data types into two main categories: Primitive Types: These hold the actual value directly. They are simple, memory-efficient, and stored in the Stack Memory. They are the 'nuts and bolts' of computation. Numeric: byte, short, int, long (for whole numbers), float, double (for decimals). Character: char (for a single character). Logical: boolean (for true or false). Reference Types (Objects): These do not store the actual data directly. Instead, they store a reference (a memory address) pointing to the object's location in the Heap Memory. Examples include String, Arrays, and any custom class you create (like Scanner or a custom User class). #Java #development #datatypes #aoftwareengineering #OOPs
Java Data Types: Primitives vs References
More Relevant Posts
-
🚀 Day 47 of #100DaysOfCode – LeetCode Problem #1013: Partition Array Into Three Parts With Equal Sum 💬 Problem Summary: Given an array of integers, determine whether it can be split into three non-empty parts such that: Each part has the same sum, and The partitions appear in order (left → mid → right). Formally, we need to find indices i + 1 < j such that: sum(arr[0..i]) == sum(arr[i+1..j-1]) == sum(arr[j..end]) 🧩 Examples: Input: [0,2,1,-6,6,-7,9,1,2,0,1] Output: true ✔️ Three parts sum to 3 each. Input: [0,2,1,-6,6,7,9,-1,2,0,1] Output: false 🧠 Logic: This challenge focuses on finding equal prefix sums: 1️⃣ Compute total sum of the array. 2️⃣ If total sum is not divisible by 3 → ❌ impossible. 3️⃣ Walk through the array, accumulating values. 4️⃣ Each time a segment equals target = totalSum / 3, increase the partition count. 5️⃣ If we find 2 such partitions before the last index → array can be divided. 💻 Java Solution: class Solution { public boolean canThreePartsEqualSum(int[] arr) { int total = 0; for(int num : arr) total += num; if(total % 3 != 0) return false; int target = total / 3; int sum = 0, count = 0; for(int i = 0; i < arr.length; i++) { sum += arr[i]; if(sum == target) { count++; sum = 0; if(count == 2 && i < arr.length - 1) return true; } } return false; } } ⚙️ Complexity: Time: O(n) Space: O(1) ✅ Result: Accepted (Runtime: 0 ms) 💬 Takeaway: A great pattern-recognition problem—once you realize that only two valid partitions are needed (the third is implied), the solution becomes clean and efficient.
To view or add a comment, sign in
-
💭 Java Memory Leaks: They Exist (Even with Garbage Collection!) 🧠 Most developers believe: > “Java has Garbage Collection, so memory leaks can’t happen.” But here’s the truth 👇 Even with GC, your app can still leak memory — and the scary part? It happens silently. 😬 --- ⚙️ How It Happens GC only removes objects that are no longer referenced. If something still holds a reference — even accidentally — the GC leaves it untouched. Common leak culprits 👇 1️⃣ Static fields — A static list or map that keeps growing and never cleared. 2️⃣ Inner classes / Anonymous classes — Hold an implicit reference to the outer class. 3️⃣ ThreadLocal misuse — Forgetting to call remove() keeps data alive across threads. 4️⃣ Caches that never expire — Especially when using custom in-memory maps. --- 🚨 Real-world example private static List<Data> cache = new ArrayList<>(); public void loadData() { cache.add(new Data()); } Every call keeps adding objects — and since cache is static, the GC can never reclaim that memory 🧱 --- 💡 How to Prevent It ✅ Always clear ThreadLocal after use ✅ Use WeakReference or WeakHashMap for caches ✅ Monitor heap usage with tools like VisualVM or Eclipse MAT ✅ Watch out for static collections or lingering listeners --- ⚡ The Takeaway Garbage Collection isn’t a silver bullet — it’s a helper, not a housekeeper. As engineers, it’s our job to manage references wisely 💪 --- 💬 Your turn: Have you ever faced a production memory issue that GC alone couldn’t fix? 👇 Share your experience — it might help someone else today! #Java #GarbageCollection #MemoryLeak #PerformanceTuning #BackendDevelopment #CleanCode #JavaDeveloper
To view or add a comment, sign in
-
🚀 How a Single Annotation Made Our Java Backend 50x Faster Sometimes, performance issues hide in plain sight. In our case, it was a seemingly harmless @Transactional annotation. Here’s what happened 👇 We had: @Transactional @Query("SELECT u FROM User u WHERE u.id = :id") Optional<User> findById(@Param("id") Long id); This annotation was silently creating proxies, starting unnecessary transactions, and performing dirty checks — all for a simple read query. The fix? @Transactional(readOnly = true) public interface UserRepository extends JpaRepository<User, Long> {} 💡 Instant impact: 10ms → 0.2ms per query (50x faster!) 📊 Key takeaways: Use @Transactional(readOnly = true) for queries — avoids unnecessary flush checks Don’t annotate repository methods with @Transactional unless needed Always profile before guessing — tools like JProfiler, YourKit, or async-profiler reveal hidden bottlenecks Micro-optimizations scale — saving milliseconds per request can mean hours of CPU time saved daily Sometimes, small changes lead to massive performance wins. ⚡ #Java #SpringBoot #Performance #BackendDevelopment #CodeOptimization #TechLearning #SpringDataJPA
To view or add a comment, sign in
-
Java Thread Lifecycle and Synchronization Explained Clearly Once you understand what threads are, the next step is knowing how they live and interact. Every thread in Java follows a clear lifecycle. 1. New Thread is created but not started yet. Thread t = new Thread(() -> System.out.println("Running...")); 2. Runnable When you call t.start(), it moves to the runnable state. It’s ready to run when the CPU allows it. 3. Running The thread is actively executing its code. 4. Blocked / Waiting The thread pauses temporarily — maybe waiting for a resource or another thread to complete. 5. Terminated After completing its task, the thread dies. You can’t restart a dead thread. You must create a new one. Why Synchronization matters When multiple threads modify shared data, things can go wrong fast. For example: class Counter { private int count = 0; public synchronized void increment() { count++; } } The synchronized keyword ensures only one thread accesses increment() at a time. Without it, two threads could update count at once, causing inconsistent results. Quick recap Every thread has a clear lifecycle. Synchronization prevents data corruption. Always guard shared resources in multithreaded code. Understanding these basics prepares you for real-world concurrency problems. Next, we’ll move into ExecutorService and Thread Pools, which make managing multiple threads much easier. How do you handle thread safety in your code — synchronized blocks or locks? #Java #SpringBoot #Programming #SoftwareDevelopment #Cloud #AI #Coding #Learning #Tech #Technology #WebDevelopment #Microservices #API #Database #SpringFramework #Hibernate #MySQL #BackendDevelopment #CareerGrowth #ProfessionalDevelopment
To view or add a comment, sign in
-
𝙃𝙤𝙬 𝙅𝙑𝙈 𝙈𝙚𝙢𝙤𝙧𝙮 𝙒𝙤𝙧𝙠𝙨 (𝙃𝙚𝙖𝙥, 𝙎𝙩𝙖𝙘𝙠, 𝙈𝙚𝙩𝙖𝙎𝙥𝙖𝙘𝙚) — 𝙎𝙞𝙢𝙥𝙡𝙚 𝙀𝙭𝙥𝙡𝙖𝙣𝙖𝙩𝙞𝙤𝙣 Understanding JVM memory is a must for every Java backend developer. Almost every interviewer asks this in some form. Here’s the simplest explanation 👇 1️⃣ JVM divides memory into two main parts: Heap and Stack ✅ Stack Memory Used for: method calls local variables function arguments Fast and automatically cleaned up when a method finishes. Example: int x = 10; // stored in stack Each thread has its own stack. --- 2️⃣ Heap Memory (big area) Used for storing objects: User u = new User(); // stored in heap Heap is shared by all threads. Garbage Collector cleans the heap. Heap is divided into: --- 2.1 Young Generation (new objects) Eden → new objects created here Survivor S0/S1 → objects that survive a few GC cycles Frequent “minor GC” happens here. --- 2.2 Old Generation (long-lived objects) If an object stays alive long enough, it moves here. GC here is called “major GC”. --- 3️⃣ MetaSpace (stores class information) This is where JVM stores: class definitions methods metadata Replaced “PermGen” after Java 8. It grows automatically based on need. --- 4️⃣ Simple Flow 1. Program starts 2. Methods → stack 3. Objects → heap 4. Class info → metaspace 5. Garbage Collector removes unused heap objects 💡 In short Stack → method-level data, very fast Heap → objects, cleaned by GC Young Gen → new objects Old Gen → long-living objects MetaSpace → class and metadata Once you understand this, debugging memory leaks, GC issues, and OutOfMemory errors becomes much easier. #Java #JVM #BackendDevelopment #InterviewPrep #JavaInternals #CleanCode #CodingConcepts #techieanky #javainterview #prepration #concept
To view or add a comment, sign in
-
🌳 Trees in Java — From Layman to Pro (2025 Edition) Ever wondered how hierarchical structures like file systems, JSON, or company org charts are represented in code? That’s where Trees come in — nature’s most elegant data structure 🌱 In my latest article, I break down Trees from scratch — starting with simple Java examples to architect-level insights: What makes a Tree different from linear structures Building and traversing a Binary Search Tree (BST) Understanding metrics like height, depth, diameter, balance factor, and leaf count How Trees relate to real-world systems (Kubernetes, APIs, ML models, databases) And yes, a complete working Java program you can run today 🚀 If you’ve ever felt Trees were confusing — this one will make them crystal clear. Simple visuals, intuitive explanations, and modern Java code (2025-ready). 👉 Read here: https://lnkd.in/dhsQQj2p #Java #DataStructures #SystemDesign #Coding #Learning #SoftwareEngineering #Algorithms #TechEducation
To view or add a comment, sign in
-
Day 46/100 – #100DaysOfCode 🚀 | #Java #BFS #Graph ✅ Problem Solved: Word Ladder (LeetCode 127) 🧩 Problem Summary: You are given a beginWord, endWord, and a list of words. You must transform beginWord → endWord by changing one character at a time, where each intermediate word must exist in the dictionary. Return the minimum number of transformations. 💡 Approach Used: Used Breadth-First Search (BFS) because: We need the shortest path in terms of transformation steps. Each word is considered a node in a graph. Key Steps: Pre-processed all words into generic pattern groups (e.g., h*t → hot, hit, etc.). Performed BFS from beginWord until reaching endWord. Counted transformation depth as solution. ⚙️ Time Complexity: O(N × L²) 📦 Space Complexity: O(N × L) ✨ Takeaway: This problem is an excellent example of how BFS can be used for shortest transformation sequences in word-graphs. #Java #LeetCode #Graph #BFS #ProblemSolving #100DaysOfCode #CodingChallenge
To view or add a comment, sign in
-
-
Proxy Pattern in Java Use the Proxy Pattern when you want to control access to an object. You do not modify the original class. You place a proxy in front of it. Common situations • Logging • Security checks • Lazy loading • Caching Example interface Service { void process(); } class RealService implements Service { public void process() { System.out.println("Processing data"); } } class ServiceProxy implements Service { private RealService realService; public void process() { if (realService == null) { realService = new RealService(); } System.out.println("Access check done"); realService.process(); } } Usage Service service = new ServiceProxy(); service.process(); What happened • Proxy controls access • Real object is created only when needed • You add logic without touching the real class Benefits • Cleaner code • Better control • Improved performance when used for lazy loading or caching Takeaway Proxy adds control without changing the original class. #Java #SpringBoot #Programming #SoftwareDevelopment #Cloud #AI #Coding #Learning #Tech #Technology #WebDevelopment #Microservices #API #Database #SpringFramework #Hibernate #MySQL #BackendDevelopment #CareerGrowth #ProfessionalDevelopment
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