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.
Related
So this is for my Java 1 class. And I'm reading the chapter on Inheritance and Interfaces. This is section "Implementing Subclasses". And there is a piece of code with a feature I don't understand. Basically the part I'm reading is describing how to implement methods. Honestly I don't even know how to say this but can someone explain the point to the empty double quotes on the second line?
// Converts choices.size() to string
String choiceString = "" + choices.size();
setAnser (choiceString);
It's a trick to convert choices.size() (an int) to a String, using the String concatenation operator, +. To quote the spec on the String concatenation operator, +:
If only one operand expression is of type String, then string
conversion (ยง5.1.11) is performed on the other operand to produce a
string at run time.
So, in your example, this is a trick to force the integer returned by choices.size() to be converted to a string. Then an empty string is prepended, with the final result of a string.
Another, more readable way to do this would be String.valueOf(choices.size()).
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
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
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 string like :
string = abcdefghabcd
Now lets say I want to replace the first occurrence of a. I tried something like this :
string[string.indexOf('a')] = '0'
But this doesn't seems to be working. Any other way I can do this?
Thanks in advance.
In Java you can use String.replaceFirst() :
String s = "abcdefghabcd";
s = s.replaceFirst("a", "0");
System.out.println(s);
Output will be :
0bcdefghabcd
Warning : the replaceFirst() method takes a regex : so if you want to replace a special character like [ you need to escape by putting a \ before it. \ being a special character itself, you need to double it as follow :
s = s.replaceFirst("\\[", "0");
Here is the documentation on Java Regular Expressions. Also, here is Oracle's Java tutorial on manipulating Characters in Strings.
You should be aware that strings in Java are immutable. They cannot be changed. Any method you use to "change" a string will have to return a new string. If you want to modify a string directly you will need to use a mutable string type like StringBuilder.
There are many methods in the String API docs that will help you get a modified version of your string, including s.replace(), s.replaceAll(),s.replaceFirst(), ... or you could use a combination of substring and "+" to create a new string.
If you really want to treat the string as an array as in your initial example, you could use String.getChars to get an array of characters, manipulate that, and then use the String constructor String(char[]) to convert back to a String object.
In this program you will need use replaceFirst() method of String class in Java.
/*
Java String replace example.
This Java String Replace example describes how replace method of java String
class can be used to replace character or substring by new one.
*/
public class JavaStringReplaceExample{
public static void main(String args[])
{
String str="abcdefghabcd";
System.out.println(str.replaceFirst("a", "0"));
}
}
you can refer to here for details