-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);
}
}
  • 1
    Strings in java are something very different than strings in `c++` and therefore the logic does not make any sense in java. https://hg.openjdk.java.net/jdk7u/jdk7u6/jdk/file/8c2c5d63a17e/src/share/classes/java/lang/String.java#l622 – luk2302 Jun 22 '21 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. – OH GOD SPIDERS Jun 22 '21 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) – Gyro Gearless Jun 22 '21 at 14:31

4 Answers4

1

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

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
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)

Markus
  • 111
  • 2
  • 12
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().

GURU Shreyansh
  • 881
  • 1
  • 7
  • 19
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

 
WJS
  • 36,363
  • 4
  • 24
  • 39