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
Java String Length Method Misconception
More Relevant Posts
-
💡 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
-
-
🚨 Java Myth Buster: “Finally block always executes” — Really? 🤔 Most developers confidently say: 👉 “Yes, finally always runs!” ❌ Let’s break that myth with a real example 👇 --- 💻 Code Example: public class Test { public static void main(String[] args) { try { System.out.println("Inside try"); System.exit(1); } finally { System.out.println("Inside finally"); } } } --- 📌 Output: Inside try 😳 Wait… where is the "finally" block? --- 💡 Explanation (Simple & Clear): When "System.exit(1)" is executed: - 🚫 JVM shuts down immediately - 🚫 No further code executes - 🚫 "finally" block is completely skipped --- 🔢 Understanding Exit Codes: - "System.exit(0)" → Normal termination ✅ - "System.exit(1)" → Abnormal termination ❌ 👉 But important point: Both will skip the "finally" block! --- ⚠️ So when does finally NOT execute? ✔️ When JVM is forcefully terminated ✔️ Using "System.exit()" ✔️ JVM crash / system failure ✔️ Infinite loop (control never reaches finally) --- 🧠 Interview Takeaway: 👉 “Finally block executes in almost all cases, except when JVM terminates abruptly like with System.exit().” --- 🔥 This is one of the most asked tricky Java interview questions! 💬 Did you know this before? #Java #JavaDeveloper #CodingInterview #Programming #TechTips #Developers #InterviewQuestions #JavaBasics
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
-
-
🚀 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
-
𝙒𝙝𝙮 𝙙𝙤 𝙎𝙩𝙖𝙩𝙞𝙘 𝘽𝙡𝙤𝙘𝙠𝙨 𝙚𝙭𝙚𝙘𝙪𝙩𝙚 𝙤𝙣𝙡𝙮 𝙤𝙣𝙘𝙚 𝙞𝙣 𝙅𝙖𝙫𝙖 ? 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 22 – Reference Variables in Java Today I explored an important concept in Object-Oriented Programming — Reference Variables. Unlike primitive variables, reference variables store the address of an object, not the actual value. 🔹 What is a Reference Variable? A reference variable is a non-primitive variable that refers to an object created from a class. It is declared using the class name. Syntax: ClassName referenceVariable; Initialization- referenceVariable = new ClassName(); Or both together: ClassName referenceVariable = new ClassName(); Here: ClassName → Name of the class referenceVariable → Object reference new → Keyword used to create an object ClassName() → Constructor 🔹 Example class Demo5 { int x = 100; int y = 200; } class MainClass3 { public static void main(String[] args) { Demo5 d1 = new Demo5(); System.out.println("x = " + d1.x); System.out.println("y = " + d1.y); System.out.println("modifying x & y"); d1.x = 300; d1.y = 400; System.out.println("x = " + d1.x); System.out.println("y = " + d1.y); } } Output: x = 100 y = 200 modifying x & y x = 300 y = 400 🔹 Important Observation When we write: Demo5 d1 = new Demo5(); Java performs three things: 1️⃣ Creates a reference variable (d1) 2️⃣ Creates a new object in memory 3️⃣ Stores the object reference in the variable #Java #CoreJava #JavaFullStack #OOP #Programming #BackendDevelopment #LearningInPublic #SoftwareDevelopment
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
-
-
Day 16: VarArgs and Recursion 🔸Variable Arguments (Varargs): A function with varargs can be created in Java using the following syntax: public static void foo(int... arr) { // arr is available here as int[] arr } foo can be called with zero or more arguments, like this: foo(7) foo(7, 8, 9) foo(1, 2, 7, 8, 9) We can also create a function bar like this: public static void bar(int a, int... arr) { // code } bar(1) bar(1, 2) bar(1, 7, 9, 11) 🔸Example static int avg(int... arr) { int result = 0; int avg = 0; for (int element : arr) { result += element; } avg = result / arr.length; return avg; } public static void main(String[] args) { System.out.println("The average is " + avg(3, 5, 8, 7)); } 🔸Recursion A function in Java can call itself. Such calling of a function by itself is called recursion. 🔸Syntax of Recursion in Java: returnType functionName(parameters) { if(base_condition) { return value; } else { return functionName(smaller_problem); } } 🔸Example: Factorial Using Recursion: static int factorial(int n) { if(n == 0 || n == 1) // base condition return 1; else return n * factorial(n - 1); } public static void main(String[] args) { int result = factorial(5); System.out.println(result); } #Java #Programming #SoftwareDevelopment #JavaDeveloper #Coding #ProblemSolving #LearningJourney #ComputerScience #KodNest
To view or add a comment, sign in
-
-
Brushing up my OOPS concepts today and revisited an interesting point about 'Runtime Polymorphism' and 'Inheritance concept' in Java. In runtime polymorphism, the JVM decides which overridden method to execute during runtime based on the actual object being created, not the reference type. This usually happens when: - A child class inherits from a parent class - The child overrides a method from the parent class - A parent reference variable refers to a child class object Example: Parent ref = new Child(); Here, the overridden method in the Child class will be executed, even though the reference type is Parent. However, things work differently with variables. If both parent and child classes define a variable with the same name and type, the variable accessed depends on the reference type, not the object type. This is because variables do not participate in runtime polymorphism (they follow variable hiding). For example: class Parent { int a = 10; } class Child extends Parent { int a = 20; } public class Test { public static void main(String[] args) { Parent ref = new Child(); System.out.println(ref.a); } } In this code, the output will be 10, because the reference type is Parent, so it accesses the Parent class variable. This behavior is known as variable hiding. Always interesting to revisit these core concepts — they look simple but have subtle behaviors that are important for writing clean and predictable Java code. #Java #OOPS #Polymorphism #Learning #SoftwareEngineering #SDET #Coding #Inheritance
To view or add a comment, sign in
-
Tackling the "Silent Overflow" in Java 🛑🔢 I recently worked through LeetCode #7: Reverse Integer, and it was a fantastic deep dive into how Java handles 32-bit integer limits and the dangers of "silent overflows." The Problem: Reverse the digits of a signed 32-bit integer. If the reversed number goes outside the 32-bit signed range of [-2^{31}, 2^{31} - 1], the function must return 0 The "Asymmetry" Challenge: In Java, Integer.MIN_VALUE is -2,147,483,648, while Integer.MAX_VALUE is 2,147,483,647. The negative range is one unit larger than the positive range due to Two's Complement arithmetic. This creates a massive trap: using Math.abs() on the minimum value will actually overflow and remain negative! My Optimized Solution Strategy: I implemented a two-pronged approach to handle these edge cases efficiently: 1️⃣ Pre-emptive Boundary Filtering: I added a specific optimization check at the very beginning: if(x >= Integer.MAX_VALUE - 4 || x <= Integer.MIN_VALUE + 6) return 0;. This catches values at the extreme ends of the 32-bit range immediately, neutralizing potential Math.abs overflow before the main logic even begins. 2️⃣ 64-bit Buffering: I used a long data type for the reversal calculation. This provides a 64-bit "safety net," allowing the math to complete so I can verify if the result fits back into a 32-bit int boundary. Complexity Analysis: 🚀 Time Complexity: O(log_10(n))— The loop runs once for every digit in the input (at most 10 iterations for any 32-bit integer). 💾 Space Complexity: O(1)— We use a constant amount of extra memory regardless of the input size. Small details like bit-range asymmetry can break an entire application if ignored. This was a great reminder that as developers, we must always think about the physical limits of our data types! #Java #LeetCode #SoftwareDevelopment #ProblemSolving #Algorithms #CleanCode #JavaProgramming #DataStructures #CodingLife
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