Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do Strings start with a "" in Java? [duplicate]

Tags:

Possible Duplicate:
Why does “abcd”.StartsWith(“”) return true?

Whilst debugging through some code I found a particular piece of my validation was using the .startsWith() method on the String class to check if a String started with a blank character

Considering the following :

public static void main(String args[])
{

    String s = "Hello";
    if (s.startsWith(""))
    {
        System.out.println("It does");
    }

}

It prints out It does

My question is, why do Strings start off with a blank character? I'm presuming that under the hood Strings are essentially character arrays, but in this case I would have thought the first character would be H

Can anyone explain please?

like image 299
Jimmy Avatar asked Oct 06 '10 13:10

Jimmy


People also ask

What is string repeat in Java?

String Class repeat() Method in Java with Examples repeat() method is used to return String whose value is the concatenation of given String repeated count times. If the string is empty or the count is zero then the empty string is returned. Syntax: string. repeat(count);

How do you duplicate a string in Java?

repeated = new String(new char[n]). replace("\0", s);

Why are strings special in Java?

Java String is, however, special. Unlike an ordinary class: String is associated with string literal in the form of double-quoted texts such as " hello, world ". You can assign a string literal directly into a String variable, instead of calling the constructor to create a String instance.

When was string repeat added in Java?

The repeat() method is added in the String class from Java 11 version.


2 Answers

"" is an empty string containing no characters. There is no "empty character", unless you mean a space or the null character, neither of which are empty strings.

You can think of a string as starting with an infinite number of empty strings, just like you can think of a number as starting with an infinite number of leading zeros without any change to the meaning.

1 = ...00001
"foo" = ... + "" + "" + "" + "foo"

Strings also end with an infinite number of empty strings (as do decimal numbers with zeros):

1 = 001.000000...
"foo" = "foo" + "" + "" + "" + ...
like image 177
Cameron Avatar answered Sep 20 '22 10:09

Cameron


Seems like there is a misunderstanding in your code. Your statement s.startsWith("") checks if string starts with an empty string (and not a blank character). It may be a weird implementation choice, anyway, it's as is : all strings will say you they start with an empty string.

Also notice a blank character will be the " " string, as opposed to your empty string "".

like image 20
Riduidel Avatar answered Sep 20 '22 10:09

Riduidel