Java Program: Write a program to check whether the given string is a palindrome using a StringBuilder. Explanation: To check for a palindrome using `StringBuilder`, the process is simplified by leveraging the class's mutable nature and built-in utilities: Explanation: To check for a palindrome using StringBuilder, the process is simplified by leveraging the class's mutable nature and built-in utilities: Initialization: We wrap the original String inside a StringBuilder object. Reversal: The StringBuilder class provides a reverse() method that efficiently flips the character sequence in place. Comparison: Since StringBuilder does not override the equals() method from the Object class (it compares memory addresses rather than content), we must convert the reversed sequence back into a String using toString(). Case Sensitivity: In the example, equalsIgnoreCase() is used to ensure that words like "Radar" or "madam" are still identified as palindromes despite the capital "R". Key Points Summary: A palindrome reads the same forward and backwards. StringBuilder is preferred over String for reversals because String is immutable, meaning every change creates a new object in memory. Always remember to use .toString() before comparing the reversed StringBuilder to the original String.
Vinayak Titti’s Post
More Relevant Posts
-
Java Program: Find the second largest number from an array. Summary of the Logic The code employs a two-tier comparison strategy within a single for-each loop to track the top two values: The Primary Condition (if (num > largest)): If the current number is greater than the current maximum, the previous largest is moved down to secondLargest. The current number then becomes the new largest. The Secondary Condition (else if (num > secondLargest && num != largest)): If the number is not larger than the maximum, the code checks if it is larger than the current secondLargest. The num != largest clause is crucial: it prevents a duplicate of the maximum (like the second $87$ in your array) from being counted as the second largest value. Execution on Your Array Given the array {10,20,43,87,44,87,65,2,1} {10,20,43,87,44,87,65,2,1}, the logic flows as follows: Initial Hits: $10, 20, 43, and \87$ all trigger the first if block, updating largest and pushing the previous max to secondLargest. **Encounters $44**: It fails the first `if` (since \44 < 87) but passes the `else if` (since \44 > 43). `secondLargest` becomes \44$. **Encounters Second $87**: It fails the first `if` (\87 \ngtr 87) and the `else if` (\87 \neq 87$ is false). It is ignored. **Encounters $65**: It fails the first `if` (\65 < 87) but passes the `else if` (\65 > 44). `secondLargest` is updated to \65$. Encounters $2, 1$: Both fail all conditions. Final Output After iterating through all elements, the program will print: First largest number is: $87$ SecondLargest number is: $65$
To view or add a comment, sign in
-
-
🚀 Java Enums – Why not just Classes? 🔹 Ever wondered why we use enum instead of creating constant classes or interfaces? Enums are not just "fancy constants" – they are type‑safe, singleton‑like objects with hidden powers. 💡 Hook: "Imagine traffic lights without enums – everywhere you’d see 'RED', 'GREEN', 'YELLOW' strings… and a single typo could crash the entire system!" ✅ Why Enums over Classes? Type Safety: Compiler ensures only valid values (no random strings). Singleton Guarantee: Each enum constant is a single instance (no duplicates). Readable Code: TrafficLight.RED looks cleaner than "RED" string. Extra Features: Enums can have constructors, methods, and even implement interfaces. 🔍 Internal Working of Enums Every enum internally extends java.lang.Enum. Enum constants are actually static final objects created at class load time. You can add fields & methods → each constant can have its own behavior. Reflection or cloning cannot create new instances → immutability ensured. 🧩 Example: enum TrafficLight { RED("Stop"), GREEN("Go"), YELLOW("Wait"); private String action; TrafficLight(String action) { this.action = action; } public String getAction() { return action; } } 👉 Here, each constant is an object with its own property.
To view or add a comment, sign in
-
-
Java tip: starting from Java 14, you can use switch expressions - the code becomes shorter and cleaner with logic involving multiple branches. Previously, you had to write it cumbersingly with break and assignments: => Old method String season; switch (month) { case 12: case 1: case 2: season = "Winter"; break; case 3: case 4: case 5: season = "Spring"; break; default: season = "Invalid"; } Now, you can immediately return the value from the switch: => New switch expression String season = switch (month) { case 12, 1, 2 -> "Winter"; case 3, 4, 5 -> "Spring"; default -> "Invalid"; }; What does this provide: - less code - no risk of forgetting to use break - it reads like an expression, not a "mini-procedure"
To view or add a comment, sign in
-
-
Top 5 Causes of Memory Leaks in Java 🚀 Memory leaks in Java may not cause immediate crashes, but they can significantly degrade performance over time. These leaks occur when objects are no longer needed but are still referenced, preventing Garbage Collection from cleaning them up. The top causes of memory leaks in Java include: 1. Unused objects still referenced – Objects remain in memory due to active references. 2. Static collections – Data continues to grow because static variables persist for the entire application lifecycle. 3. Incorrect equals() and hashCode() – This can lead to duplicate entries in collections like HashMap. 4. Unclosed resources – Resources such as database connections, streams, or sessions are not properly closed. 5. Non-static inner classes – These classes hold implicit references to outer class objects. Understanding these causes can help developers write more efficient Java applications.
To view or add a comment, sign in
-
-
In Java, the immutability of the String class means that once a String object is created, its value cannot be changed. Any attempt to modify it—such as using methods like concat(), replace(), or substring()—results in the creation of a new String object rather than altering the original. Here are the key reasons for String immutability: ✔️**Security**: Strings often hold sensitive data, including usernames, passwords, URLs, file paths, and network connections. If Strings were mutable, malicious code could change their values after they have been used in security checks. For example: String url = "https://secure.com"; // If mutable, another thread could change it to "http://malicious.com" ✔️**Thread-Safety**: Immutable objects are inherently thread-safe, allowing multiple threads to share the same String without requiring synchronization. This is particularly important in multithreaded environments, such as web servers. ✔️**String Pool Optimization**: Java maintains a String Constant Pool to optimize memory usage. If Strings were mutable, changing one reference could impact all references in the pool, leading to inconsistencies. For example: String a = "Hello"; String b = "Hello"; // Both point to the same object in the pool ✔️**Caching and Performance**: The immutability of Strings allows their hash code to be cached after the first calculation, making them efficient as keys in hash-based collections like HashMap and HashSet. ✔️**Predictable Behavior**: Immutability guarantees that once a String is created, it will consistently represent the same sequence of characters, simplifying debugging and code reasoning. 🟢 In summary, Java strings are immutable to ensure security, thread-safety, memory efficiency, performance, and predictable behavior.
To view or add a comment, sign in
-
There is no silver bullet when choosing between LinkedList and ArrayList in Java. I’m currently studying DSA for coding interviews, and revisiting the trade-offs between these two classes has been a great refresher. 𝐋𝐢𝐧𝐤𝐞𝐝𝐋𝐢𝐬𝐭 is an implementation of a doubly-linked list. It stores each record in a node consisting of the data and two pointers. • The Trade-off: You can insert or delete records in O(1) time because you just change the pointers to the new address, but finding data takes O(n) due to link traversing. It also uses more memory to store those extra pointers. • Best Use Case: When you need to frequently insert and delete from the beginning or end of a collection. A classic example is building an "Undo" feature where you constantly save and remove the latest edit. 𝐀𝐫𝐫𝐚𝐲𝐋𝐢𝐬𝐭 uses an internal array that the JVM dynamically resizes when needed. The records are stored in contiguous data blocks, providing excellent memory locality and exploiting CPU cache for fast access. • The Trade-off: You get O(1) read access using indexes. However, insertion and deletion can be O(n) in the worst case because the JVM has to shift elements to make room, or when the array has reach its capacity, copy and rewrite the old data to a new allocated array. • Best Use Case: When you need to iterate over large datasets quickly, such as generating a monthly financial report from thousands of transactions. You can read more about them in the official Java 25 docs: 🔗 LinkedList: https://lnkd.in/d_kVgPpW 🔗 ArrayList: https://lnkd.in/dkpzZZxf
To view or add a comment, sign in
-
-
Java Program: Write a program to remove duplicates from an array. Core Functionality The program processes an integer array containing several duplicate values (such as 65 and 87). It utilizes a Set data structure to filter out these duplicates and then attempts to sort the result before printing it to the console. Step-by-Step Execution Initialization: An integer array named array is defined with the values {10, 20, 65, 87, 44, 87, 65, 2, 1}. Deduplication: A LinkedHashSet<Integer> is instantiated. A Set is a collection that, by definition, cannot contain duplicate elements. The program iterates through the array using an enhanced for loop. For each number, it checks if the set already contains the value. If not, it adds the value to the set. Note: Since a Set automatically rejects duplicates, the if(!set.contains(num)) check is technically redundant but safe. Sorting: The code calls Arrays.sort(set). Technical Note: In standard Java, Arrays.sort() is designed for arrays, not Collections like a Set. To make this specific code snippet functional in a real environment, the set would typically be converted back into a list or an array before sorting, or a TreeSet would be used to handle sorting automatically. Output: Finally, the program prints the resulting collection to the console. Comparison of Collection Types used Summary of Key Points Purpose: To extract unique elements from a dataset and sort them. Mechanism: Leverages the unique property of the Java Collections Framework (specifically Set) to handle duplicate logic automatically. Result: The original array of 9 elements is reduced to 7 unique elements: [1, 2, 10, 20, 44, 65, 87].
To view or add a comment, sign in
-
-
Starting from JDK25, you can write a simple Java entry point (JVM main method) program as, ``` void main() { IO.println("Hello, World!"); } ``` and more interactively, ``` void main() { String name = IO.readln("Please enter your name: "); IO.print("Pleased to meet you, "); IO.println(name); } ``` 1. Both the above variants are single-file source-code programs (compact source file) 2. Automatically imports commonly used base packages such as java.io, java.math, and java.util via automatic import of the java.base module 3. To evolve a compact source file into a ordinary source file, all you need to do is wrap its fields and methods in an explicit class declaration and add an import declaration Assuming this program is in the file HelloWorld.java, you can run it directly with the source-code launcher: $ java HelloWorld.java Previously, the above simple Java program would look like below, ``` public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } } ``` where, 1. "public" access modifier & "class" declaration provides for proper encapsulation boundaries 2. "static" modifier provides for a class-object modelling 3. String[] args parameter provides for the program execution inputs 4. System.out.println provides utilities for printing to the console More details in the JEP512 - https://lnkd.in/g5JBAWwe advocating the simplification
To view or add a comment, sign in
-
-
🚀🎊Day 84 of 90 – Java Backend Development ✨🎆 In Java, the final keyword is a non-access modifier used to restrict the user from changing the state of a variable, method, or class. Think of it as a way to achieve immutability and prevent inheritance or overriding. 👉 1. Final variables: When you declare a variable as final, its value cannot be modified once it has been initialized. It essentially becomes a constant. i) Local Variables: Must be initialized before use and cannot be reassigned. ii) Instance Variables: Can be initialized during declaration or inside the constructor. iii) Static Variables: Often used to create "Class Constants" (e.g., public static final double PI = 3.14159;). Note: For objects, final means the reference cannot change. You can still modify the internal state (fields) of the object, but you cannot point the variable to a new object. 👉2. Final methods: A method declared with the final keyword cannot be overridden by subclasses. i) Usage: Use this when you want to ensure that the specific implementation of a method remains consistent across all subclasses. ii) Performance: Historically, the compiler could optimize final methods through inlining, though modern JVMs often do this automatically regardless. 👉 3. Final classes: A class declared as final cannot be subclassed (inherited). i) Security & Integrity: Many standard Java library classes are final, such as String, Integer, and other wrapper classes. This prevents developers from creating a "fake" version of a String that might behave maliciously. ii) Implicitly Final: If a class is final, all of its methods are implicitly final as well. 👉 Code example: final class Vehicle { // Cannot be inherited final int SPEED_LIMIT = 90; // Constant final void drive() { // Cannot be overridden System.out.println("Driving at " + SPEED_LIMIT); } } #FinalKeyword #Immutable #Performance #Java #Constant
To view or add a comment, sign in
-
-
🚀🎊Day 81 of 90 – Java Backend Development ✨🎆 In Java, Wrapper classes provide a way to use primitive data types (like int, boolean, etc.) as objects. Since Java is an object-oriented language, many of its most powerful features—like Collections (ArrayList, HashMap) and Generics—only work with objects, not primitives. 👉Why do we need them? Primitives are fast and memory-efficient, but they lack the "bells and whistles" of objects. Wrapper classes bridge this gap by "wrapping" a primitive value inside an object. i) Collections Support: You cannot create an ArrayList<int>, but you can create an ArrayList<Integer>. ii) Utility Methods: They provide handy methods for conversion (e.g., converting a String to an int). iii) Null Values: Primitives must have a value; Wrapper objects can be null, which is useful in databases or web forms. 👉Autoboxing and unboxing Modern Java (since version 5) handles the conversion between primitives and wrappers automatically. This makes your code much cleaner. 1. Autoboxing The automatic conversion of a primitive type to its corresponding wrapper class. int primitive = 10; Integer wrapper = primitive; // Autoboxing 2. Unboxing The reverse process: converting a wrapper object back into a primitive. Integer wrapper = 20; int primitive = wrapper; // Unboxing 👉 Useful features: Wrapper classes aren't just containers; they are packed with static utility methods. For example: i) Parsing Strings: int x = Integer.parseInt("123"); ii) Constants: Integer.MAX_VALUE or Double.NaN. iii) Type Conversion: myInteger.doubleValue(); #Wrapperclass #PrimitiveDataType #Autoboxing #Autounboxing
To view or add a comment, sign in
-
More from this author
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