Something new I learned about Java Strings Why does this print true? 👉 String a = "Peter"; String b = "Peter"; System.out.println(a == b); Because of the String Constant Pool. Java stores string literals in a special memory area. If the value already exists, it reuses the same reference. Now look at this: 👉 String a = new String("Peter"); String b = new String("Peter"); Now a == b is false. Why? Using new forces Java to create a new object in heap memory, even if the same value exists in the pool. Why does Java do this? To optimize memory usage. Since Strings are immutable, Java can safely reuse the same object for identical literals. 💡 Key takeaway: == compares references .equals() compares actual content #Java #JavaDeveloper #BackendDevelopment #SpringBoot #SoftwareEngineering #LearningInPublic
Sajal Shrivastav’s Post
More Relevant Posts
-
🔥 String vs StringBuilder in Java In Java, String is immutable and StringBuilder is mutable — and that makes a big difference in performance. 🔹 String • Immutable (cannot be changed after creation) • Every modification creates a new object in memory • Slower when used inside loops • Thread-safe ⚠️ Repeated concatenation (like in loops) leads to unnecessary object creation and memory usage. 🔹 StringBuilder • Mutable (modifies the same object) • No new object created for each change • Faster and memory efficient • Not thread-safe 🚀 Best choice for frequent string modifications, especially inside loops. 🎯 When to Use? ✅ Use String → When value doesn’t change ✅ Use StringBuilder → When performing multiple concatenations 💡 In backend applications, choosing StringBuilder for heavy string operations improves performance significantly. #Java #BackendDevelopment #JavaProgramming #Performance
To view or add a comment, sign in
-
-
🔍 Understanding String vs StringBuilder vs StringBuffer in Java 📌 1️⃣ String String objects are immutable, meaning once a string is created, its value cannot be changed. Any modification results in the creation of a new object in memory. Because of this immutability, strings are thread-safe by default and are stored in the String Pool for memory optimization. ✔ Best used for fixed or constant text values such as messages, configuration keys, or identifiers. 📌 2️⃣ StringBuilder StringBuilder is a mutable class, allowing modifications to the same object without creating new ones. This makes it much faster for frequent string operations like concatenation or modification. However, it is not thread-safe, which means it should be used mainly in single-threaded environments. ✔ Best used when performing multiple string modifications in loops or intensive operations. 📌 3️⃣ StringBuffer StringBuffer is also mutable, similar to StringBuilder, but it is synchronized, making it thread-safe. Because synchronization adds overhead, it is generally slower than StringBuilder. ✔ Best used in multi-threaded applications where multiple threads may modify the same string. 💡 Key Takeaway • Use String for immutable and constant values • Use StringBuilder for fast string manipulation in single-threaded programs • Use StringBuffer when thread safety is required Thank you Anand Kumar Buddarapu Sir for your guidance and motivation. Learning from you was really helpful! 🙏 Uppugundla Sairam sir Saketh Kallepu sir #Java #Programming #SoftwareDevelopment #JavaDeveloper #CodingConcepts #LearningJava
To view or add a comment, sign in
-
-
Hi everyone 👋 Continuing the weekend Java Keyword Series with another important keyword 👇 📌 Java Keyword Series – Part 3 Today let’s understand one of the most important multithreading keywords in Java 👇 🔐 synchronized Keyword in Java The synchronized keyword is used to control thread access to shared resources. It ensures: - Mutual Exclusion (Only one thread at a time) - Visibility of changes - Thread Safety 🔹 Why Do We Need synchronized? In multithreading, multiple threads may try to access or modify the same object. Example problem: class Counter { int count = 0; public void increment() { count++; } } If two threads call increment() simultaneously, the result may be incorrect. Because count++ is NOT atomic. 🔹 Solution Using synchronized class Counter { int count = 0; public synchronized void increment() { count++; } } Now: - Only one thread can execute increment() at a time - Other threads must wait 🔹 How Does It Work Internally? Every object in Java has a monitor lock. When a thread enters a synchronized method/block: - It acquires the object’s lock - Other threads must wait - Lock is released when method finishes 🔹 In Simple Words synchronized ensures that only one thread at a time can access a critical section of code. #Java #Multithreading #Synchronized #CoreJava #InterviewPreparation #BackendDeveloper
To view or add a comment, sign in
-
................................................................String......................................................................... A String is a sequence of characters used to store text in Java. Strings are immutable, which means their value cannot be changed once created. If we need a mutable string, we can use StringBuffer (thread-safe) or StringBuilder. Java also uses a String Constant Pool to store string literals. String s1 = "Ankit"; String s2 = "Ankit"; Here both s1 and s2 point to the same object in the String Constant Pool to save memory.
To view or add a comment, sign in
-
-
🚀Why String is Immutable in Java? — Explained Simply🧠💡!! 👩🎓In Java, a String is immutable, which means once a String object is created, its value cannot be changed. If we try to modify it, Java creates a new String object instead of changing the existing one. 📌But why did Java designers make Strings immutable? 🤔 ✅ 1️⃣ Security Strings are widely used in sensitive areas like database URLs, file paths, and network connections. Immutability prevents accidental or malicious changes. ✅ 2️⃣ String Pool Optimization Java stores Strings in a special memory area called the String Pool. Because Strings are immutable, multiple references can safely share the same object — saving memory. ✅ 3️⃣ Thread Safety Immutable objects are naturally thread-safe. Multiple threads can use the same String without synchronization issues. ✅ 4️⃣ Performance & Caching Hashcodes of Strings are cached. Since values never change, Java can reuse hashcodes efficiently, improving performance in collections like HashMap. 🧠 Example: String name = "Java"; name = name.concat(" Dev"); Here, the original "Java" remains unchanged, and a new object "Java Dev" is created. 🚀 Understanding small concepts like this builds strong Core Java fundamentals and helps you write better, safer, and optimized code. #Java #CoreJava #Programming #JavaDeveloper #CodingConcepts #SoftwareEngineering #LearningEveryday #Parmeshwarmetkar
To view or add a comment, sign in
-
-
🚀 Prepare with Pankaj – Day 3 Today I revised an important Java concept: String Immutability In Java, String objects are immutable, which means once a String object is created, its value cannot be changed. Example: String s = "Hello"; s.concat(" World"); Here many beginners think the value of s becomes "Hello World". But actually it does NOT change. The method "concat()" creates a new String object instead of modifying the existing one. Original Object → "Hello" New Object → "Hello World" Why Java made Strings Immutable? • Security – used in URLs, file paths, DB connections • Thread Safety – safe to use across threads • String Pool Optimization – memory efficient • HashCode Caching – improves HashMap performance Small concept but very frequently asked in Java interviews. #Java #BackendDeveloper #JavaInterview #PrepareWithPankaj #LearningInPublic
To view or add a comment, sign in
-
-
Day 17 of #100days — Java File Writing & Streams Today I went deeper into File Writing and understood how Streams work in Java. In Java, everything in File I/O happens through streams — a stream is basically a flow of data from source to destination. There are two main types: 🔹 Byte Stream Works with raw binary data Uses InputStream / OutputStream Example: FileInputStream, FileOutputStream Suitable for images, audio, PDFs 🔹 Character Stream Works with text data (characters) Uses Reader / Writer Example: FileReader, FileWriter Suitable for text files 💡 Key Difference: Byte Stream → handles data byte by byte (8-bit) Character Stream → handles data character by character (16-bit Unicode) Today’s realization: Choosing the correct stream matters depending on the type of data you're handling. Text? Use character streams. Binary files? Use byte streams. Java File I/O is not just about writing files — it’s about understanding how data flows. #Java #FileIO #Streams #JavaLearning #BackendDevelopment #100DaysOfCode #ProgrammingJourney #SoftwareDevelopment
To view or add a comment, sign in
-
-
Understanding == vs .equals() in Java 🔍 As I start sharing on LinkedIn, I thought I'd kick things off with a fundamental Java concept that often trips up developers: the difference between == and .equals() **The == Operator:** → Compares memory addresses (reference equality) → Checks if two references point to the exact same object → Works for primitives by comparing actual values **The .equals() Method:** → Compares the actual content of objects → Can be overridden to define custom equality logic → Default implementation in Object class uses == (unless overridden) Here's a practical example: String str1 = new String("Java"); String str2 = new String("Java"); str1 == str2 → false (different objects in memory) str1.equals(str2) → true (same content) **Key Takeaway:** Use == for primitives and reference comparison. Use .equals() when you need to compare the actual content of objects. This fundamental concept becomes crucial when working with Collections, String operations, and custom objects in enterprise applications. What other Java fundamentals would you like me to cover? Drop your suggestions in the comments. #Java #Programming #SoftwareDevelopment #BackendDevelopment #CodingTips #JavaDeveloper
To view or add a comment, sign in
-
-
String is easily the most-used type in any #Java codebase. For the most part, we don't need to think about it, and most of the time, we don't have to. But over the last decade, the java.lang.String class has quietly evolved into an architectural marvel. My latest article covers the design decisions behind Java's most common class and how it actually works under the hood today. A few things covered in the post: • Why CHarSequence is an elegant abstraction. • Why a single emoji can silently double a string's memory footprint (and how Compact Strings work). • Why the classic advice to "always use StringBuilder instead of the + operator" is no more universally true in modern Java. • The String.intern() trap, and why G1 string deduplication mostly solved it. • A look at the modern API highlights you might have missed. If you've ever tracked a memory issue or GC thrashing down to massive char arrays in a heap dump, this one might interest you. Read "The Secret Life of a Java String" on Medium here: https://lnkd.in/evWjh9Kx
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
You should also see about intern() in String