Day 22 - Built-in Methods in Strings & compareTo() in Java Strings in Java are immutable, but the String class provides powerful built-in methods for efficient text handling. ✅ Commonly Used Methods in String length() → returns string length charAt(index) → access character by index substring() → extract part of a string toUpperCase() / toLowerCase() → case conversion trim() → remove leading & trailing spaces replace() → replace characters or substrings contains() → check substring presence startsWith() / endsWith() → prefix & suffix checks equals() / equalsIgnoreCase() → content comparison 🔹 compareTo() Method Used to compare strings lexicographically (dictionary order). String a = "Apple"; String b = "Banana"; a.compareTo(b); // negative value 🔸 Return Values 0 → both strings are equal > 0 → first string is greater < 0 → first string is smaller 📌 Comparison is based on Unicode values and checks characters one by one. 🔹 compareTo() vs equals() compareTo() → ordering & sorting equals() → equality check 🔑 Key Takeaway ✔ Use equals() to check equality ✔ Use compareTo() for sorting and ordering logic #Java #String #CoreJava #Programming #JavaDeveloper #Coding #SoftwareEngineering
Java String Methods & compareTo() Explained
More Relevant Posts
-
Do u know ? String.length() ( length method of string class) is sometimes misleading in Java… you know that? 👀 For example, it counts length as 2 for a single emoji. Try this: Java Copy code String name = "hi😅"; System.out.println(name.length()); It shows 4. At first I was like… how? "h" = 1 "i" = 1 "😅" = 1 So shouldn’t it be 3? Here’s the reason. In Java, String.length() does NOT count characters the way humans see them. It counts UTF-16 code units. Java internally uses UTF-16 encoding. Basic rule: Normal characters (a, b, c, h, i) → 1 code unit Some special characters (like emojis 😅) → 2 code units These are called Supplementary Characters. They are represented using something called a Surrogate Pair. Let’s break "hi😅": h → 1 i → 1 😅 → 2 Total = 4. That’s why length() prints 4. Internally, 😅 has Unicode: U+1F605 UTF-16 can’t store it in one 16-bit value. So it splits into: High surrogate Low surrogate So Java actually sees: hi😅 as h i \uD83D \uDE05 Total = 4. If you want actual character count (human count), use: name.codePointCount(0, name.length()); That returns 3. I recently found this again while revising my basics. I had completely forgotten this detail. Sometimes going back to fundamentals teaches more than learning something new. How many of you knew this? 👀 #java #String #codenodes #coding #developing #android
To view or add a comment, sign in
-
1980. LeetCode Daily Challenge Solved | Find Unique Binary String Solved today’s Find Unique Binary String problem using an elegant Diagonal Construction (Cantor’s Argument) approach. 🔹 Key Idea: Instead of generating all possible binary strings, we construct a new string by flipping the diagonal bits of the given strings. This guarantees the new string differs from every string in the array at least in one position. 🔹 Approach: Traverse each string i Check the i-th character of nums[i] Flip it (0 → 1, 1 → 0) Build a new binary string from these flipped bits This ensures the generated string cannot match any existing string in the input. 🔹 Time Complexity: O(n) 🔹 Space Complexity: O(n) 💻 Java Implementation: class Solution { public String findDifferentBinaryString(String[] nums) { char[] res = new char[nums.length]; for (int i = 0; i < nums.length; i++) { char c = nums[i].charAt(i); res[i] = (c == '0') ? '1' : '0'; } return new String(res); } } ⚡ Result: ✔ Runtime: 0 ms (Beats 100%) ✔ Memory: 42.86 MB Consistency with daily problems builds strong problem-solving intuition. On to the next challenge! #LeetCode #DSA #Java #CodingPractice #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
🔍 Understanding String vs StringBuilder vs StringBuffer in Java 📌 1️⃣ String String objects are immutable, meaning once a string is created, its value cannot be changed. Any modification results in the creation of a new object in memory. Because of this immutability, strings are thread-safe by default and are stored in the String Pool for memory optimization. ✔ Best used for fixed or constant text values such as messages, configuration keys, or identifiers. 📌 2️⃣ StringBuilder StringBuilder is a mutable class, allowing modifications to the same object without creating new ones. This makes it much faster for frequent string operations like concatenation or modification. However, it is not thread-safe, which means it should be used mainly in single-threaded environments. ✔ Best used when performing multiple string modifications in loops or intensive operations. 📌 3️⃣ StringBuffer StringBuffer is also mutable, similar to StringBuilder, but it is synchronized, making it thread-safe. Because synchronization adds overhead, it is generally slower than StringBuilder. ✔ Best used in multi-threaded applications where multiple threads may modify the same string. 💡 Key Takeaway • Use String for immutable and constant values • Use StringBuilder for fast string manipulation in single-threaded programs • Use StringBuffer when thread safety is required Thank you Anand Kumar Buddarapu Sir for your guidance and motivation. Learning from you was really helpful! 🙏 Uppugundla Sairam sir Saketh Kallepu sir #Java #Programming #SoftwareDevelopment #JavaDeveloper #CodingConcepts #LearningJava
To view or add a comment, sign in
-
-
💡 While implementing string permutations in Java, I noticed a small detail about 'substring()' that many developers overlook. Here’s the example I was working on. Find all permutations of "ABC". Total permutations: 3! = 6 ABC ACB BAC BCA CAB CBA The idea behind the algorithm is simple. At each step we: • pick one character • append it to the answer • recurse on the remaining characters A common Java implementation looks like this: public static void permutation(String str, String ans) { if (str.isEmpty()) { System.out.println(ans); return; } for (int i = 0; i < str.length(); i++) { char current = str.charAt(i); String newStr = str.substring(0, i) + str.substring(i + 1); permutation(newStr, ans + current); } } Initial call: permutation("ABC", "") While walking through the code, an interesting Java behavior appears. Consider this case: str = "ABC" i = 2 // character 'C' The code executes: str.substring(0, 2) → "AB" str.substring(3) → "" Why doesn't `substring(3)` throw an error? Because in Java: "#substring(beginIndex)" returns the substring from #beginIndex to the end of the string. If: beginIndex == str.length() Java simply returns an empty string, not an exception. So the expression becomes: "AB" + "" Result: "AB" This small language detail allows the permutation logic to work without extra boundary checks. Sometimes the most useful insights while solving DSA problems come from understanding how the programming language behaves at edge cases. #Java #DSA #Recursion #Algorithms #CodingInterview
To view or add a comment, sign in
-
-
𝙒𝙝𝙮 𝙙𝙤 𝙎𝙩𝙖𝙩𝙞𝙘 𝘽𝙡𝙤𝙘𝙠𝙨 𝙚𝙭𝙚𝙘𝙪𝙩𝙚 𝙤𝙣𝙡𝙮 𝙤𝙣𝙘𝙚 𝙞𝙣 𝙅𝙖𝙫𝙖 ? After my previous post on Order of Execution, a follow-up question naturally came to mind: 👉 Why does a Static Block execute only once in Java? The answer lies in 𝐂𝐥𝐚𝐬𝐬 𝐋𝐨𝐚𝐝𝐢𝐧𝐠. 📝 Key Concept In Java, Static Blocks belong to the Class, not to Objects. When the JVM loads a class into memory, it performs class initialization. During this phase, all static variables and static blocks are executed. And here’s the important part: ➡️A class is loaded only once by the JVM ➡️ Therefore Static Blocks execute only once 👨💻 Example 𝐜𝐥𝐚𝐬𝐬 𝐓𝐞𝐬𝐭 { 𝐬𝐭𝐚𝐭𝐢𝐜 { 𝐒𝐲𝐬𝐭𝐞𝐦.𝐨𝐮𝐭.𝐩𝐫𝐢𝐧𝐭𝐥𝐧("𝐒𝐭𝐚𝐭𝐢𝐜 𝐛𝐥𝐨𝐜𝐤 𝐞𝐱𝐞𝐜𝐮𝐭𝐞𝐝"); } 𝐓𝐞𝐬𝐭() { 𝐒𝐲𝐬𝐭𝐞𝐦.𝐨𝐮𝐭.𝐩𝐫𝐢𝐧𝐭𝐥𝐧("𝐂𝐨𝐧𝐬𝐭𝐫𝐮𝐜𝐭𝐨𝐫 𝐞𝐱𝐞𝐜𝐮𝐭𝐞𝐝"); } 𝐩𝐮𝐛𝐥𝐢𝐜 𝐬𝐭𝐚𝐭𝐢𝐜 𝐯𝐨𝐢𝐝 𝐦𝐚𝐢𝐧(𝐒𝐭𝐫𝐢𝐧𝐠[] 𝐚𝐫𝐠𝐬) { 𝐧𝐞𝐰 𝐓𝐞𝐬𝐭(); 𝐧𝐞𝐰 𝐓𝐞𝐬𝐭(); 𝐧𝐞𝐰 𝐓𝐞𝐬𝐭(); } } 📌 𝐎𝐮𝐭𝐩𝐮𝐭 𝐒𝐭𝐚𝐭𝐢𝐜 𝐛𝐥𝐨𝐜𝐤 𝐞𝐱𝐞𝐜𝐮𝐭𝐞𝐝 𝐂𝐨𝐧𝐬𝐭𝐫𝐮𝐜𝐭𝐨𝐫 𝐞𝐱𝐞𝐜𝐮𝐭𝐞𝐝 𝐂𝐨𝐧𝐬𝐭𝐫𝐮𝐜𝐭𝐨𝐫 𝐞𝐱𝐞𝐜𝐮𝐭𝐞𝐝 𝐂𝐨𝐧𝐬𝐭𝐫𝐮𝐜𝐭𝐨𝐫 𝐞𝐱𝐞𝐜𝐮𝐭𝐞𝐝 👉 Notice something interesting? Even though three objects are created, the Static Block runs only once. 📍Simple way to remember Class loads once ➡️ Static block runs once Object created multiple times ➡️Constructor runs multiple times Understanding these small JVM behaviors makes many Java interview questions much easier. Did you know this earlier? Or is this something you recently discovered? Let’s discuss in the comments 💬 #Java #JavaDeveloper #JavaBackend #TechJourney #TechInsights #LearnBySharing #Programming #JavaConcepts #JVM
To view or add a comment, sign in
-
Day 42 of My DSA Journey 🚀 | Basic String Operations in Java 🧠 Summary: Demonstrate common string operations in Java such as comparison, length calculation, substring extraction, case conversion, and character traversal. 💡 Key Concepts: • String immutability • == vs .equals() comparison • Case-insensitive comparison • Built-in string methods • Character iteration 🧠 Approach: This program explores several commonly used String methods. Step-by-step operations: • Declaration Two ways to create strings: → Using string literal → Using the new keyword • String Comparison → == checks if two references point to the same object. → .equals() compares actual string values. → .equalsIgnoreCase() compares values ignoring case differences. • String Methods → length() returns number of characters. → charAt(index) retrieves character at given position. → substring(start,end) extracts part of a string. → toUpperCase() converts characters to uppercase. → toLowerCase() converts characters to lowercase. → contains() checks if a substring exists. • String Traversal → Iterate through the string using a loop and access characters using charAt(). 🔧 Practical Usage / Why This Matters: • Processing user input in applications • Validating text-based data • Parsing messages or logs • Formatting and transforming text data 🌱 What I Learned Today: I strengthened my understanding of Java String methods and how object comparison differs from value comparison. 🙌 If you're preparing for placements, let’s connect and grow together! #dsa #datastructures #algorithms #java #javadeveloper #javaprogramming #dsainjava #strings #stringalgorithms #codinginterview #leetcode #geekforgeeks #codingpractice #interviewpreparation #100daysofcode #developerjourney #softwaredeveloper #problemSolving
To view or add a comment, sign in
-
-
Day 8-What I Learned In a Day Today, I learned about Primitive and Non-Primitive Variables in Java. Primitive Variables: Primitive variables store the actual data value directly in memory. They are basic built-in data types and store only a single value. Primitive Data Types: • byte • short • int • long • float • double • char • boolean Syntax: For Single Variable: PrimitiveDatatype varname; For multiple Variable: PrimitiveDatatype v1,v2; Non-Primitive Variables: Non-primitive variables store the reference (address) of an object, not the actual value. They can store single or multiple values and provide more functionality. Non-Primitive Types: • String • Arrays • Classes • Interfaces Syntax: For Single Variable: Non-PrimitiveDatatype varname; For multiple Variable: Non-PrimitiveDatatype v1,v2; Somebody Can relate the Songs +Coding= 👌 (Like the Song What I Played) #java # javaprogramming #coding #DailyGrowth #consistency
To view or add a comment, sign in
-
🚀 Why is .length() in Java So Fast? Many developers use .length() every day — but have you ever wondered why it runs so fast? Let’s break it down. 🧠 For Arrays int[] arr = {1, 2, 3, 4}; System.out.println(arr.length); For arrays, .length is not even a method — it’s a field. When an array is created in Java: => Its size is stored internally as metadata. => The JVM stores the length alongside the array object in memory. => Accessing arr.length is just reading an integer field. 👉 Time Complexity: O(1) No iteration. No calculation. 🧠 For Strings String str = "Hello"; System.out.println(str.length()); For String, .length() is a method — but it’s still O(1). Why? => Because inside the String class: => The length is stored as a field. => The method simply returns that stored value. Conceptually, it looks like this: public int length() { return value.length; } No looping. No counting characters. ⚡ Why This Matters If .length() had to iterate over elements: => Checking size inside a loop would become expensive. => Many common algorithms would degrade in performance. => Instead, Java ensures length access is constant time. #Java #JVM #BackendDevelopment #InterviewPrep #SoftwareEngineering #ProgrammingInternals
To view or add a comment, sign in
-
Why "Thinking in Objects" is the Ultimate Superpower in Java 🚀 If you are just starting your journey into Object-Oriented Programming (OOP), the terminology can feel like a foreign language. "Classes," "Objects," "Methods," "Instances"—it’s a lot to take in. But if you look at this illustration, you’ll see that coding isn’t just about syntax; it’s about architecture. 1. The Class: Your Architectural Blueprint 📜 The left side of the image shows the Class House. In Java, a class is not a thing; it is a template. It defines: Attributes (Fields): Like int windows and String color—these are the characteristics every house will have. Behaviors (Methods): Like void build()—this is what the house (or the system) can do. 2. The Process: Instantiation 🏗️ Notice the arrow in the middle? That’s the "Magic Moment" called Instantiation. When you use the new keyword in Java, you are telling the computer: "Take this blueprint and actually build it in memory!". 3. The Objects: The Real-World Result 🏡 On the right, we see three distinct Objects: Object 1: A Red House. Object 2: A Yellow House. Object 3: A Blue House. Here is the key takeaway: Even though they all came from the exact same blueprint, they are unique. They each have their own "state" (different colors), but they share the same "identity" (they are all Houses). Why does this matter? By using this model, Java allows us to write code that is: ✅ Reusable: Write the blueprint once, create a thousand houses. ✅ Organized: Keep data and behavior in one neat package. ✅ Scalable: It’s much easier to manage a neighborhood when you have a standard plan to follow. What was the "Aha!" moment that helped you finally understand OOP? Drop a comment below! 👇 #Java #SoftwareEngineering #CodingLife #OOP #TechEducation #WebDevelopment
To view or add a comment, sign in
-
-
💻 LeetCode Daily Challenge – Find Unique Binary String (Problem 1980) Today's LeetCode Daily Challenge was "Find Unique Binary String". 📌 Problem Summary We are given n unique binary strings of length n. The task is to construct a binary string of length n that does not exist in the given list. 🔎 Approach 1: HashSet + Generate All Possibilities Idea: Store all given strings in a HashSet. Generate binary numbers from 0 to 2^n - 1. Convert each number to a binary string of length n. Return the first string not present in the set. Time Complexity: O(2^n) Space Complexity: O(n) 🔎 Approach 2: Backtracking Idea: Recursively generate all binary strings of length n. Check if the generated string exists in the set. Return the first missing string. Time Complexity: O(2^n) Space Complexity: O(N) 🚀 Approach 3 (Optimal – Cantor’s Diagonalization) This elegant approach guarantees a unique string. Idea: Look at the i-th character of the i-th string. Flip the bit (0 → 1 or 1 → 0). Build a new string using these flipped bits. This ensures the constructed string differs from every string at least at one position. Time Complexity: O(n) Space Complexity: O(n) 💡 Java Implementation (Optimal Approach) class Solution { public String findDifferentBinaryString(String[] nums) { StringBuilder res = new StringBuilder(); for(int i = 0; i < nums.length; i++){ char ch = nums[i].charAt(i); if(ch == '0') res.append('1'); else res.append('0'); } return res.toString(); } } 📚 Key Takeaway This problem demonstrates a clever application of Cantor’s Diagonalization, allowing us to construct a guaranteed unique binary string in linear time. #LeetCodeDaily #DSA #Java #ProblemSolving #CodingPractice #SoftwareEngineering
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