-5

what is the wrong of the following code , i am trying to write the length method source code , i tried it with c++ ( same logic i mean ) and it worked , but here it give me the below exception error : StringIndexOutOfBoundsException , thanks for helping . Note : iam using intellij idea

package com.company;
public class Main {

public static void main(String args[]) {

    String text = "hello world";
    int i = 0;
    while (text.charAt(i) != '\0') {
        i++;
    }
    System.out.println(i);
}
}
3
  • 1
    Strings in java are something very different than strings in c++ and therefore the logic does not make any sense in java. hg.openjdk.java.net/jdk7u/jdk7u6/jdk/file/8c2c5d63a17e/src/… Commented Jun 22, 2021 at 14:29
  • 1
    Java Strings don't work like that. They don't have a char '\0' in their last index to denote the end. Also unless you are doing this just to train your java skills all of this is unnecessary complicated. You can just call length() on your Strings to get their length. Commented Jun 22, 2021 at 14:31
  • No such thing as a \0 in a java String (unless you explicitly put a \0 in a String, which is perfectly valid) Commented Jun 22, 2021 at 14:31

4 Answers 4

1

The length is just text.length(). Checking for a \0 terminator is a C-ism. Java doesn't terminate strings with NUL.

Sign up to request clarification or add additional context in comments.

Comments

0

As stated in this SO,

Strings in Java do NOT have a NULL terminator as in C, so you need to use the length() method to find out how long a string is.

Therefore you can change the condition to

while (i < text.length())

(If your goal really is to get the length of a string, your function therefore is redundant, as it is already built in)

Comments

0

There is no char c='\0' to check the end of a string in Java. It's valid in C/C++ but there is no null character to identify the end of a string in Java.
We can use a forEach loop to count the number of characters (length of String) as follows:

public class Main
{
    public static void main(String args[])
    {
        String text = "hello world";
        int i = 0;
        // Using For-Each loop
        for (char character : text.toCharArray()) // For each character of `text`
        {
            i++;
        }
        System.out.println(i);
    }
}

To directly check the length of string we use length() function as stringName.length().

Comments

0

Strings are backed by arrays. They are not terminated by any special character. So if you don't want to use text.length(), you can do the following:

String text = "hello world";
int len = text.toCharArray().length;
System.out.println(len);

Prints

11

 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.