Started learning Strings and StringBuilder in Java today. At first it looked simple, but once I began writing code, I realized the real challenge was understanding how strings actually behave in memory and how comparisons really work. Things that became clear: - Using == checks memory reference, not the actual text inside a string - Using .equals() compares the real content, which is what we usually need - Creating strings with new changes how memory is allocated and affects comparison results A small example that made this obvious: String a = "abcxyz"; String b = "abcxyz"; System.out.println(a == b); // true (same reference in string pool) System.out.println(a.equals(b)); // true (same content) String c = new String(a); System.out.println(a == c); // false (different memory) System.out.println(a.equals(c)); // true (same content) Output clearly showed why .equals() is the correct way to compare strings in real programs. Still early in this section, but the confusion from the beginning is slowly reducing. Continuing with StringBuilder and performance differences next. #java #strings #stringbuilder #codingjourney #learninginpublic #softwaredevelopment
Java Strings and StringBuilder: Understanding Memory and Comparisons
More Relevant Posts
-
Day 24.... 🚀 Deepening My Understanding of Strings in Java Today, I explored the key differences between String, StringBuffer, and StringBuilder in Java — focusing on mutability, performance, and thread safety. 1️⃣ String (Immutable) • Once created, it cannot be modified • Every change creates a new object • Thread-safe (due to immutability) • Slower for frequent modifications Common methods: length() charAt() substring() toUpperCase() toLowerCase() equals() indexOf() replace() split(). 2️⃣ StringBuffer (Mutable & Thread-Safe) • Can modify without creating new objects • Methods are synchronized • Slower than StringBuilder due to synchronization Common methods: append() insert() replace() delete() reverse(). 3️⃣ StringBuilder (Mutable & Non-Thread-Safe) • Similar to StringBuffer but not synchronized • Faster performance • Best for single-threaded applications. 4️⃣ Conversion Between Types Immutable → Mutable StringBuffer sb = new StringBuffer(str); StringBuilder sbl = new StringBuilder(str); Mutable → Immutable String str = sb.toString(); 5️⃣ String Tokenization • split() → Modern, regex-based, preferred method • StringTokenizer → Older approach Example: String[] parts = s.split(" "); 💡 Key Takeaway: Choosing the right string class in Java improves performance and ensures thread safety in applications. #Java #LearningJourney #SoftwareDevelopment #JavaDeveloper #StringHandling #CodingJourney
To view or add a comment, sign in
-
-
🔹 Today I learned about Strings in Java • A String is a sequence of characters enclosed in double quotes. • In Java, Strings are objects used to store and manipulate text. 🔹 Types of Strings • Immutable Strings – Once created, their value cannot be changed Examples: name, date of birth, gender • Mutable Strings – Their value can be changed Examples: password, email, months of the year 🔹 Ways to Create Strings • Using new keyword → String s1 = new String("java"); • Without new keyword → String s2 = "java"; 🔹 Memory Allocation (Heap Segment) • String Constant Pool (SCP) – Does not allow duplicate values – Strings created without new are stored here • Heap Area – Allows duplicate objects – Strings created with new are stored in the heap 🔹 Ways to Compare Strings • == → Compares references (memory locations) • equals() → Compares values • compareTo() → Compares strings character by character • equalsIgnoreCase() → Compares values ignoring case differences #TapAcademy #Java #JavaProgramming #LearningJava #StringConcept #ProgrammingBasics #CodingJourney #TechLearning
To view or add a comment, sign in
-
-
Today’s focus was on understanding why StringBuilder exists and how it changes the way strings are handled in Java. What changed from the previous learning: - Strings are immutable, so every modification creates a new object and increases memory usage - StringBuilder is mutable, which means changes happen in the same object without creating new ones - Common operations like append, insert, delete, reverse, and setCharAt make real text manipulation much more efficient A simple practice example: StringBuilder sb = new StringBuilder("Hello"); sb.append(" World"); // Hello World sb.insert(5, ","); // Hello, World sb.replace(7, 12, "Java"); // Hello, Java sb.delete(5, 6); // Hello Java sb.reverse(); // avaJ olleH This made it clear that performance and memory efficiency are the real reasons StringBuilder is used in real applications. The biggest realization: - Working with strings is not only about syntax - It is about choosing the right structure for efficiency Not perfect yet, but progress is visible, especially in understanding how Java handles text internally. #java #stringbuilder #datastructures #codingjourney #learninginpublic #softwaredevelopment
To view or add a comment, sign in
-
1980. LeetCode Daily Challenge Solved | Find Unique Binary String Solved today’s Find Unique Binary String problem using an elegant Diagonal Construction (Cantor’s Argument) approach. 🔹 Key Idea: Instead of generating all possible binary strings, we construct a new string by flipping the diagonal bits of the given strings. This guarantees the new string differs from every string in the array at least in one position. 🔹 Approach: Traverse each string i Check the i-th character of nums[i] Flip it (0 → 1, 1 → 0) Build a new binary string from these flipped bits This ensures the generated string cannot match any existing string in the input. 🔹 Time Complexity: O(n) 🔹 Space Complexity: O(n) 💻 Java Implementation: class Solution { public String findDifferentBinaryString(String[] nums) { char[] res = new char[nums.length]; for (int i = 0; i < nums.length; i++) { char c = nums[i].charAt(i); res[i] = (c == '0') ? '1' : '0'; } return new String(res); } } ⚡ Result: ✔ Runtime: 0 ms (Beats 100%) ✔ Memory: 42.86 MB Consistency with daily problems builds strong problem-solving intuition. On to the next challenge! #LeetCode #DSA #Java #CodingPractice #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
Quick Sort in Java may look complex, but most mistakes happen because: • we don’t clearly understand how the pivot divides the array • we mix up the partition logic • we think recursion is doing the sorting The core idea is straightforward: choose a pivot, place it in the correct position, and recursively apply the same process to the left and right parts. What really happens: – A pivot element is selected – The array is rearranged so that elements smaller than pivot go to the left – Elements greater than pivot go to the right – The pivot lands at its final sorted position Then: – The left subarray is partitioned again using a new pivot – The right subarray is partitioned again – This continues until subarrays have 0 or 1 element – A single element is already sorted by definition So: – First, one pivot divides the array into two parts – Then each part is divided again – Then those smaller parts are divided further – And so on, until everything is positioned correctly The key insight: 👉 All the real sorting happens during partitioning, not after recursion finishes. Once you understand that: • recursion just keeps reducing the problem size • partition logic ensures correct positioning • average time complexity stays O(n log n) Quick Sort isn’t about guaranteed worst-case performance — it’s about speed, in-place efficiency, and practical performance. That’s what makes it a foundation algorithm for: ✔ in-memory sorting ✔ competitive programming ✔ high-performance systems #Java #QuickSort #DSA #Algorithms #DivideAndConquer #ProblemSolving #BackendEngineering
To view or add a comment, sign in
-
Day 22 - Built-in Methods in Strings & compareTo() in Java Strings in Java are immutable, but the String class provides powerful built-in methods for efficient text handling. ✅ Commonly Used Methods in String length() → returns string length charAt(index) → access character by index substring() → extract part of a string toUpperCase() / toLowerCase() → case conversion trim() → remove leading & trailing spaces replace() → replace characters or substrings contains() → check substring presence startsWith() / endsWith() → prefix & suffix checks equals() / equalsIgnoreCase() → content comparison 🔹 compareTo() Method Used to compare strings lexicographically (dictionary order). String a = "Apple"; String b = "Banana"; a.compareTo(b); // negative value 🔸 Return Values 0 → both strings are equal > 0 → first string is greater < 0 → first string is smaller 📌 Comparison is based on Unicode values and checks characters one by one. 🔹 compareTo() vs equals() compareTo() → ordering & sorting equals() → equality check 🔑 Key Takeaway ✔ Use equals() to check equality ✔ Use compareTo() for sorting and ordering logic #Java #String #CoreJava #Programming #JavaDeveloper #Coding #SoftwareEngineering
To view or add a comment, sign in
-
-
Interfaces also allow a class to follow multiple contracts at the same time. Unlike classes, where a class can extend only one parent class, a class in Java can implement multiple interfaces. Things that became clear : • a class can implement more than one interface • each interface can define a different set of behaviours • the implementing class must provide implementations for all the methods • this approach allows combining different capabilities in a single class • it helps achieve flexibility while avoiding multiple inheritance of classes A simple example shows how multiple interfaces can be implemented : interface ICalculator { void add(int a, int b); void sub(int a, int b); } interface IAdvancedCalculator { void mul(int a, int b); void div(int a, int b); } class CalculatorImpl implements ICalculator, IAdvancedCalculator { public void add(int a, int b) { System.out.println(a + b); } public void sub(int a, int b) { System.out.println(a - b); } public void mul(int a, int b) { System.out.println(a * b); } public void div(int a, int b) { System.out.println(a / b); } } This structure allows the class to support operations defined by multiple interfaces while keeping responsibilities organized. #java #oop #programming #learning #dsajourney
To view or add a comment, sign in
-
Journey Today I solved the Anagram String Problem in Java. An anagram means two strings contain the same characters with the same frequency, just arranged in a different order. Example: listen → silent ✅ triangle → integral ✅ 🔍 What I practiced today: String traversal Converting String to char[] using toCharArray() Using Arrays.sort() for comparison Understanding character frequency logic Improving problem-solving thinking 💡 One important learning: Small mistakes like case sensitivity (toCharArray() not tocharArray()) can break the entire program. Attention to detail matters! Consistency is teaching me more than talent ever could. Every day I understand Java a little deeper. 36 days completed. No breaks. Just progress. 💪 #Day36 #CodingJourney #Java #Anagram #ProblemSolving #100DaysOfCode #Consistency #Learning My code ===== //import java.util.Arrays; class Solution { public static boolean areAnagrams(String s1, String s2) { // code here char a[]=s1.toCharArray(); char b[]=s2.toCharArray(); Arrays.sort(a); Arrays.sort(b); if(a.length!=b.length) { return false; } for(int i=0;i<a.length;i++) { if(a[i]!=b[i]) { return false; } } return true; } }
To view or add a comment, sign in
-
-
🚀 Java 8 Streams – A Small Problem That Tests Big Concepts Today I revisited a classic interview question that seems simple but hides some heavy duty concepts: 👉 Find the last repeating character in a string using Java 8 Streams. Example: Input: "programming" Output: g (The repeated chars are 'r', 'g', 'm'. 'g' is the last one to appear in the original sequence.) Here is an elegant way to solve it: Java String input = "programming"; Optional<Character> result = input.chars() .mapToObj(c -> (char) c) .collect(Collectors.groupingBy( Function.identity(), LinkedHashMap::new, // Key: Maintains insertion order Collectors.counting() // Value: Frequency count )) .entrySet() .stream() .filter(e -> e.getValue() > 1) .reduce((first, second) -> second) // The "Last" logic .map(Map.Entry::getKey); result.ifPresent(System.out::println); ✨ Why this is a great test of fundamentals: It’s not just about the syntax it’s about what’s happening under the hood: It’s easy to write code that works it’s harder to write code that is both expressive and efficient. I’m curious how would you tackle this 😄? 1️⃣ Stick to the modern Streams approach? 2️⃣ Go back to a traditional for loop for potential performance gains? 3️⃣ Use a different collection entirely? #Java #Java8 #Streams #BackendDevelopment #CodingInterview #SoftwareEngineering #CleanCode #InterviewQuestion
To view or add a comment, sign in
-
-
🚀 Stop Writing Boilerplate: Java Records in 17+ If you are still writing private final fields, constructors, getters, equals(), hashCode(), and toString() for simple data carriers, it's time to switch to Records. Introduced as a standard feature in Java 17, Records provide a compact syntax to model immutable data. Why use them? ✅ Conciseness: 1 line of code replaces 30+ lines of boilerplate. ✅ Immutability by default: Thread-safe and predictable. ✅ Intent: Explicitly declares that a class is a pure data carrier. // The old way (before Java 14/16) public class User { private final String name; private final int age; public User(String name, int age) { this.name = name; this.age = age; } // ... getters, equals, hashCode, toString ... } // The Java 17 way public record User(String name, int age) {} #java #java17 #programming #softwareengineering #backend
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