Java Practice — Palindrome Check Using Streams Today I revisited a small but powerful problem: checking if a string is a palindrome — this time using Java Streams for a more functional approach. Here’s the snippet I practiced: import java.util.stream.IntStream; public class PalindromeWithStreams { public static void main(String[] args) { String s = "madam"; boolean isPalindrome = IntStream.range(0, s.length() / 2) .allMatch(i -> s.charAt(i) == s.charAt(s.length() - i - 1)); System.out.println(isPalindrome ? "Palindrome" : "Not palindrome"); } } > Key takeaway: 1: IntStream.range(0, s.length() / 2) generates indices for only half the string. 2: .allMatch() ensures every pair of characters (from front and back) are equal. 3: Clean, concise, and expressive — a great example of functional programming in modern Java. #Java #Streams #CodingPractice #ProblemSolving #CleanCode #DevelopersJourney
How to Check Palindrome with Java Streams
More Relevant Posts
-
💡 == Operator vs. .equals() Method: Why Context Matters in Java 🧐 When comparing two variables or objects in Java, the choice between the == operator and the .equals() method is critical. They perform two fundamentally different types of comparisons! 1. The == Operator (Identity Comparison) What it compares: The == operator always compares memory addresses (references). Primitives: When used with primitives (int, char, boolean, etc.), it checks if the values stored in those memory locations are identical. Example: (5 == 5) is true. Objects: When used with objects (including String), it checks if the two variables refer to the exact same object in the Heap memory. Example: (obj1 == obj2) is only true if they point to the same memory location (same object ID). 2. The .equals() Method (Content Comparison) What it compares: The .equals() method is used to check for content equality. It determines if two objects are meaningfully equal based on their data. Default Behavior: Since this method is inherited from the base Object class, its default behavior is the same as == (checking references). The Power of Overriding: For almost all custom classes and core classes (like String), this method is overridden. String overrides .equals() to check if the sequence of characters (the content) is identical. You must override it in your custom classes (like Employee) to define when two distinct objects are considered equal based on their field values (id, name, etc.). Always use .equals() when comparing the content of objects, and reserve == for comparing primitives or checking if two variables are references to the exact same physical object. Thank you sir Anand Kumar Buddarapu,Saketh Kallepu,Uppugundla Sairam,Codegnan #Java #ProgrammingTips #OOP #ObjectEquality #SoftwareDevelopment #TechEducation
To view or add a comment, sign in
-
-
Understanding ClassCastException in Java Today I ran into a classic Java runtime exception: java.lang.ClassCastException 😅 At first, it seemed confusing — my code compiled perfectly, but crashed at runtime. After debugging, I realized the cause 👇 🧠 What it means ClassCastException occurs when we try to cast an object to a class, but the object is not actually an instance of that class. In simple terms: ✅ The code compiles fine ❌ But at runtime, Java refuses the cast and throws an exception 📦 Example Object obj = "Hello World"; // a String object Integer num = (Integer) obj; // trying to cast String to Integer This will throw: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer 🔹 How to Avoid Use instanceof before casting: if(obj instanceof Integer){ Integer num = (Integer) obj; } Use generics for type-safe collections: List<String> list = new ArrayList<>(); String str = list.get(0); // No cast needed 💬 Lesson Learned Even if the compiler is happy, the runtime JVM enforces type safety. Always ensure your object is of the correct type before casting. #Java #JavaDeveloper #SpringBoot #BackendDevelopment #Debugging #ErrorHandling #ProgrammingTips #SoftwareEngineering #CodeWithMe #LearningByDoing
To view or add a comment, sign in
-
💻 Today I Learned About Strings in Java In Java, Strings are a collection of characters enclosed within double quotes. They are objects and play a vital role in almost every Java program. There are two types of strings in Java: 🔹 Immutable Strings — Once created, they cannot be changed. Examples: name, date of birth, gender. 🔹 Mutable Strings — These can be modified. Examples: email ID, password, etc. For immutable strings, the class used is String. Strings created without using new keyword are stored in the String Constant Pool. Strings created using new keyword are stored in the Heap Memory. There are multiple ways to compare strings in Java: == → Compares references equals() → Compares values compareTo() → Compares character by character equalsIgnoreCase() → Compares values ignoring case differences Some commonly used String methods are: toLowerCase(), toUpperCase(), length(), charAt(), startsWith(), endsWith(), contains(), indexOf(), lastIndexOf(), and substring(). For mutable strings, we have two classes: StringBuffer → Synchronized, thread-safe, slower, suitable for multi-threaded environments. StringBuilder → Non-synchronized, not thread-safe, faster, suitable for single-threaded environments. ✨ Understanding strings is fundamental in Java, as they form the basis for text manipulation, data handling, and efficient memory management. #Java #String #Programming #Learning #JavaDeveloper #CodingJourney #TechLearning #SoftwareDevelopment #Immutable #Mutable #StringBuilder #StringBuffer
To view or add a comment, sign in
-
-
A quick Java tip about Strings In Java, string literals live in the String Pool — so identical strings share the same memory.That’s why this works: String s1 = "Hello"; String s2 = "Hello"; System.out.println(s1 == s2); // true ✅ But when you use a variable in concatenation, Java creates a new String in the heap, not from the pool: String part = "Hel"; String s3 = part + "lo"; System.out.println(s1 == s3); // false ❌ You can bring it back to the pool using .intern(): String s4 = (part + "lo").intern(); System.out.println(s1 == s4); // true ✅ #java #javadeveloper #javaprogramming #programming
To view or add a comment, sign in
-
✨ Difference Between String and StringBuffer In Java, both String and StringBuffer are used to handle text data. However, they differ in mutability, performance, and thread-safety — which makes choosing the right one important for your application. 💡 🧩 1️⃣ String Immutable → Once created, it cannot be changed. Every modification (like concatenation) creates a new object. Slower when performing many modifications. Not thread-safe (since it doesn’t change, this isn’t a problem). ⚙️ 2️⃣ StringBuffer Mutable → Can be modified after creation. Performs operations (append, insert, delete) on the same object. Faster for repeated modifications. Thread-safe → All methods are synchronized. Use String when the content never changes. Use StringBuffer when your program modifies text frequently — especially in multi-threaded applications. Thank you to Anand Kumar Buddarapu Sir for guiding me through this concept and helping me understand Java fundamentals more deeply. #Java #StringVsStringBuffer #CodingBasics #LearningJourney
To view or add a comment, sign in
-
-
Method overloading in Java is when a class has multiple methods with the same name but different parameters (either in number or type). This allows you to perform similar but slightly different tasks using the same method name, improving code readability and reducing redundancy. java example : class Calculator { // Adds two integers public int add(int a, int b) { return a + b; } // Adds three integers public int add(int a, int b, int c) { return a + b + c; } // Adds two double values public double add(double a, double b) { return a + b; } } public class Test { public static void main(String[] args) { Calculator calc = new Calculator(); System.out.println(calc.add(5, 10)); // calls add(int, int) System.out.println(calc.add(5, 10, 15)); // calls add(int, int, int) System.out.println(calc.add(5.5, 3.2)); // calls add(double, double) } } Here, the add method name is overloaded with different parameter lists. The compiler decides which method to call based on arguments given. Summary: Method overloading means same method name, different parameters.Improves code clarity; no need for different method names for similar actions.Compiler selects correct method based on argument types/count. #Java #MethodOverloading #ProgrammingConcepts #CodingTips #JavaBasics #JavaDevelopment #100DaysOfCode #Day6ofcoding
To view or add a comment, sign in
-
💡 String vs. StringBuffer: Why Mutability Matters in Java 📝 When working with text in Java, understanding the core difference between String and StringBuffer—Mutability—is key to writing efficient code. 1. String (Immutable) Immutability: Once a String object is created, its value cannot be changed. Behavior: Any operation that appears to modify a String (like concatenation using the + operator) actually creates a brand new String object in the Heap memory. Performance: This continuous creation of new objects is slow and consumes extra memory, especially when concatenating strings repeatedly within a loop. Use Case: Ideal for storing text that is constant and will not change (e.g., names, final identifiers, or configuration values). 2. StringBuffer (Mutable & Synchronized) Mutability: The value of a StringBuffer object can be changed in the same memory location. Behavior: Methods like append(), insert(), or delete() modify the sequence of characters directly within the existing object's allocated memory buffer. No new object is created for intermediate changes. Synchronization: StringBuffer is thread-safe (synchronized), meaning its methods can be safely used by multiple threads simultaneously without causing data corruption. Performance: Much faster than String for repeated text manipulation because it avoids the overhead of creating numerous temporary objects. Use Case: Ideal for text manipulation in a multi-threaded environment where concurrent access to the string data is a concern. The Golden Rule: If the text is constant, use String. If the text needs to be repeatedly changed (modified, appended, or inserted into), use StringBuffer. Thank you sir Anand Kumar Buddarapu,Saketh Kallepu,Uppugundla Sairam,Codegnan #Java #ProgrammingTips #String #StringBuffer #Codegnan
To view or add a comment, sign in
-
-
💡 Difference between == and .equals() in Java — and why it still confuses even experienced devs In Java, many developers think == and .equals() do the same thing... but they don’t 👇 ⚙️ == — The == operator compares memory references. It checks whether two variables point to the same object. String a = new String("Java"); String b = new String("Java"); System.out.println(a == b); // false 🚫 Here, a and b are two different objects, even if their content is identical. 🧠 .equals() — The .equals() method compares the logical content of the objects (when properly implemented). System.out.println(a.equals(b)); // true ✅ Both Strings contain “Java”, so the result is true. 🧩 Extra tip: Primitive types (int, double, boolean, etc.) use == because they don’t have .equals(). Objects (String, Integer, List, etc.) should use .equals() unless you need to check if they’re the same object in memory. 💬 Conclusion: Use == ➡️ to compare references Use .equals() ➡️ to compare values 💭 Have you ever fallen into this trap? Share your experience below 👇 #Java #Backend #CleanCode #DeveloperTips #SpringBoot #Programming #Learning
To view or add a comment, sign in
-
Here's a simple Java program that demonstrates basic string operations: public class StringExample { public static void main(String[] args) { String name = "John"; String greeting = "Hello, " + name + "!"; System.out.println(greeting); // Output: Hello, John! System.out.println(name.length()); // Output: 4 System.out.println(name.toUpperCase()); // Output: JOHN System.out.println(name.toLowerCase()); // } } Let's break it down with easy analogies: 1. *String Declaration*: `String name = "John";` Think of a string like a labeled box where you can store a message. Here, we're creating a box called `name` and putting the message "John" inside. 2. *String Concatenation*: `String greeting = "Hello, " + name + "!";` Imagine you're writing a greeting card. You're combining different pieces of paper (strings) to create a complete message. Here, we're combining "Hello, ", the contents of the `name` box (John), and "!" to create a new message. 3. *String Length*: `name.length()` Think of a ruler that measures the length of a piece of string. Here, we're asking for the length of the string "John", which is 4 characters. 4. *String Case Conversion*: `name.toUpperCase()` and `name.toLowerCase()` Imagine a keyboard with a caps lock button. `toUpperCase()` is like turning on the caps lock, and `toLowerCase()` is like turning it off. We're converting the string "John" to all uppercase (JOHN) or all lowercase (john). These are basic string operations in Java, and understanding these concepts will help you work with text data in your programs! What will be the output if we convert it into a lower case? Can anyone guess ? #Java #Coding #Programming
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
Tq Gopi V . This is very helpful to interview prospective.