Day 10 – == vs .equals() in Java ⏳ 1 Minute Java Clarity – Understanding how Java compares Strings This is one of the most confusing topics for beginners in Java ❓ Are these the same? String a = "Java"; String b = "Java"; 👉 a == b → true 👉 a.equals(b) → true Looks same right? But wait ⚠️ 📌 What does == do? It checks if both references point to the same object (memory location). 📌 What does .equals() do? It checks if the values (content) are equal. 💥 Now see this: String a = new String("Java"); String b = new String("Java"); 👉 a == b → false ❌ (different objects in memory) 👉 a.equals(b) → true ✅ (same text content) 💡 Quick Summary ✔ == → compares memory addresses. ✔ .equals() → compares actual values. 🔹 Always use .equals() for Strings unless you specifically need to check if two variables point to the exact same memory slot. 🔹 Next → String Immutability in Java Have you ever spent hours debugging because of a == mistake? #Java #BackendDeveloper #JavaFullStack #LearningInPublic #Programming #JavaProgramming #equals() #SoftwareEngineering #TechCommunity
Java String Comparison: == vs equals()
More Relevant Posts
-
🚀 Java Puzzle: Why this prints "100" even after using "final"? 🤯 Looks like a bug… but it’s actually Java behavior 👇 👉 Example: final int[] arr = {1, 2, 3}; arr[0] = 100; System.out.println(arr[0]); // 100 😮 👉 Wait… "final" but still changing? 🤔 💡 Reality of "final": - "final" → reference cannot change - NOT → object data cannot change 👉 So: - ❌ "arr = new int[]{4,5,6}" → not allowed - ✅ "arr[0] = 100" → allowed --- 🔥 Now the REAL twist 😳 final StringBuilder sb = new StringBuilder("Java"); sb.append(" Developer"); System.out.println(sb); // Java Developer 😮 👉 Again changing despite "final" 🔥 Golden Rule: 👉 "final" means: - You cannot point to a new object - But you CAN modify the existing object 💡 Common misconception: 👉 Many think "final = constant" (NOT always true) 💬 Did you also think "final" makes everything immutable? #Java #JavaDeveloper #Programming #Coding #100DaysOfCode #TechTips #JavaTips #InterviewPrep #Developers #SoftwareEngineering
To view or add a comment, sign in
-
Java Puzzle for Today What will be the output of this program? String a = "Java"; String b = "Java"; String c = new String("Java"); System.out.println(a == b); System.out.println(a == c); System.out.println(a.equals(c)); Take a moment and guess before scrolling. Most beginners think the output will be: true true true But the actual output is: true false true Why does this happen? Because Java stores string literals in a special memory area called the String Pool. So when we write: String a = "Java"; String b = "Java"; Both variables point to the same object in the String Pool. But when we write: String c = new String("Java"); Java creates a new object in heap memory, even if the value is the same. That’s why: - "a == b" → true (same object) - "a == c" → false (different objects) - "a.equals(c)" → true (same value) Lesson: Use "equals()" to compare values, not "==". Small Java details like this can save you from real bugs in production. #Java #Programming #JavaPuzzle #Coding #SoftwareDevelopment
To view or add a comment, sign in
-
Most Java developers write code. Very few write good Java code🔥 Here are 10 Java tips every developer should know 👇 1. Prefer interfaces over implementation → Code to "List" not "ArrayList" 2. Use "StringBuilder" for string manipulation → Avoid creating unnecessary objects 3. Always override "equals()" and "hashCode()" together → Especially when using collections 4. Use "Optional" wisely → Avoid "NullPointerException", but don’t overuse it 5. Follow immutability where possible → Makes your code safer and thread-friendly 6. Use Streams, but don’t abuse them → Readability > fancy one-liners 7. Close resources properly → Use try-with-resources 8. Avoid hardcoding values → Use constants or config files 9. Understand JVM basics → Memory, Garbage Collection = performance impact 10. Write meaningful logs → Debugging becomes 10x easier Clean code isn't about writing more. It’s about writing smarter. Which one do you already follow? 👇 #Java #JavaDeveloper #SoftwareEngineering #BackendDevelopment #SpringBoot #CleanCode #Programming #Developers #TechTips #CodingLife
To view or add a comment, sign in
-
-
Day 8/100 — Mastering Strings in Java 🔤 Today I explored one of the most important topics in Core Java: Strings. Every Java developer should clearly understand these three concepts: 1️⃣ Immutability In Java, a String object cannot be changed after it is created. Any modification actually creates a new object in memory. 2️⃣ String Pool Java optimizes memory using the String Pool. When we create strings using literals, Java stores them in a special memory area and reuses them. 3️⃣ equals() vs == • equals() → compares the actual content of two strings • == → compares memory references (whether both variables point to the same object) 💻 Challenge I practiced today: Reverse a String using charAt() method. Example logic: String str = "Java"; String reversed = ""; for (int i = str.length() - 1; i >= 0; i--) { reversed += str.charAt(i); } System.out.println(reversed); Small concepts like these build strong Java fundamentals. Consistency is key in this 100 Days of Code journey 🚀 #Java #CoreJava #JavaLearning #Strings #Programming #DeveloperJourney #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Java Series – Day 1/30 📌 Topic: ArrayList in Java (Most Used Collection) 🔹 What is ArrayList? ArrayList is a dynamic array in Java. 👉 Its size grows automatically when elements are added. 🔹 Why use ArrayList? ✔ No fixed size limitation ✔ Easy to add & remove elements ✔ Widely used in real-world projects 🔹 Important Methods (Must Know) ➕ add() → Insert element ❌ remove() → Delete element 🔍 get() → Access element 📏 size() → Number of elements 🔹 Example ArrayList<String> list = new ArrayList<>(); list.add("Java"); list.add("Python"); System.out.println(list.get(0)); System.out.println(list.size()); 🔹 Important Point 👉 ArrayList stores only objects (not primitive directly) 👉 Internally uses a resizable array 💡 Key Takeaway ArrayList is one of the most asked topics in interviews and widely used in backend development. Consistency is the key 🔥 Day 1 complete ✅ What do you think about this? 👇 #Java #JavaDeveloper #Programming #BackendDevelopment #CodingJourney #100DaysOfCode
To view or add a comment, sign in
-
-
📌 Optional in Java — Avoiding NullPointerException NullPointerException is one of the most common runtime issues in Java. Java 8 introduced Optional to handle null values more safely and explicitly. --- 1️⃣ What Is Optional? Optional is a container object that may or may not contain a value. Instead of returning null, we return Optional. Example: Optional<String> name = Optional.of("Mansi"); --- 2️⃣ Creating Optional • Optional.of(value) → value must NOT be null • Optional.ofNullable(value) → value can be null • Optional.empty() → represents no value --- 3️⃣ Common Methods 🔹 isPresent() Checks if value exists 🔹 get() Returns value (not recommended directly) --- 4️⃣ Better Alternatives 🔹 orElse() Returns default value String result = optional.orElse("Default"); 🔹 orElseGet() Lazy default value 🔹 orElseThrow() Throws exception if empty --- 5️⃣ Transforming Values 🔹 map() Optional<String> name = Optional.of("java"); Optional<Integer> length = name.map(String::length); --- 6️⃣ Why Use Optional? ✔ Avoids null checks everywhere ✔ Makes code more readable ✔ Forces handling of missing values ✔ Reduces NullPointerException --- 7️⃣ When NOT to Use Optional • As class fields • In method parameters • In serialization models --- 🧠 Key Takeaway Optional makes null handling explicit and safer, but should be used wisely. It is not a replacement for every null. #Java #Java8 #Optional #CleanCode #BackendDevelopment
To view or add a comment, sign in
-
Day 9 Java Practice: Find the First Non-Repeated Character in a String While practicing Java, I worked on a classic string problem: 👉 Find the first non-repeated character in a given string. For example, in the string "swiss", the first character that does not repeat is 'w'. To solve this, I used a LinkedHashMap to store character counts while preserving insertion order. Then I iterated through the map to find the first character with count = 1. ================================================== // Online Java Compiler // Use this editor to write, compile and run your Java code online import java.util.*; class Main { public static void main(String[] args) { String s="swiss"; char[] words=s.toCharArray(); Map<Character,Integer>map=new LinkedHashMap<Character,Integer>(); for(char word:words) { map.put(word,map.getOrDefault(word,0)+1); } for(Map.Entry<Character,Integer>entry:map.entrySet()) { if(entry.getValue()==1) { System.out.println("First non-repeated character in the string is:"+entry.getKey()); break; } } } } Output:First non-repeated character in the string is:w This was a good exercise to understand: Character frequency counting Importance of insertion order using LinkedHashMap String traversal logic #AutomationTestEngineer #Selenium #Java #CodingPractice #ProblemSolving
To view or add a comment, sign in
-
-
🚨 Most Common Confusion with Variables in Java (Even for Experienced Developers) Many Java developers get confused between Class Variables, Instance Variables, and Local Variables. Understanding the difference is important for writing clean and efficient code. Let’s simplify it 👇 🔹 1. Class Variable (Static Variable) A variable declared with the static keyword. It belongs to the class, not to objects, so all objects share the same copy. Example: class Student { static String schoolName = "ABC School"; } Here, schoolName is shared across all Student objects. 🔹 2. Instance Variable Declared inside a class but without static. Each object gets its own copy. Example: class Student { String name; } Each student object can have a different name. 🔹 3. Local Variable Declared inside methods or blocks and accessible only within that scope. Example: void display() { int count = 10; } This variable exists only during method execution. 📌 Quick Comparison • Class Variable → One copy per class • Instance Variable → One copy per object • Local Variable → Exists only inside method/block 💡 Pro Tip: Local variables must be initialized before use, while class and instance variables get default values automatically. #Java #JavaProgramming #SoftwareDevelopment #CodingTips #BackendDevelopment #Developers
To view or add a comment, sign in
-
🚀 Day 2 – Subtle Java Behavior That Can Surprise You Today I explored the difference between "==" and ".equals()" in Java — and it’s more important than it looks. String a = "hello"; String b = "hello"; System.out.println(a == b); // true System.out.println(a.equals(b)); // true Now this: String c = new String("hello"); System.out.println(a == c); // false System.out.println(a.equals(c)); // true 👉 "==" compares reference (memory location) 👉 ".equals()" compares actual content 💡 The catch? Because of the String Pool, sometimes "==" appears to work correctly… until it doesn’t. This small misunderstanding can lead to tricky bugs, especially while working with collections or APIs. ✔ Rule I’m following: Always use ".equals()" for value comparison unless you explicitly care about references. #Java #BackendDevelopment #JavaBasics #LearningInPublic
To view or add a comment, sign in
-
Hello Connections, Post 17 — Java Fundamentals A-Z This one confuses every Java developer at least once. 😱 Can you spot the bug? 👇 public static void addTen(int number) { number = number + 10; } public static void main(String[] args) { int x = 5; addTen(x); System.out.println(x); // 💀 5 or 15? } Most developers say 15. The answer is 5. 😱 Java ALWAYS passes by value — never by reference! Here’s what actually happens 👇 // ✅ Understanding the fix public static int addTen(int number) { number = number + 10; return number; // ✅ Return the new value! } public static void main(String[] args) { int x = 5; x = addTen(x); // ✅ Reassign the result! System.out.println(x); // ✅ 15! } But wait — what about objects? public static void addName(List<String> names) { names.add("Mubasheer"); // ✅ This WORKS! } public static void main(String[] args) { List<String> list = new ArrayList<>(); addName(list); System.out.println(list); // [Mubasheer] ✅ } 🤯 Java passes the REFERENCE by value! You can modify the object — but not reassign it! Post 17 Summary: 🔴 Unlearned → Java passes objects by reference 🟢 Relearned → Java ALWAYS passes by value — even for objects! 🤯 Biggest surprise → This exact confusion caused a method to silently lose transaction data! Have you ever been caught by this? Drop a 📨 below! #Java #JavaFundamentals #BackendDevelopment #LearningInPublic #SDE2 Follow along for more! 👇
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
#CFBR