🔥 Java developers pause for a second and check this A very small snippet But many developers answer it wrong Take a look ```java String s = "java easy"; System.out.println(s.length()); System.out.println(s.trim().length()); ``` ★ Before scrolling Guess the output in your mind Type your answer in the comments first Most people think the output will change after using **trim()** But wait… look carefully at the string. There is a space only in the **middle** Not at the beginning Not at the end ⬇ ⬇ ⬇ ★ Output System.out.println(s.length()); → 9 System.out.println(s.trim().length()); → 9 ✔ Reason `trim()` removes spaces only from the **start** and **end** of the string It does **not remove spaces in the middle** So the string `"java easy"` still keeps the middle space And the length remains **9** Tiny concepts like this look simple But these small fundamentals are what make a **strong Java developer** Keep learning Keep exploring And never underestimate the basics #java #javadeveloper #javaengineer #backenddeveloper #springboot #javatips #javaquestion #codingchallenge #developers #softwaredeveloper
Java Tricky Trim Method Explained
More Relevant Posts
-
Hello Connections, Post 15 — Java Fundamentals A-Z This one surprises even senior developers. 😱 Can you spot the bug? 👇 public int getValue() { try { return 1; } finally { return 2; // 💀 What gets returned? } } System.out.println(getValue()); // 1 or 2? Most developers say 1. The answer is 2. 😱 finally ALWAYS runs — and overrides return! Here’s the full order 👇 public int getValue() { try { System.out.println("try"); // 1st return 1; } catch (Exception e) { System.out.println("catch"); // Only if exception } finally { System.out.println("finally"); // ALWAYS runs! 💀 // ❌ Never return from finally! } return 0; } // Output: try → finally → returns 1 ✅ Post 15 Summary: 🔴 Unlearned → finally just cleans up resources 🟢 Relearned → finally ALWAYS runs — even after return! #Java #JavaFundamentals #BackendDevelopment #LearningInPublic #SDE2 Follow along for more! 👇
To view or add a comment, sign in
-
-
10 Java Tips to Write Cleaner & Smarter Code Great Java developers don't just write code - they write code that performs, scales, and lasts. We've put together 10 powerful Java tips to help you code more efficiently and confidently every single day. Use StringBuilder for faster string handling Master equals() vs == to avoid common bugs Embrace var for cleaner, modern Java syntax Unlock the power of Switch Expressions in Java 14+ Plus 6 more tips to sharpen your Java skills instantly These are simple, practical techniques used by top Java developers worldwide - and they make a real difference in your code quality. Whether you're building your foundation or leveling up your expertise, these tips are your shortcut to writing better Java. Which Java tip do you use the most? Share it in the comments below. Follow us for more Java, backend, and software engineering insights Website: https://lnkd.in/gM8uj6tU Explore Our Tools: https://lnkd.in/g_6VYTVB Email: info@gramosoft.in Contact: +91 8977741931 #Java #JavaDeveloper #JavaProgramming #CleanCode #SoftwareEngineering #CodingTips #LearnJava #JavaTips #CodeQuality #SoftwareDevelopment #ProgrammingTips #TechCommunity #Developer
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
-
📌 TOPIC: Optional Class in Java (Java 8) The Optional class (from java.util) is used to avoid NullPointerException and handle missing values safely. 👉 Instead of using null, we use Optional to represent a value that may or may not be present. 🔸 Why use Optional? 1️⃣ Prevents NullPointerException 2️⃣ Makes code more readable 3️⃣ Forces proper handling of missing values 🔸 Creating Optional Objects import java.util.Optional; Optional<String> opt1 = Optional.of("Hello"); // value must not be null Optional<String> opt2 = Optional.ofNullable(null); // can be null Optional<String> opt3 = Optional.empty(); // empty Optional 🔸 Common Methods ✔️ isPresent() & get() Optional<String> name = Optional.of("Java"); if(name.isPresent()) { System.out.println(name.get()); } ✔️ orElse() Optional<String> name = Optional.ofNullable(null); System.out.println(name.orElse("Default Value")); 👉 Output: Default Value ✔️ ifPresent() Optional<String> name = Optional.of("Java"); name.ifPresent(n -> System.out.println(n)); Key Insight: Optional helps write cleaner and safer code by reducing direct null checks and preventing runtime errors. #Java #Optional #Java8 #Programming #Codegnan #LearningJourney #Developers My gratitude towards my mentor #AnandKumarBuddarapu #SakethKallepu #UppugundlaSairam
To view or add a comment, sign in
-
-
🚀 Day 7/100 – Java Practice Challenge Continuing my #100DaysOfCode journey with another important Java concept. 🔹 Topic Covered: Exception Handling Exception handling helps to manage runtime errors and ensures the program runs smoothly without crashing. 💻 Practice Code: 🔸 Example Program public class Main { public static void main(String[] args) { int balance = 5000; try { int withdrawAmount = 6000; if (withdrawAmount > balance) { throw new Exception("Insufficient Balance!"); } balance -= withdrawAmount; System.out.println("Withdraw successful. Remaining balance: " + balance); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); } finally { System.out.println("Transaction completed."); } } } 📌 Key Learnings: ✔️ Handles runtime errors effectively ✔️ Prevents application crashes ✔️ try-catch is used to handle exceptions ✔️ finally block always executes 🎯 Focus: Handles "what if something goes wrong" during program execution ⚡ Types of Exceptions: 👉 Checked Exceptions 👉 Unchecked Exceptions 🔥 Interview Insight: Exception handling is widely used in real-world applications (Banking, APIs, Microservices) to ensure reliability and stability. #Java #100DaysOfCode #ExceptionHandling #JavaDeveloper #Programming #LearningInPublic
To view or add a comment, sign in
-
Unlock the power of Java Access Modifiers. Discover how these tools shape visibility in your code. Essential insights in a concise guide.
To view or add a comment, sign in
-
Most Java developers use this daily... but don't 𝘧𝘶𝘭𝘭𝘺 understand it. 𝑺𝒕𝒂𝒄𝒌 𝒗𝒔 𝑯𝒆𝒂𝒑 𝑴𝒆𝒎𝒐𝒓𝒚 𝒊𝒏 𝑱𝒂𝒗𝒂 If you're preparing for interviews or writing better Java code, this concept is a MUST. The problem? Most people just memorize the definitions. Let's change that. 𝑾𝒉𝒂𝒕 𝒊𝒔 𝑺𝒕𝒂𝒄𝒌 𝑴𝒆𝒎𝒐𝒓𝒚? Think of the Stack as your execution workspace. Every time a method is called, a new "stack frame" is created. This frame holds: Method calls Local variables References to objects 𝐊𝐞𝐲 𝐜𝐡𝐚𝐫𝐚𝐜𝐭𝐞𝐫𝐢𝐬𝐭𝐢𝐜𝐬: ->Works in LIFO (Last In First Out) manner ->Extremely fast ->Memory is automatically managed (as soon as the method finishes, the stack frame is gone) 𝑾𝒉𝒂𝒕 𝒊𝒔 𝑯𝒆𝒂𝒑 𝑴𝒆𝒎𝒐𝒓𝒚? The Heap is your storage room. All Java objects (including instance variables) live here. 𝐊𝐞𝐲 𝐜𝐡𝐚𝐫𝐚𝐜𝐭𝐞𝐫𝐢𝐬𝐭𝐢𝐜𝐬: ->Shared across the entire application ->Slower than stack access ->Managed by the Garbage Collector (this is where things get tricky!) 𝐖𝐡𝐞𝐧 𝐲𝐨𝐮 𝐰𝐫𝐢𝐭𝐞: 𝓟𝓮𝓻𝓼𝓸𝓷 𝓹 = 𝓷𝓮𝔀 𝓟𝓮𝓻𝓼𝓸𝓷(); Here's what's happening: ->𝓹 is the reference and it's stored in the Stack. ->𝓷𝓮𝔀 𝓟𝓮𝓻𝓼𝓸𝓷(); is the actual object and it's created in the Heap. Satyam Kumar #HarshCodes #Java #Programming #SoftwareEngineering #TechInterviews #CareerAdvice #MemoryManagement #codingblocks #Leetcode #codeforces
To view or add a comment, sign in
-
-
🚀 Java Revision Journey – Day 28 Today I revised LinkedHashSet in Java, an important Set implementation that maintains order along with uniqueness. 📝 LinkedHashSet Overview LinkedHashSet is a class in java.util that implements the Set interface. It combines the features of HashSet + Doubly Linked List to maintain insertion order. 📌 Key Characteristics: • Stores unique elements only (no duplicates) • Maintains insertion order • Allows one null value • Internally uses Hash table + Linked List • Implements Set, Cloneable, and Serializable • Not thread-safe 💻 Example LinkedHashSet<Integer> set = new LinkedHashSet<>(); set.add(10); set.add(20); set.add(10); // Duplicate ignored System.out.println(set); // Output: [10, 20] (in insertion order) 🏗️ Constructors Default Constructor LinkedHashSet<Integer> set = new LinkedHashSet<>(); From Collection LinkedHashSet<Integer> set = new LinkedHashSet<>(list); With Initial Capacity LinkedHashSet<Integer> set = new LinkedHashSet<>(10); With Capacity + Load Factor LinkedHashSet<Integer> set = new LinkedHashSet<>(10, 0.75f); 🔑 Basic Operations Adding Elements: • add() → Adds element (maintains insertion order) Removing Elements: • remove() → Removes specified element 🔁 Iteration • Using enhanced for-loop • Using Iterator for (Integer num : set) { System.out.println(num); } 💡 Key Insight LinkedHashSet is widely used when you need: • Maintain insertion order + uniqueness together • Predictable iteration order (unlike HashSet) • Removing duplicates while preserving original order • Slightly better performance than TreeSet with ordering needs 📌 Understanding LinkedHashSet helps in scenarios where order matters along with uniqueness, making it very useful in real-world applications. Continuing to strengthen my Java fundamentals step by step 💪🔥 #Java #JavaLearning #LinkedHashSet #DataStructures #JavaDeveloper #BackendDevelopment #Programming #JavaRevisionJourney 🚀
To view or add a comment, sign in
-
-
🚀 Exploring the Power of Java 8 Features Even with the rapid evolution of Java (Java 11, 17, 21…), Java 8 continues to dominate in production systems. Many enterprise applications still rely on it because it introduced features that fundamentally changed how developers write and structure code. ✨ Let’s dive deeper into what made Java 8 revolutionary: 🔸 Lambda Expressions Before Java 8, implementing behavior required verbose anonymous classes. Lambdas simplified this by allowing inline function definitions, reducing boilerplate and improving readability. 👉 Example: "(a, b) -> a + b" instead of multiple lines of code 🔸 Stream API Streams introduced a functional approach to processing collections. Instead of manually iterating using loops, developers can now chain operations like "filter()", "map()", and "collect()". 👉 Benefit: Cleaner, more readable, and parallelizable code 🔸 Functional Interfaces Interfaces like "Runnable", "Callable", and "Comparator" became more powerful with lambda support. 👉 Key point: Any interface with a single abstract method (SAM) can be used with lambdas 🔸 Default & Static Methods in Interfaces Java 8 allowed interfaces to have method implementations. 👉 Why it matters: Developers can enhance interfaces without breaking existing codebases (backward compatibility) 🔸 Optional Class NullPointerException is one of the most common issues in Java. Optional provides a safe way to handle null values. 👉 Example: "Optional.ofNullable(value).orElse("default")" 🔸 Method References A cleaner alternative to lambdas when you just call an existing method. 👉 Example: "System.out::println" instead of "(x) -> System.out.println(x)" 🚀 Why this matters for freshers: Most companies still expect strong knowledge of Java 8 because: ✔ Legacy systems are built on it ✔ Interviews heavily focus on Streams & Lambdas ✔ It builds a foundation for modern Java concepts 📌 Pro Tip: Don’t just learn syntax — practice converting traditional loops into streams and replacing anonymous classes with lambdas. That’s where real understanding comes in. 💬 In my learning journey, Java 8 felt like the point where Java truly became modern and expressive. #Java #Java8 #Programming #CleanCode #SoftwareDevelopment #Developers #LearningJourney #CareerGrowth
To view or add a comment, sign in
-
-
equals() and hashCode() Contract Most Java developers override equals(). But many forget about hashCode(). And that tiny mistake breaks one of the most important contracts in Java. This contract is defined in java.lang.Object and it directly affects how collections like HashMap and HashSet behave. Let’s break it down in simple terms: • If two objects are equal according to equals(), they must return the same hashCode(). • If two objects have the same hashCode(), they may or may not be equal. • Different objects can still share the same hash code — this is called a hash collision. Why does this matter? Because hash-based collections work in two steps. • First, the object’s hashCode() decides which bucket it goes into. • Then equals() is used to compare objects inside that bucket. Now imagine this situation. • You override equals(). • But you forget to override hashCode(). • Two objects that are logically equal generate different hash codes. • They get placed in different buckets. • equals() is never even called. The result? Collections start behaving incorrectly. Example: Set<User> users = new HashSet<>(); users.add(new User(1, "Alex")); users.add(new User(1, "Alex")); Expected result: Only one object should exist. Actual result: Both objects are stored. Why? Because the map never realized they were equal. The correct rule is simple: • Override equals() • Override hashCode() • Use the same fields in both methods Good engineers don’t just implement equality. They make sure objects behave correctly inside collections. That small design detail prevents some of the hardest bugs to debug in Java backend systems. #Java #BackendEngineering #JavaDeveloper #InterviewPrep #SoftwareEngineering #TechCareers
To view or add a comment, sign in
-
Explore related topics
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
Topic: Core Java