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()).
Related
I've seen in some java libraries when returning a string the value is concatenated with an empty value.
For example package java.io;
/**
* The system-dependent default name-separator character, represented as a
* string for convenience. This string contains a single character, namely
* <code>{#link #separatorChar}</code>.
*/
public static final String separator = "" + separatorChar;
Why not return only separatorChar?
Are strings the preferred datatype for return values? Give that this is only a char anyway why use a string datatype?
Are there any performance implications of doing this conversion?
One is a String, the other is char. It's useful to always be dealing with a String, rather than having to check if it's a char.
This is one of several ways of converting a char to a String. Although this used to be one of the slower ways of converting from char to String, as of java 6 update 20, with the introduction of -XX:+OptimizeStringConcat flag, concatenation is the fastest way to convert any value to string. As of Java 7, this option is turned on by default. So you're correct. There are performance implications. Here is a really great post which discusses this : https://stackoverflow.com/a/44485322/1028560.
What kind of quote marks should I choose for a single character when I concatenate it with a string?
String s1="string";
Should I use
String s2=s1+'c';
Or
String s2=s1+"c";
?
You can use both! Give it a try!
"Why?" you ask. The magic here is the + operator.
When + is used with strings, it automatically turns the other operand into a string! That's why it can be used with 'c', a character literal. It can also be used with "c" because of course, "c" is a string literal.
Not only that, you can even add integers to a string:
String s2=s1+1;
U can use it in two diferent ways : String s2=s1+'c'; and
char x = 'c';
String s2 = s1 + x;
Both approaches are ok but if you are going into the details then perhaps
String s2=s1+'c';
will take a little less memory than the second way because char is just two bytes while String requires 8+ bytes. But I don't think that such nuances are important in most cases and also I'm not even sure that this difference will exist at all because JVM may optimize it
Java automatically does the conversion for you, so it doesn't really matter, but I'd personally just use a string (double quotes) just because I personally prefer to minimize the 'automatic stuff' that happens if I can prevent it.
Also, if you ever decide that 'c' should be 'csomething', then you'll have to change it into a boudle quote anyway.
But I suppose I'm just nitpicking...
Those are 2 different types of casting: implicit casting and explicit casting.
String s2=s1+'c';
This is a implicit casting, which means that the magic is done by the compiler (no overhead).
String s2=s1+"c";
This is a explicit casting, because "c" is converted to an object like:
Object o = "c";
String s2 = (String) o;
This means that the conversion must be checked for null-pointers, which will create an overhead.
Therefore, while both ways works, I prefer casting from character ('c') because that will create less overhead!
source: http://www.javaworld.com/article/2076555/build-ci-sdlc/java-performance-programming--part-2--the-cost-of-casting.html
I'm making a calculator, and some computations require 3 pieces of information (eg, 3*4), whereas other only require 2 (eg, 5!).
I have managed to split the input into 3 parts using the following code:
String[] parts = myInput.split(" ");
String num1 = parts[0];
String operation = parts[1];
String num2 = parts[2];
But this means that when I only type 2 things, it doesn't work.
How can I allow for either 3 or 2 things as an input?
You should not assume that the input will always in the 3 parameter form. Rather, take a generic input, parse on it based on use cases.
In your case, it boils down to two specific use cases AFTER you accept the input:
Operators that operate on single operand - unary operator
Operators that operate on double operand - binary operator
For each case, you can define a list of operators allowed. E.g. '!' will be in case 1 list, while '*' will be in case '2'
scan through the string, look for the operator position. [^0-9] (represents a pattern which other than numbers). Or simply you can do a trivial check for the operator (by creating your own custom method)
Once you have figured out this, validate your string (optional) - e.g. makes no sense to have two operands for a unary operator.
Having done this, it is fairly easy to parse now the required operands by splitting out the string based on the operator. Computation is fairly trivial then.
Hope this helps.
Without knowing more I can't help you find a better design to accommodate for the commonalities and variances. But to answer the stated questions....
You can use parts.length to know many variables you were given and use that to branch your code (i.e. if else statement).
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 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.