Declaration of characters and Strings - java

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

Related

Can String contain <0x00> along with assigned values in java

If I declare one string, is there any possibility that the string can contain <0x00> along with assigned data ?
For instance :
String s = "Stack";
Can the string result come as :
Stack<0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00><0x00>
Yes, as:
String s = "Stack\u0000\u000";
This in contrast to C/C++ where strings are terminated by a '\0' char.
If a String must be passed as byte array to native code, there java has a trick available for UTF-8,
a modified UTF-8 that also turns '\u0000' into a multi-byte sequence: DataOutputStream.writeUTF(String)
Note that \u0000 (as some other control chars) is not allowed in XML.
By the way the 0 string terminator is deemed by its inventor as the greatest mistake in C. It also influenced processor instruction sets.

Java- when a user inputs a string, is it a string literal?

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.

Character.valueOf

I run this method:
String str=Character.valueOf(char).toString()
The output comes like a small square at console and just like a bar code in the file. What the actual format of the output is, also the output is not able to copy.
Character.valueOf(char) simply takes a char and returns a Character wrapper instance representing the same value. Using toString() on that returns a String containing only that single charcter.
So if your initial char value represents a printable character, then the result should be just as printable.
If, however, you use an arbitrary numeric value (especially, if you use 0, 1 or very high values) as your starting point, then the result will be a String containing a single Unicode character with that codepoint. That's unlikely to be a useful result.
In other words: crap in, crap out.
What is your actual input value and what do you expect to happen?
Try
String.valueOf(c);
.toString() offers a string representation of an object and that can be anything. What you want is not the string representation of the Character object. You want to convert/create a string from a char.

Parse a substring?

I'm trying to convert the first two characters of a String using the parseInt method but I cannot. It's supposed to look like this:
String firstChars = IntMessage.substring(0,2);// firstChars is a String that corresponds to the first two characters of the string.
message=ASCII[(Integer.parseInt(firstChar))-32];//The message variable is a String that is supposed to take a firstChars variable and make it an integer so it can be used by the ASCII array in determining which element of the array is to be concatenated to the message String.
For example if the first two characters are 98, I want to take that substring and convert it into an int.
Well, other than the fact that your string is called firstChars and you're trying to parse firstChar, that should work fine.
But this is an area where you should either be using a debugger with breakpoints so you can figure out what values are being placed in the variables, or just print them out:
IntMessage before doing the substring (and shouldn't this normally start with a lower case letter if it's an object?).
firstChars after doing the substring (make sure it's numeric, for example).
Integer.parseInt(firstChars) after that, making sure it's what you expect.
Then Integer.parseInt(firstChars) - 32.
Finally, ASCII[Integer.parseInt(firstChars) - 32].
Then it will be a simple matter of examining all the outputs to see what the problem is.

Explanation of this line of code?

Can you explain what is happening in this line of code? Specially what is args[0].tocharArray ?
char[] password = args[0].toCharArray();
char[] is your datatype. "char" is a single 16 bit character, and char[] is a character array.
args[0] is the first argument that's passed to the program.
.toCharArray(); converts that argument to a character array.
This line of code is basically taking an argument, turning it into a character array, and storing it in "password" which is a character array.
It's converting the first argument of a Java program—passed as a String[] to the main method—to a character array.
Most password-oriented APIs use char[] so that after calling the method, the caller can "zero-ize" the array, effectively erasing the password from memory. Since Java String instances are immutable, they can't be zero-ized. However, in practice, it's hard to get user-input without using a String. All web frameworks will convert passwords submitted in a web request to a String. Swing password widgets and Java 6's Console class will input char[], however.
args[0] is presumably a String array. Thus it is a call to the method String.toCharArray() which converts a String to an array of chars.
EDIT: Corrected my answer after comment.
It converts the first item of the args array (presumably, the first command line argument passed to the main method, which is of string type) to an equivalent array of chars (an array containing all the chars that build up the string).
args is an array.
The type of the array contains a function called toCharArray which returns an array of characters. NOTE: args is most likely an array of strings
So it takes the string in args[0] and creates an array of characters which represents that string.
args[0] - representing a string
toCharArray() - convert this string to char array
I thought this, toCharArray(), might help.

Categories