🔥 Today's Learning Update — #Day51 Today’s concept: Why are Strings immutable in Java? 💡 What I understood In Java, once a String is created, it cannot be changed. If we try to modify it, a new String object is created instead. 💡 Why is it designed this way? 1️⃣ String Pool (Memory Efficiency) Multiple variables can point to the same String value without creating new objects. Since Strings are immutable, this is safe and saves memory. 2️⃣ Security Strings are used in things like file paths and database connections. If they were mutable, they could be changed during execution, which could cause serious issues. 3️⃣ HashCode Performance Since a String never changes, its hashCode can be cached. This makes it very efficient when used in structures like HashMap. 💡 Important observation When we “modify” a String, we are actually creating a new object, not changing the existing one. If we need frequent modifications, it’s better to use StringBuilder, which is mutable. 🧠 What I learned today Some design decisions in Java are not limitations — they are optimizations for performance, safety, and memory efficiency. #Java #CoreJava #String #Programming #SoftwareEngineering #ConsistencyCurve
Why Strings are Immutable in Java
More Relevant Posts
-
Day 33 of Learning Java Today I learned about Return Types in Java methods, and it finally started to make sense how methods give results back! Here’s what I understood: 🔹 Every method has a return type 🔹 It tells what kind of value the method will give back 🔹 There are mainly two types: Primitive Data Types (PDT) : • byte • short • int • long • char • String • float • double • boolean Reference Data Types (RDT) : • Arrays • Classes • Interfaces • Annotations • Enums 🔹 A method can also return an object 🔹 The "return" keyword is used to send the value back 🔹 If nothing is returned, we use "void" Thanks to my mentor Ashim Prem Mahto for the clear explanations and for always clearing my doubts. #Java #LearningJava #ProgrammingJourney #CodingLife #JavaBasics #SoftwareDevelopment #DeveloperJourney #TechLearning #StudentLife
To view or add a comment, sign in
-
-
🚀 DSA in Java – Day 88 ✅ Today’s problem was all about finding the minimum distance between three equal elements in an array — and it really tested my ability to optimize brute force logic 💡 🔍 Approach I used: • Applied 3 nested loops to check all possible triplets • Optimized by skipping unnecessary comparisons using continue • Used break to stop early once a valid third element is found • Focused on minimizing (k - i) instead of full formula 💡 Key Insight: Instead of directly calculating the full distance, I realized that: 👉 Distance = 2 × (k - i) So minimizing (k - i) automatically gives the minimum distance 🚀 📈 What I learned today: • Even brute force can be improved with small optimizations • Early stopping (break) can reduce unnecessary iterations • Observing patterns in formulas helps simplify problems Some days are about solving fast, and some days are about thinking smarter — today was both 💯 Let’s keep growing consistently 💪 #DSAinJava #LeetCode #ProblemSolving #Java #CodingJourney #Consistency #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Day 10 – Race Condition & Synchronization in Java After learning multithreading, I explored a common issue: Race Condition 👉 It happens when multiple threads access and modify shared data at the same time. Example: class Counter { int count = 0; void increment() { count++; } } If multiple threads call "increment()" simultaneously: 👉 Expected: consistent count 👉 Reality: unpredictable results 💡 Why? Because "count++" is not atomic (it involves multiple steps internally) --- 👉 Solution: Synchronization synchronized void increment() { count++; } ✔ Ensures only one thread executes the method at a time ✔ Prevents data inconsistency ⚠️ Insight: Synchronization solves the problem, but excessive use can impact performance. 💡 Real takeaway: - Multithreading = powerful - But without control → leads to subtle bugs - Balance between safety and performance is key #Java #BackendDevelopment #Multithreading #Synchronization #LearningInPublic
To view or add a comment, sign in
-
Day 66 of #100DaysOfLeetCode 💻✅ Solved #3427. Sum of Variable Length Subarrays problem in Java. Approach: • Iterated through each index of the array • Determined the starting index using i - nums[i] • Ensured the start index does not go below 0 • Calculated sum of elements from start to current index i • Added each subarray sum to the total Performance: ✓ Runtime: 1 ms (Beats 99.90% submissions) ✓ Memory: 45.22 MB (Beats 56.30% submissions) Key Learning: ✓ Practiced handling variable-length subarrays ✓ Improved understanding of index-based range calculations ✓ Strengthened nested loop logic for array problems Learning one problem every single day 🚀 #Java #LeetCode #DSA #Arrays #PrefixSum #ProblemSolving #CodingJourney #100DaysOfCode
To view or add a comment, sign in
-
-
𝗠𝗮𝘀𝘁𝗲𝗿𝗶𝗻𝗴 𝗝𝗮𝘃𝗮’𝘀 𝘃𝗮𝗿 Recently, I explored how Java introduced Local Variable Type Inference (var) in Java 10 and how it transformed the way developers write cleaner and more expressive code. Java has traditionally been known for its verbosity. With the introduction of var through Project Amber, the language took a major step toward modern programming practices—balancing conciseness with strong static typing. 𝗪𝗵𝗮𝘁 𝗜 𝗹𝗲𝗮𝗿𝗻𝗲𝗱: • var allows the compiler to infer types from initializers, reducing boilerplate without losing type safety. • It is not a keyword, but a reserved type name, ensuring backward compatibility. • Works only for local variables, not for fields, method parameters, or return types. • The inferred type is always static and compile-time resolved—no runtime overhead. • Powerful in handling non-denotable types, including anonymous classes and intersection types. Must be used carefully: • Avoid when the type is unclear from the initializer • Prefer when the initializer clearly reveals the type (e.g., constructors or factory methods) • Enhances readability only when the initializer clearly conveys the type. 𝗞𝗲𝘆 𝘁𝗮𝗸𝗲𝗮𝘄𝗮𝘆: var is not just about writing less code—it’s about writing clearer, more maintainable code when used correctly. The real skill lies in knowing when to use it and when not to. A special thanks to Syed Zabi Ulla sir at PW Institute of Innovation for their clear explanations and continuous guidance throughout this topic. #Java #Programming #SoftwareDevelopment #CleanCode #Java10 #Developers #LearningJourney
To view or add a comment, sign in
-
Day 73 of #90DaysDSAChallenge Solved LeetCode 451: Sort Characters By Frequency Learned an important Java design concept today. Problem Overview: The task was to sort characters in a string based on descending frequency. What confused me initially: Why create a separate Freq class instead of just using HashMap and PriorityQueue directly? Key Learning: PriorityQueue stores one complete object at a time. For this problem, each item needs two pieces of data together: Character Frequency Example: Instead of storing: e and 2 separately We package them as: Freq('e', 2) That custom class acts like a container holding both values in one object, so PriorityQueue can compare and sort them correctly. Why this matters: This taught me that custom classes in Java are often not about complexity, they simply bundle related data into one manageable unit. Alternative approach: We can also use Map.Entry<Character, Integer> instead of creating a custom class, but building Freq makes the logic easier to understand while learning. Today’s takeaway: Not every class is for business logic — sometimes it exists just to package data cleanly. #Java #90DaysDSAChallenge #LeetCode #PriorityQueue #HashMap #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
🚀 LeetCode #258 – Add Digits | Java Solution Another quick but insightful problem solved today! 💡 📌 Problem Statement Given an integer num, repeatedly add all its digits until the result becomes a single digit. 🔍 Example Input: 38 3 + 8 = 11 1 + 1 = 2 Output: 2 💻 Approach I Used (Iterative) Keep summing digits using % 10 and / 10 Repeat until the number becomes a single digit while (num >= 10) { int sum = 0; while (num != 0) { sum += num % 10; num = num / 10; } num = sum; } return num; 🧠 Key Learning Breaking numbers using modulo & division Looping until a condition is satisfied Understanding digit manipulation 📈 Small problems like this sharpen your thinking for bigger optimizations. Happy Coding 😊 #LeetCode #Java #DSA #ProblemSolving #CodingJourney #100DaysOfCode #Algorithms
To view or add a comment, sign in
-
-
🚀 Beats 100% of all Java solutions on LeetCode! Just solved LeetCode #290 — Word Pattern in Java with 0ms runtime, outperforming every submission. Here's how I approached it 👇 🧩 Problem: Given a pattern (like "abba") and a string of words, check if the words follow the exact same pattern — a full bijection. e.g. pattern = "abba", s = "dog cat cat dog" → true ✅ 💡 My approach: Used a single HashMap<Character, String> to map each pattern character to its corresponding word. The key insight: also check containsValue() to prevent two different characters from mapping to the same word — ensuring true one-to-one bijection. 📊 Results: Runtime: 0 ms — Beats 100.00% 🌿 Memory: 42.65 MB — Beats 80.14% 🔑 Key takeaway: Always verify bijection in both directions — a one-way map is not enough for pattern matching problems. One extra containsValue() check is all it takes! All 44 test cases passed ✅ — Clean, simple, and blazing fast. #LeetCode #Java #DSA #CodingChallenge #ProblemSolving #100Percent #Programming #SoftwareEngineering #CompetitiveProgramming #HashMap
To view or add a comment, sign in
-
-
Day 44-What I Learned In a Day(JAVA) Today I revised pattern programming in Java to strengthen my core logic and understanding of loops. What I practiced: • Star patterns • Number patterns • Pyramid patterns • Inverted patterns • Nested loop logic Pattern programming helped me improve: • Loop control (for/while) • Logical thinking • Understanding of rows & columns Every pattern I solve makes my logic stronger step by step. Consistency is the key #Java #CodingJourney #PatternProgramming #Learning #StudentDeveloper
To view or add a comment, sign in
-
🚀 Day 13 – Decimal to Binary Conversion & Scope in Java Today, I learned how to convert a decimal number into a binary number and also understood the concept of scope in Java. First, I studied the method of converting decimal to binary using repeated division by 2. For example, when converting the number 7, we divide it by 2 continuously and note the remainders. When we read the remainders in reverse order, we get the binary value (111). This method helped me clearly understand how binary numbers are formed. I also learned the logic behind writing this program using a while loop. In each iteration, we divide the number by 2, store the remainder, and increase the power value. This step-by-step process makes it easy to convert any decimal number into binary using code. Next, I revised the concept of scope, which tells where a variable can be accessed in a program. I learned about method scope, where variables declared inside a method can only be used within that method. Then, I understood block scope, where variables declared inside a block (like inside curly braces {}) are limited only to that block. I also saw examples showing correct and incorrect usage of variables, which made the concept much clearer. 💪 I will continue practicing daily and improve step by step. #Java #DSA #CodingJourney #Learning #Consistency
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