-2

I Just tried to find out what the compiler does if I try to find the index of a null charachter in a String.I remember somehwere that a null charachter is always appended to the end of a string, so i expected the code below to give me 5.

When I type out this:

String s = "Hello";
System.out.println(s.indexOf(""));

It gives an output of 0

Help please!

Héctor
  • 24,444
  • 35
  • 132
  • 243
  • 1
    `""` is not a "null character" - it's an empty String. And Java does not store strings with a "null character" at the end. It stores them as a `char` array –  Mar 21 '18 at 14:01
  • `""` is not null character. It's an empty string – Héctor Mar 21 '18 at 14:01
  • 1
    You're thinking of C, not java - C strings are terminated by a null character – Jon Kiparsky Mar 21 '18 at 14:01
  • "" and null are different – Kepotx Mar 21 '18 at 14:01
  • There is no null character in a Java `String` unless you add one yourself. If you want to find the end of the string, just use `s.length()`. What are you actually trying to do? – khelwood Mar 21 '18 at 14:02
  • Consider `System.out.println("Hello".substring(0,0));` and `System.out.println(Arrays.toString("Hello".split("")));` - The empty `String` appears before the first character, the second character, etc... – Elliott Frisch Mar 21 '18 at 14:03
  • Check out the following links, maybe they'll help! https://stackoverflow.com/questions/2683466/java-string-indexof-and-empty-strings https://stackoverflow.com/questions/4802015/difference-between-null-and-empty-java-string – ChanceVI Mar 21 '18 at 14:06
  • Yeah that helped!Thanks luzi – Siddharth Bhat Mar 21 '18 at 14:08

1 Answers1

1

First, if you were looking for a null character you would probably want to do (char)0 because "" is an empty string (no character).

Second, if Java uses a null character (they don't have to IIRC) then they hide it.

EDIT: Struck my third point because I'm not sure about it anymore.

SECOND EDIT: I looked it up, Java strings are not null terminated. They rely on the length field.

Pace
  • 41,875
  • 13
  • 113
  • 156