This question already has answers here:
Difference between null and empty ("") Java String
(22 answers)
Closed 6 years ago.
In my computer science class we were discussing null and values when we came across a predicament. We could not figure out the value of simply 2 quotes with no space as "". Just wondering if anyone would know what the exact value of "". Thanks
It's the empty String. JLS-3.10.5. String Literals says A string literal consists of zero or more characters enclosed in double quotes. And, then includes this example
The following are examples of string literals:
"" // the empty string
As Java String(s) are immutable, it has a constant length of 0 and stores a sequence of 0 characters.
When you initialize it with null like this:
String s1 = null;
It means that no object is assigned to variable s1. However, when you initialize it with empty String like this:
String s2 = "";
It means that a String object is assigned to s2 (although empty).
Now if you want to perform any operation, let's say you want to call the .equals(..) method of string, then it will throw NullPointerException in the former case as there is not String object. However, it will work fine in latter because there is an object there, it doesn't matter whether it's empty or not
s1.equals("something"); // throws NullPointerException
s2.equals("something"); // works fine
Related
This question already has answers here:
Java String.indexOf and empty Strings
(7 answers)
Closed 4 years ago.
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!
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.
Declaration of a character:
char ch = '';
When I do this i am getting the error 'empty character literal'.
Declaration of a String:
String str = "";
I see no error in doing that to a String.
The question is, why doesn't a similar error show up for the declaration of a String, or why declaration of empty character generating such error where empty string is getting passed
String is a set of chars and String str=""; contains no chars(read: empty string)
but if you want to have Char variable it must have some value. '' means no value.
String is a class in Java with its own syntax and methods. It accepts strings in double quotes. And a string is actually an Array of characters and is hence acceptable to be posted empty.
Char on the other hand is a data type and cannot be left undetermined. It needs to specified NULL.
I would recommend you to read through the Java tutorial documentation hosted on Oracle's website whenever you are in doubt about anything related to Java.
Basically char is a thing you put in a box, and a string is a box to hold all those things. You can have an empty box but not a non-existant thing.
A string is an array of characters. By passing it nothing, i.e. making it equal to "" you basically make an empty array which is fine. But char is a primitive type hence it cannot be "empty". The closest you can get is setting it equal to '\0' which is the null character.
Here char represents the 16-bit integer value of the character in quotes. Refer this table for the values.
There is no representation number for "empty/no character".
In case of String refer their source code. You can see that empty string is represented internally by 0 size char array. So String internally does not have magical representation of empty/no character. For "" String class does not allocate any space per se
This question already has answers here:
String can't change. But int, char can change
(7 answers)
Closed 9 years ago.
String s1 = "ABC";
s1.replace("ABC","abc");
print(s1); // prints ABC as output
s1 = s1.replace("ABC","abc");
print(s1); //prints abc
What's the difference between two replace statements?
What happens internally when the first replace statement is called?
String.replace(CharSequence first, CharSequence second) returns a new String reference and this is why the output is different.
In the first replace line you're not assigning the resulting String to anything, whereas in the second you're replacing the reference of s1 with the result of the replacement.
s1.replace("ABC","abc"); doesn't replace on s1. It gives output of the replaced string.
$s2 = s1.replace("ABC","abc");;
print($s1); // prints ABC
print ($s2); // prints abc
Strings are immutable. It means changes are not made directly into them instead a copy of the string is created and it is changed and the reference of the changed one is returned. If you do not accept the new reference you will find the old string unchanged.
Read the API and the Java tutorials... String can NEVER be changed. That means all its methods will return a new object and your reference will still point to the old one. To assign the return to your reference, you have to assign it as in
s1 = s1.replace("ABC","abc");
Be careful with that! Quite tricky ;)
If you will change the String a lot, use StringBuffer instead... There your appends, replaces, etc have effect in the object referenced by your variable.
String.replace() Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
Code of String.replace
When you do s1.replace("ABC", "abc") imagine that in that place new string abc is created and not assigned to anything. But with s1=s1.replace("ABC", "abc") you create new string abc and assign it to the s1 variable replacing old value.
I have some question that I wonder about. I know that string are immutable in Java and therefore a new string object is created rather than changed when for example assigning to a existing string object.
Now to my question. Let's suppose that I have the following piece of code:
String a = "Hello World";
String b = "Hello World";
String res = a.substring(0,4) + b.substring(6,10);
How many string objects will be created by the code at line 3 ? Will each call to substring create a new string object ? Will my code above generate 3 new string objects ?
Thanks in advance
Strings in Java are immutable. Basically this means that, once you create a string object, you won't be able to modify/change the content of a string. As a result, if you perform any manipulation on a string object which "appears to" change the content of the string, Java creates a new string object, and performs the manipulation on the newly created one.
Based on this, your code above appears to create five string objects - two are created by the declaration, two are created by calls to substring, and the last one is created after you concatenate the two pieces.
Immutability however leads to another interesting consequence. JVM internally maintains something like a string pool for creating string literals. For saving up memory, JVM will try to use string objects from this pool. Whenever you create a new string literal, JVM will loop into the pool to see if any existing strings can be used. If there is, JVM will simply use it and return it.
So, technically, before Java 7, JVM will create only one string object for your whole code. Even your substring calls won't create new string objects in the pool, it will use the existing "Hello World" one, but in this case it will only use characters from position 0 to 3 for your first call to substring, for example. Starting from Java 7, substring will not share the characters, but will create a new one. So, total object count will be 4 - the last one will be created with the concatenation of the two substrings.
Edit
To answer your question in the comment, take a look at Java Language Specification -
In the Java programming language, unlike C, an array of char is not a
String, and neither a String nor an array of char is terminated by
'\u0000' (the NUL character).
A String object is immutable, that is, its contents never change,
while an array of char has mutable elements.
The method toCharArray in class String returns an array of characters
containing the same character sequence as a String. The class
StringBuffer implements useful methods on mutable arrays of
characters.
So, no, char arrays are not immutable in Java, they are mutable.
Literal a is created newly and kept in the pool.Literal b refer the a, it will not create new one instead.
The line 3 will create 3 new String since substring creates a new string and concatenate creates new Strings every time.
String substring(int beginIndex,int endIndex)
Returns a new string that is a substring of this string. The substring
begins at the specified beginIndex and extends to the character at
index endIndex - 1. Thus the length of the substring is
endIndex-beginIndex.
I have a question to help me with homework. We were to write a program using a string literal and print it in reverse. I wrote it and it works fine but i have two different versions. The first uses the scanner so the user can input a string and then it prints in reverse. In the second, i declare a string literal and just print that in reverse.
My question isn't about my program which works fine, but rather i can't find anywhere online or in my book which says an inputted string is a string literal. I understand that a string literal is usually written as
String a = "Welcome to Java"
but can be written as
String a = new String("Welcome to Java")
So then is an inputted string not the same as a string literal?
Does it have to be written out in quotes to be considered a string literal?
I'm assuming the answer will be yes since my book basically says it has to be in quotes, but i want to double check before i hand in my assignment that i'm turning in the correct version. Thanks in advance for any clarification!
A string literal is one that is in quotes and literally in your code:
String literal = "string literal";
An input string is not a string literal, just a string.
At #Shakedown implies, a string literal is a syntactic element of your Java source code. It is also (in a loose sense) a Java String object that corresponds to that literal when your program is executed. We can say that the literal denotes the runtime string. Furthermore, the JLS specifies that two string literals with the same characters will denote the same String object in the context of a simple program execution.
In your code snippets.
String a = "Welcome to Java";
and
String a = new String("Welcome to Java");
... the "Welcome to Java" character sequences in the source code are both String literals, and assuming that they are used in the same execution, they will denote the same (interned) String object.
However, new String("Welcome to Java") is not a String literal. It is an expression that creates a new String object. And the result of executing that expression is guaranteed to be a different String object to the one that the literal(s) denoted.
Does it have to be written out in quotes to be considered a string literal?
Yes. And more than that, it has to be written in quotes in your program's source code to qualify as a string literal.
If I wrote a program that accepted use input from a GUI, and the user entered input with double quote characters around it, that is NOT a string literal. Rather it is a String which happens to start and end with double quote characters. (Yes ... in this case the string's value would include the quote characters.)
A string literal ("foo bar baz") is a String object -- it's just a nice syntax for creating such objects. When you get input from the user, it will also be a String object -- the same type as that literal.
However, a string literal refers to that syntax (the stuff in quotes), not the type of object. So, to answer your question precisely, the user's input is not a string literal.
The inputted string is no different from a string literal.
Strings are stored, in Java, as objects of class String. One way of getting one is a string literal: "hello sailor" is a string literal, and when used in a Java expression, it's an object of class String. Methods that return strings also return objects of class String. So they're equivalent for all purposes.
There are ways to tell a literal from a new String("..."), but those are rather contrived. As a beginner, you need not worry about those.