🚨 This small Java mistake can give wrong comparisons I used to write this: if (price == 0.1 + 0.2) { // logic } Looks correct… but it may fail ❌ --- 👉 Why? Floating-point calculations are not always exact in Java. 👉 0.1 + 0.2 = 0.30000000000000004 So comparison with "==" can fail. --- ✅ Better way: if (Math.abs(price - (0.1 + 0.2)) < 0.0001) { // logic } --- 💡 Lesson: Never use "==" for floating-point comparison. Small detail… but critical in real applications. Have you faced this before? 👇 #Java #CoreJava #Programming #BackendDeveloper #Coding #TechLearning
Java Floating Point Comparison Gotcha
More Relevant Posts
-
🚨 Java fact about constructors 👇 Constructors don’t have a return type… But something still returns an object 🤯 Example: class User { User() { System.out.println("Constructor called"); } } User user = new User(); 👉 What’s actually happening? - "new" keyword creates the object - Allocates memory - Calls the constructor - Returns the reference 👉 Important: Constructor itself does NOT return anything 👉 "new" keyword returns the object --- 👉 This is NOT a constructor: class User { void User() { } ❌ } 👉 It becomes a normal method 💡 Many people think constructor returns object… but actually new keyword does that Did you know this? 👇 #Java #CoreJava #Programming #BackendDeveloper #Coding #TechLearning
To view or add a comment, sign in
-
💡 𝗝𝗮𝘃𝗮/𝐒𝐩𝐫𝐢𝐧𝐠 𝐁𝐨𝐨𝐭 𝗧𝗶𝗽 - 𝗦𝘄𝗶𝘁𝗰𝗵 𝗘𝘅𝗽𝗿𝗲𝘀𝘀𝗶𝗼𝗻 💎 🕯 𝗧𝗿𝗮𝗱𝗶𝘁𝗶𝗼𝗻𝗮𝗹 𝗦𝘄𝗶𝘁𝗰𝗵 𝗦𝘁𝗮𝘁𝗲𝗺𝗲𝗻𝘁 The traditional switch statement has been part of Java since the beginning. It requires explicit break statements to prevent fall-through, which can lead to bugs if forgotten. Each case must contain statements that execute sequentially, making the code verbose and error-prone. 💡 𝗠𝗼𝗱𝗲𝗿𝗻 𝗦𝘄𝗶𝘁𝗰𝗵 𝗘𝘅𝗽𝗿𝗲𝘀𝘀𝗶𝗼𝗻 Switch expressions were introduced in Java 14 as a more concise and safe alternative. Using the -> syntax, you eliminate the need for break statements and can directly return values. Multiple cases can be grouped with commas, and the compiler enforces exhaustiveness for better safety. ✅ 𝗞𝗲𝘆 𝗕𝗲𝗻𝗲𝗳𝗶𝘁𝘀 ◾ No break statements, safer and cleaner code. ◾ Direct value assignment, treat switch as an expression. ◾ Multiple labels with comma separation. ◾ Compiler exhaustiveness checks, fewer runtime errors. 🤔 Which one do you prefer? #java #springboot #programming #softwareengineering #softwaredevelopment
To view or add a comment, sign in
-
-
Checked vs Unchecked Exceptions (finally made sense to me) 👇 When I first learned exceptions, this part was confusing 😅 Here’s how I understand it now: 🔹 Checked Exceptions Checked at compile-time The compiler forces you to handle them Examples: • IOException • SQLException ✔ You must either: • handle using try-catch • or declare using throws 🔹 Unchecked Exceptions Occur at runtime These are usually due to coding mistakes Examples: • NullPointerException • ArithmeticException • ArrayIndexOutOfBoundsException ✔ You’re not forced to handle them 🧠 What actually helped me understand: Checked = external issues (files, DB, network) Unchecked = logic mistakes in code ⚡ Simple takeaway You can recover from checked exceptions But unchecked ones usually mean something is wrong in your code Still learning, but this clarity helped me a lot while debugging 💡 If you’re learning Java, which one confused you more? 👇 #Java #ExceptionHandling #Developers #Programming #LearningInPublic
To view or add a comment, sign in
-
-
🔥 Day 21: Synchronization in Java A crucial concept in multithreading to avoid data inconsistency 👇 🔹 What is Synchronization? 👉 Definition: Synchronization is a mechanism to control access of multiple threads to shared resources. 🔹 Why Do We Need It? 👉 Without synchronization: Multiple threads modify data ❌ Results become inconsistent ❌ 👉 With synchronization: Only one thread accesses at a time ✅ Data remains correct ✅ 🔹 Simple Example (Without Synchronization) class Counter { int count = 0; void increment() { count++; } } 👉 Problem: Multiple threads → wrong count ⚠️ 🔹 With Synchronization class Counter { int count = 0; synchronized void increment() { count++; } } 👉 Now: ✔ One thread at a time ✔ Correct result 🔹 Types of Synchronization 1️⃣ Method Level synchronized void method() { } 2️⃣ Block Level synchronized(this) { // critical section } 3️⃣ Static Synchronization static synchronized void method() { } 🔹 Key Points ✔ Prevents race conditions ✔ Uses intrinsic lock (monitor) ✔ Slows performance slightly (due to locking) 🔹 When to Use? ✔ Shared variables ✔ Multi-threaded environment ✔ Critical sections 💡 Pro Tip: Use synchronization only where needed — too much can reduce performance ⚡ 📌 Final Thought: "Synchronization ensures safety, but balance it with performance." #Java #Multithreading #Synchronization #ThreadSafety #Programming #JavaDeveloper #Coding #InterviewPrep #Day21
To view or add a comment, sign in
-
-
Topic of the day String? Why String is Immutable? 👉 In Java, a String is immutable, which means once it is created, its value cannot be changed. Example: String s = "Hello"; s.concat(" World"); 👉 You might expect: "Hello World" 👉 But actual output: "Hello" Because concat() creates a new object, instead of modifying the existing one. 🔍 Why did Java designers make String immutable? ✔️ Security – Strings are used in sensitive areas (like DB connections, file paths, network URLs) ✔️ Thread Safety – No need for synchronization (safe in multithreading) ✔️ Performance – Enables String Pool (memory optimization) ✔️ Caching – Hashcode can be cached (used in HashMap) If you are doing multiple string modifications, prefer: 👉 StringBuilder (faster, not thread-safe) 👉 StringBuffer (thread-safe) #Java #JavaConcepts #InterviewPreparation #Programming #Developers #Programming #Development #Coding
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
-
Today I practiced a star pattern using nested loops in Java. This program demonstrates: ✔️ Use of multiple loops ✔️ Logic building for pattern design ✔️ Understanding of spacing and alignment 🧠 Problem Solved: Inverted Right-Angled Triangle Pattern Output: ***** **** *** ** * Consistent practice of small problems like this helps improve logic building and coding skills.
To view or add a comment, sign in
-
-
🔥 3. Java 8 Stream Coding Questions (Most Trending) 1. Find duplicate elements using streams. 2. Find the first non-repeating character using streams. 3. Find the longest string in a list. 4. Count frequency of characters using streams. 5. Sort a list of objects using streams. 6. Group strings by length using streams. 7. Convert a list of strings to uppercase using streams. 8. Find the second highest number using streams. 9. Find common elements between two lists using streams. 10. Remove duplicates using streams. #java8 #javainterviewqueations #frequentlyaskquetions
To view or add a comment, sign in
-
Checked Exceptions and Unchecked Exceptions may sound similar… but they behave very differently. 👀 Checked Exception is like that strict teacher: > “Handle me first, otherwise your code will not even compile.” Examples: IOException, SQLException Unchecked Exception is more dangerous: > It stays quiet… lets your program run… and then suddenly crashes everything at runtime. 💀 Examples: `NullPointerException`, `ArithmeticException` Simple rule: ✔ Checked Exception = compile-time problem ✔ Unchecked Exception = runtime surprise That’s why Java developers fear the silent ones more 😅 Which one has troubled you more? NullPointerException or IOException? #Java #CoreJava #Exceptions #CheckedException #UncheckedException #NullPointerException #JavaDeveloper #Programming #BackendDevelopment #CodingHumor
To view or add a comment, sign in
-
-
This Java snippet trips up even experienced developers 👇 Integer a = 127; Integer b = 127; Integer c = 128; Integer d = 128; System.out.println(a == b); System.out.println(c == d); One prints true. One prints false. At first glance, both comparisons look identical. Same type. Same assignment. Same operator. So what’s going on? If you know the reason, you’ve got a deeper grasp of how Java actually works under the hood. Drop your explanation below — no Googling 👇 #Java #Programming #SoftwareEngineering #DevCommunity #CodeChallenge
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