Why is it necessary to put double quotes? - java

In the code line
editText.setText(firstnum + secondnum + "");
Can anyone explain to me why there are double quotes at the end?

firstnum and secondnum are both of type Float it seems so adding them will result in a Float, the setText() method takes a String not a Float, when adding + "" java will automatically convert the addition of the 2 Floats to a string, think if you had:
editText.setText(5 + " apples");
Then java will think you want to have a string "5 apples" that is why it convert the int before the string to a string representation then append it to " apples".

This is to enforce conversion of your integer value (result of firstnum + secondnum) to string, which is what setText() requires as argument. There's also setText() that accepts int (you are using floats so that's not the case anyway) but that int will be used as ID of string resource which is not what you want, hence need of conversion to string. It's also just less typing. It's basically equivalent of replacing:
editText.setText(firstnum + secondnum + "");
with:
editText.setText(String.valueOf(firstnum + secondnum));

The + is an overloaded operator
when it is between two numbers that it will add them
but adding the "" will make it in a string

setText wants a String.
if you want to get a String from an int you can use String.valueOf(i) or i+"".

Related

Why do we print variable values like this?

I want to know why we concatenate a dummy string with a variable while printing its value.
Eg.
system.out.print(var + " ");
Concatenation with an empty string is a technique some developers use to convert any value to a string. It's unnecessary with System.out.print as that accepts any value anyway. I prefer using String.valueOf anyway:
String text = String.valueOf(variable);
This is clearer in terms of the purpose being converting a value to a string, rather than concatenation.
However, in the case you've given, it's possible that the developer wasn't just using concatenation for that purpose - but actually to get the extra space. For example:
int var1 = 1, var2 = 2, var3 = 3;
System.out.print(var1 + " ");
System.out.print(var2 + " ");
System.out.print(var3 + " ");
Those will all print on the same line:
1 2 3
Other options include:
Using a StringBuilder to build up the string before printing it
Putting it all into a single System.out.print call: System.out.print(var1 + " " + var2 + " " + var3);
Using printf instead: System.out.printf("%d %d %d", var1, var2, var3);
Extremely sorry. The question was l1.setText(var+" "); and it is done because a text field cannot take an integer value, so we concatenate a dummy string at the end of it, so the integer value in var can be printed.
Thank you all for helping me out!

Difference between String.valueOf(int i) and printing only i

See the below code snippet:
int count = 0;
String query = "getQuery";
String query1 = "getQuery";
final String PARAMETER = "param";
query += "&" + PARAMETER + "=" + String.valueOf(count);
query1 += "&" + PARAMETER + "=" + count;
System.out.println("Cast to String=>"+query);
System.out.println("Without casting=>"+query1);
Got the both output exactly same. So I am wondering why this has been used when we can get the same result by using only count.
I got some link but did not found exactly same confusion.
This is well explained in the JLS - 15.18.1. 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.
You should note the following:
The + operator is syntactically left-associative, no matter whether it
is determined by type analysis to represent string concatenation or
numeric addition. In some cases care is required to get the desired
result.
If you write 1 + 2 + " fiddlers" the result will be
3 fiddlers
However, writing "fiddlers " + 1 + 2 yields:
fiddlers 12
Java compiler plays a little trick when it sees operator + applied to a String and a non-string: it null-checks the object, calls toString() on it, and then performs string concatenation.
That is what's happening when you write this:
query1 += "&" + PARAMETER + "=" + count;
// ^^^ ^^^^^^^^^ ^^^
You can certainly do this when the default conversion to String is what you want.
However, if you do this
String s = count; // <<== Error
the compiler is not going to compile this, because there is no concatenation. In this situation you would want to use valueOf:
String s = String.valueOf(count); // <<== Compiles fine
String.valueOf(int) actually calls Integer.toString().
So, it is used to convert an int to a String elegantly. As, doing i+"" is IMNSHO, not quite elegant.
Moreover, when you print any number directly, it actually calls the toString() method of its Wrapper class, and the prints the string.

Print multiple char variables in one line?

So I was just wondering if there was a way to print out multiple char variables in one line that does not add the Unicode together that a traditional print statement does.
For example:
char a ='A';
char b ='B';
char c ='C';
System.out.println(a+b+c); <--- This spits out an integer of the sum of the characters
System.out.println(a+""+b+""+c);
or:
System.out.printf("%c%c%c\n", a, b, c);
You can use one of the String constructors, to build a string from an array of chars.
System.out.println(new String(new char[]{a,b,c}));
The println() method you invoked is one that accepts an int argument.
With variable of type char and a method that accepts int, the chars are widened to ints. They are added up before being returned as an int result.
You need to use the overloaded println() method that accepts a String. To achieve that you need to use String concatenation. Use the + operator with a String and any other type, char in this case.
System.out.println(a + " " + b + " " + c); // or whatever format
This will serve : System.out.println(String.valueOf(a) + String.valueOf(b) + String.valueOf(c));.
System.out.println(new StringBuilder(a).append(b).append(c).toString());
System.out.print(a);System.out.print(b);System.out.print(c) //without space

Why does concatenated characters print a number?

I have the following class:
public class Go {
public static void main(String args[]) {
System.out.println("G" + "o");
System.out.println('G' + 'o');
}
}
And this is compile result;
Go
182
Why my output contain a number?
In the second case it adds the unicode codes of the two characters (G - 71 and o - 111) and prints the sum. This is because char is considered as a numeric type, so the + operator is the usual summation in this case.
+ operator with character constant 'G' + 'o' prints addition of charCode and string concatenation operator with "G" + "o" will prints Go.
The plus in Java adds two numbers, unless one of the summands is a String, in which case it does string concatenation.
In your second case, you don't have Strings (you have char, and their Unicode code points will be added).
System.out.println("G" + "o");
System.out.println('G' + 'o');
First one + is acted as a concat operater and concat the two strings. But in 2nd case it acts as an addition operator and adds the ASCII (or you cane say UNICODE) values of those two characters.
This previous SO question should shed some light on the subject, in your case you basically end up adding their ASCII values (71 for G) + (111 for o) = 182, you can check the values here).
You will have to use the String.valueOf(char c) to convert that character back to a string.
The "+" operator is defined for both int and String:
int + int = int
String + String = String
When adding char + char, the best match will be :
(char->int) + (char->int) = int
But ""+'a'+'b' will give you ab:
( (String) + (char->String) ) + (char->String) = String
+ is always use for sum(purpose of adding two numbers) if it's number except String and if it is String then use for concatenation purpose of two String.
and we know that char in java is always represent a numeric.
that's why in your case it actually computes the sum of two numbers as (71+111)=182 and not concatenation of characters as g+o=go
If you change one of them as String then it'll concatenate the two
such as System.out.println('G' + "o")
it will print Go as you expect.

Split String to String[] by a period but returning an empty array

Ok maybe i just need a second pair of eyes on this.
I have a float, that I turn into a string. I then want to split it by its period/decimal in order to present it as a currency.
Heres my code:
float price = new Float("3.76545");
String itemsPrice = "" + price;
if (itemsPrice.contains(".")){
String[] breakByDecimal = itemsPrice.split(".");
System.out.println(itemsPrice + "||" + breakByDecimal.length);
if (breakByDecimal[1].length() > 2){
itemsPrice = breakByDecimal[0] + "." + breakByDecimal[1].substring(0, 2);
} else if (breakByDecimal[1].length() == 1){
itemsPrice = breakByDecimal[0] + "." + breakByDecimal[1] + "0";
}
}
If you take this and run it, you will get an array index out of bounds error on line 6 (in the code above) regarding there being nothing after a decimal.
In fact on line 5, when i print out the size of the array, it's 0.
These are to ridiculous of errors for them to NOT be something i am simply overlooking.
Like I said, another pair of eyes is exactly what i need, so please don't be rude when pointing out something that's obvious to you but I overlooked it.
Thanks in advance!
split uses regular expressions, in which "." means match any character. you need to do
"\\."
EDIT: fixed, thanks commenter&editor
Use decimal format instead:
DecimalFormat formater = new DecimalFormat("#.##");
System.out.println(formater.format(new Float("3.76545")));
I have not worked much on java, but on line 2, maybe price is not getting converted to string.
I work in C# and I would use that as :
String itemsPrice = "" + price.ToString();
maybe you should convert price to string first explicitly.
Since, it is not getting converted, string only contains "" and there is no ".", so no split and by extension arrayOutOfBounds error.
If you want to present it as a price use NumberFormat.
Float price = 3.76545;
Currency currency = Currency.getInstance(YOUR_CURRENCY_STRING);
NumberFormat numFormat = NumberFormat.getCurrencyInstance();
numFormat.setCurrency(currency)
numFormat.setMaximumFractionDigits(currency.getDefaultFractionDigits());
String priceFormatted = numFormat.format(price);
System.out.println("The price is: " + priceFormatted);
YOUR_CURRENCY_STRING is the ISO 4217 currency code for the currency you are dealing with.
Also, it's generally a bad idea to represent prices in a non-precise format (such as floating point). You should use BigDecimal or Decimal.
If you want to handle it all by yourself then try the following code:
public static float truncate(float n, int decimalDigits) {
float multiplier = (float)Math.pow(10.0,decimalDigits);
int intp = (int)(n*multiplier);
return (float)(intp/multiplier);
}
and get the truncatedPrice like this:
float truncatedPrice = truncate(3.3654f,2);
System.out.println("Truncated to 2 digits : " + truncatedPrice);

Categories

Resources