printing an int value right after a String value - java

I have the following example code:
int pay = 80;
int bonus = 65;
System.out.println(pay + bonus + " " + bonus + pay);
could someone please explain to me why I get the following output:
145 6580

Your code is interpreting the expression from left to right.
pay + bonus is interpreted as a mathematical function, so it adds the values to make 145. The + here is a plus operator.
The moment you concatenate the " ", Java converts the expression into a String. The + here is a concatenate operator.
Performing + pay converts pay to a String and concatenates it, because the expression is a String.
Also doing + bonus converts bonus to a String and concatenates it, also because of the previous expression.

Because, this is operator overloading issue. Here, First + is plus operator and last + is concat operator.
System.out.println(pay + bonus + " " + bonus + pay);
| |
(plus) (concat)

First it adds the two variables and at last it concatinates as string because the integers are converted into strings
For concatenation, imagine a and b are integers:
"" + a + b
This works because the + operator is overloaded if either operand is a String. It then converts the other operand to a string (if needed) and results in a new concatenated string. You could also invoke Integer.toString(a) + Integer.toString(b) for concatenation

bonus and pay are both ints, and therefore going to be combined into a single int result.
You need to insert an empty string between them.

first is plus operator and last is concat operator

The 1st pay and bonus in the println returns an integer. So it computes pay+bonus and returns it as an integer before printing it out.
However, after the "". The + operation then becomes a concatenation of strings and everything after that is returned as a concatenated string. Hence, ("" + bonus + pay) would be returned as "6580".

before " ",pay and bonus as integer, added result is 145.
after " ",bonus and pay as String,result is "6580"

As the others are saying the compiler is first adding the integer values and then printing the result, after " " the total value is changed to String type and after that + operator is functioning as a concat action. To not get that output, you can do this:
System.out.println(String.valueOf(pay) + String.valueOf(bonus) + " " + String.valueOf(bonus) + String.valueOf(pay));

what is surrounded by " " is referred to as a 'literal print' and gets printed exactly. The "+" sign is the concatenator operator and concatenates the string with the value that is stored in the variables. pay and bonus are declared as int, but is automatically converted to a String for the purpose of printing out.
You can print an arithmetic expression within a System.out.print statement. Use parentheses around the arithmetic expression to avoid unexpected problems.
System.out.println("ex" + 3 + 4); // becomes answer 34
System.out.println("ex" + (3 + 4)); // becomes answer 7

Related

How does the charAt() method work with taking numbers from strings and putting them into new strings in Java?

public String getIDdigits()
{
String idDigits = IDnum.charAt(0) + IDnum.charAt(IDnum.length() - 1) + "";
return idDigits;
}
In this simple method, where IDnum is a 13 digit string consisting of numbers and is a class variable, the given output is never what I expect. For an ID number such as 1234567891234, I would expect to see 14 in the output, but The output is always a three-digit number such as 101. No matter what ID number I use, it always is a 3 digit number starting with 10. I thought the use of empty quotation marks would avoid the issue of taking the Ascii values, but I seem to still be going wrong. Please can someone explain how charAt() works in this sense?
You are taking a char type from a String and then using the + operator, which in this case behaves by adding the ASCII numerical values together.
For example, taking the char '1', and then the char '4' in your code
IDnum.charAt(0) + IDnum.charAt(IDnum.length() - 1)
The compiler is interpreting this as its ASCII decimal equivalents and adding those
49 + 52 = 101
Thats where your 3 digit number comes from.
Eradicate this with converting them back to string before concatenating them...
String.valueOf(<char>);
or
"" + IDnum.charAt(0) + IDnum.charAt(IDnum.length() - 1)
Try this.
public String getIDdigits()
{
String idDigits = "" + IDnum.charAt(0) + IDnum.charAt(IDnum.length() - 1);
return idDigits;
}
When you first adding a empty it's add char like String if you put it in end it first add in number mode(ASCII) and then convert will converts that to String.
You have to be more explicit about the string concatenation and so solve your statement like this :
String idDigits = "" + IDnum.charAt(0) + IDnum.charAt(IDnum.length() - 1);
The result of adding Java chars, shorts, or bytes is an int:

Operator in print statement

Example:
System.out.println("the investment doubled after "+year+" years.");
Can someone please explain why the int variable year is inside quotations and pluses?
Adding some spacing around the operators may make this statement clearer:
System.out.println("the investment doubled after " + year + " years.");
This statement prints the result of a concatination of three strings, achieved by the two + operators:
"the investment doubled after "
The implicit conversion of the int variable year to a string
" years."
It is like this. And + is used for String concatenation. In this year is converted into String from int implicitly.
"the investment doubled after " + year + " years."
^-------inside quotes-------^ ^-----^Inside quotes
Your variable year is not inside quotes, it's actually outside of quotes. It is in between of + sign because you are concatenating it.
Here you are using the public void println(String x); method. Which means the integer will concatenated to the string when you append the years to the string, that is the reason we are using the + operator.

Unexpected java charAt output

The code is
String veggie = "eggplant";
int length = veggie.length();
char zeroeth = veggie.charAt(0);
char third = veggie.charAt(4);
String caps = veggie.toUpperCase();
System.out.println(veggie + " " + caps);
System.out.println(zeroeth + " " + third + " " + length);
System.out.println(zeroeth + third + length);
The output reads:
eggplant EGGPLANT
e 1 8
217
This doesn't make sense to me. Referencing a charAt outputs numbers instead of characters. I was expecting it to output the characters. What did I do wrong?
The second line should actually be:
e l 8
(note that the second value is a lower-case L, not a 1) which probably doesn't violate your expections. Although your variable is confusingly called third despite it being the fifth character in the string.
That just leaves the third line. The type of the expression
zeroeth + third + length
is int... you're performing an arithmetic addition. There's no implicit conversion to String involved, so instead, there's binary numeric promotion from each operand to int. It's effectively:
System.out.println((int) zeroeth + (int) third + (int) length);
It's summing the UTF-16 code units involved in 'e', 'l' and 8 (the length).
If you want string conversions to be involved, then you could use:
System.out.println(String.valueOf(zeroeth) + third + length);
Only the first addition needs to be a string concatenation... after that, it flows due to associativity. (i.e. x + y + z is (x + y) + z; if the type of x + y is String, then the second addition also becomes a string concatention.)
The compiler interprets all variables as values rather than a string.
Try System.out.println("" + zeroeth + third + length);
This line is doing integer arithmetic:
System.out.println(zeroeth + third + length);
In other words, it is adding the unicode values of each character (i.e. e is 101, l is 108, 8 is 8). To do String concatenation, you can add an empty String to the front:
System.out.println("" + zeroeth + third + length);
Since it is evaluated left-to-right, it will first do String concatenation (not addition). It will continue to do this for third and length. Adding "" at the end won't work, because addition will occur first.
You can use the method of the wrapper class Character to display the string values of char variables:
System.out.println(Character.toString(zeroeth) + Character.toString(third) + length);
This way, you always work with String values and there are no possibilities for the numeric values of the chars to be displayed or added and you don't need to concatenate with empty strings ("") to convert the char variables to String values.

Clarification regrading String concatenation and addition? [duplicate]

This question already has answers here:
What is the precedence of the + (plus) operator in Java?
(4 answers)
Closed 9 years ago.
Why do i get 10 2030 as the out put? I cant figure out why it doesnt output it as 10 50 ?
public class Testing1 {
public static void main (String args[]){
int num1=10,num2=20,num3=30;
System.out.println(num1+" "+num2+num3);
}
}
Operator precedence
System.out.println(num1+" "+(num2+num3));
While evaluation expressions,
Operators with higher precedence are evaluated before operators with relatively lower precedence. Operators on the same line have equal precedence.When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from **left to right**; assignment operators are evaluated right to left.
System.out.println(num1+" "+num2+num3);
--------------------10-----------------num1
--------------------10 -----------------num1+" "
--------------------10 20-----------------num1+" "+num2
--------------------10 2030-----------------num1+" "+num2+num3
So, now you come to know that why you got that output.
Let see how the below statement gives you desired output:
System.out.println(num1+" "+(num2+num3));
Again based on the precedence, parentheses have the high precedence than +. So
(num2+num3)
evaluates first and the rest is same.
This does not work because the expression is interpreted from left to right taking into account operator precedence
Walk through it.
System.out.println(num1+" "+num2+num3);
First you take your num1 and concat a space onto it, you now have "10".
Second you concat num2 onto that string, you have "10 20".
Third you concat num3 onto that, you have "10 2030".
In fact, what you are doing is this:
String s = num1 + " ";
s += num2;
s += num3;
Use this:
System.out.println(num1 + " " +(num2 + num3));
If you're writing (num1 + " " + num2 + num3) Java will make a String from num1 add the String " " to it, add the String made from num2 to it and then add the String made from num3 to it.
The plus first gets evaluated as String concatenation and not the math + sign.
make it System.out.println(num1+" "+ (num2+num3));
When you introduce any string when performing operations, then the concatenation happens instead of actual operation.
So if you do System.out.println(num1+num2+ " " +num3);. You will get the output as 30 30 This is because your operations are performed before string concatenation is introduced in it. and hence the operation result is produced.
Keep in mind that all operands will be treated as string AFTER the first concatenation has occurred.
Before the concatenation, all operations will be evaluated.
The reason for that output is that the + in this context (num1 + " " happens first) is treated as a concatenation operator and the rest is then concatenated too. The other answers suggest parentheses to ensure the num2 and num3 are added first before the string evaluation.
Beacause Precedence wise i.e left to right:
num1+" " will be evaluated making a string of 10
num2+num3 will simply be appended to that string because of + operator in-between
num1+" " and num2+num3 forming 10 2030
try this way
System.out.println(num1+" "+(num2+num3));
For more about precedence and their associativity : http://www.cis.upenn.edu/~palsetia/java/precedenceTable.html

concatenating string and numbers Java

Why is the output different in these cases ?
int x=20,y=10;
System.out.println("printing: " + x + y); ==> printing: 2010
System.out.println("printing: " + x * y); ==> printing: 200
Why isn't the first output 30? Is it related to operator precedence ? Like first "printing" and x are concatenated and then this resulting string and y are concatenated ? Am I correct?
Its the BODMAS Rule
I am showing the Order of precedence below from Higher to Low:
B - Bracket
O - Power
DM - Division and Multiplication
AS - Addition and Substraction
This works from Left to Right if the Operators are of Same precedence
Now
System.out.println("printing: " + x + y);
"printing: " : Is a String"
"+" : Is the only overloaded operator in Java which will concatenate Number to String.
As we have 2 "+" operator here, and x+y falls after the "printing:" + as already taken place, Its considering x and y as Strings too.
So the output is 2010.
System.out.println("printing: " + x * y);
Here the
"*": Has higher precedence than +
So its x*y first then printing: +
So the output is 200
Do it like this if you want 200 as output in first case:
System.out.println("printing: "+ (x+y));
The Order of precedence of Bracket is higher to Addition.
Basic math tells you that adding numbers is done each at a time.
So "printing: " + x is computed first. As it s a string + int the result is "printing: 20". Then you add y so "printing: 20" + y equals "printing: 2010".
In the second case, multiplying is prioritary. So first x * y is calculated and equals 200. Then "printing: " + 200 equals "printing: 200".
The results that you observe are certainly related to operator precedence and also the order of evaluation. In the absence of another rule, i.e. an operator of higher precedence, operators are evaluated in order from left to right.
In the first expression, all operators have the same precedence, because they're the same operator: +, and so the first operation is evaluated. Since it involves a String, it is String concatenation, and the result is a String; similarly for the following +.
In the second expression, one of the operators is *, which has higher precedence than +, and so is evaluated first. You get the result of the multiplication, an integer, and then the concatenation of a String and an int due to the +.
This will print 30:
System.out.println("printing: " + (x + y))
You need the parentheses to express the precedence you wish for.
It is for operator precedence
System.out.println("printing: " + x * y);
here * operator has more precedence than + so first it calculate x * y.
System.out.println("printing: " + x + y);
Where as here all are same operator and it will be treated as String concatenation operation as there is one string value is there.
if you involve bracket into this - System.out.println("printing: " + (x + y));
Then bracket ( operator has more precedence than + so first it will calculate (x + y) and will print 30
check detail operator precedence order
In the first printing line, the + operator is applied first between the String and the int and the result is a String which is again concatenated with another int resulting a String.
In the second line, the order of the operations is: first the multiplication and the resulted int concatenated to the String.
System.out.println("2*("+a"+"+b"*"+c")")
How to print this

Categories