String s = new String("5");
System.out.println(1 + 10 + s + 10 + 5);
output of the following function is 115105 how ?
"+" is left associative so
1 + 10 => 11(int)
11 + s => "115"(String)
"115" + 10 => "11510"(String) 10 is converted to String
"11510" + 5 = "115105"(String) 5 is converted to String
Your code effectively functions as integer summation as long as it's possible, because the evaluation process goes from left to right. Once the String is encountered, the function switches to concatenation.
1 + 10 + "5" + 10 + 5
= (1 + 10) + "5" + 10 + 5
= 11 + "5" + 10 + 5
= 115105
String s = new String("5");
System.out.println(1 + 10 + s + 10 + 5);
Since expressions are evaluated from left to rignt your code is same as
System.out.println((((1 + 10) + "5") + 10) + 5);
So first (1 + 10) is evaluated and since it is simple integer addition you are getting 11 so your code becomes
System.out.println(((11 + "5") + 10) + 5);
Now (11 + "5") is evaluated and since one of arguments is String, it is being concatenated and result will also be String. So 11 + "5" becomes "11"+"5" which gives us String "115".
So after that our code is same as
System.out.println(("115" + 10) + 5);
and again in ("115" + 10) one of arguments is String so we are getting "115"+"10" which gives us another String "11510".
So finally we are getting to the point where we have
System.out.println("11510" + 5);
which is same as
System.out.println("115105");
(1 + 10)and 10 and 5 are regarded as three strings in your code
Java casts the integers as a string when you include a string in the addition, it becomes concatenation. Try
import java.io.*;
import java.util.*;
import java.lang.*;
public class mainactivity {
public static void main(String a[]) {
String s = new String("5");
System.out.println((1 + 10) + s + (10 + 5));
}
}
This should output 11515.
Related
String literal1 = "java";
String object = new String("java");
String literal2 = "java";
System.out.println("result 1 = " + (literal1 == object) );
System.out.println("result 2 = " + literal1.equals(object));
System.out.println("result 3 = " + literal1 == object);
System.out.println("result 4 = " + literal1.equals(object));
System.out.println("result 5 = " + literal1 == literal2);
System.out.println("result 6 = " + literal1.equals(literal2));
Expected output
result 1 = false
result 2 = true
result 3 = false
result 4 = true
result 5 = false
result 6 = true
output obtained
result 1 = false
result 2 = true
false
result 4 = true
false
result 6 = true
When this line
System.out.println("result 5 = " + literal1 == literal2);
is changed to
System.out.println("result 5 = " + (literal1 == literal2));
Output
result 5 = true
Could anyone please explain why this is happening?
It happens because expressions are evaluated left-to-right so it will first concatenate your string (i.e. "result 3 = " + literal1) and then check for truthiness (i.e. == object), hence printing only false because the result of the concatenation is not of the same value as object.
In the first (and last) example ("result 1 = " + (literal1 == object)) you direct the default evaluation with brackets forcing (literal == object) to evaluate separately before the concatenation which is why it prints false only for that evaluation, concatenated with the string preceding it.
TLDR: it's precedence, not left-to-right
Java does have a rule that operands are evaluated left-to-right, but that has no effect here.
Also in Java all binary (meaning two-operand, not bitwise) operators other than assignment are left-associative, but that does not apply here because associativity only matters when operators have the same precedence.
What matters here is that + has higher precedence than == so as VietDD says
System.out.println("result 5 = " + literal1 == literal2);
# is equivalent to
System.out.println(("result 5 = " + literal1) == literal2);
# which is false because they aren't the same object
which happens to be the same as grouping to the left.
But if we consider instead
System.out.println(literal1 == literal2 + " is result 5!");
# THAT is equivalent to
System.out.println(literal1 == (literal2 + " is result 5!"));
# ditto
which happens to be the same as grouping to the right.
System.out.println("result 3 = " + literal1 == object);
System.out.println("result 5 = " + literal1 == literal2);
is equivalent to
System.out.println( ( "result 3 = " + literal1 ) == object);
System.out.println( ( "result 5 = " + literal1 ) == literal2);
It's String Concatenation
The expression is evaluated left to right.
If either operand is a String, + means concatenation
You can try this :
System.out.println( 1 + 2 + "3");
Output :
33
1 + 2 = 3
3 + "3" = "33"
And
System.out.println( "1" + 2 + 3);
Output:
123
"1" + 2 = "12"
"12" + 3 = "123
This question already has answers here:
Java: sum of two integers being printed as concatenation of the two
(10 answers)
Closed 5 years ago.
Code:
class Foo
{
public static void main(String[] args)
{
int x[] = new int[5];
for(int i=0;i<5;i++)
x[i]=i*i;
for(int i=0;i<5;i++)
{
System.out.println("Value #" + i+1 + " = " + x[i]);
}
}
}
The Output:
tk#insomniac-tk:~$ java Foo
Value #01 = 0
Value #11 = 1
Value #21 = 4
Value #31 = 9
Value #41 = 16
So, what's going on here? Where am I messing up my java code? I mean why is it that in Java, the i+1 means literally i concat 1?
public class Foo
{
public static void main(String[] args)
{
int x[] = new int[5];
for(int i=0;i<5;i++)
x[i]=i*i;
for(int i=0;i<5;i++)
{
System.out.println("Value # " + (i+1) + " = " + x[i]);
}
}
}
try this
In Strings the + operator is used for concatenate, so because you did not specidy any parenthesis, your i and 1 are also concatentate, you need to use parenthesis to explicitly tell that they to be sum together :
for (int i = 0; i < 5; i++) {
System.out.println("Value #" + (i + 1) + " = " + x[i]);
}
To get :
Value #1 = 0
Value #2 = 1
Value #3 = 4
Value #4 = 9
Value #5 = 16
Next to that, another way using IntStream, which will do same :
IntStream.range(0, 5)
.mapToObj(i -> "Value #" + (i + 1) + " = " + (i * i))
.forEach(System.out::println);
The + means something like concat, if you want the expression to be evaluated put it into brackets
(i + 1) not i + 1
This line:
System.out.println("Value #" + i+1 + " = " + x[i]);
And in particular
"Value #" + i+1 + " = " + x[i]
Is syntactic sugar for the following code:
new StringBuffer().append("Value #")
.append(i)
.append(1)
.append(" = ")
.append(x[i])
.toString();
What you want is this:
"Value #" + (i+1) + " = " + x[i]
Which would translate to
new StringBuffer().append("Value #")
.append(i+1)
.append(" = ")
.append(x[i])
.toString();
Because in this case, Java append i to your String, then 1 to your String.
To evaluate the value first (and produce the result you are expecting here), you have to inform Java that you want to evaluate the value before it is appended, using parenthesis:
System.out.println("Value #" + (i+1) + " = " + x[i]);
Output
Value #1 = 0
Value #2 = 1
Value #3 = 4
Value #4 = 9
Value #5 = 16
The key reason the Java and C++ programs differ is because the operators used are different:
System.out.println("Value #" + i+1 + " = " + x[i]); // Java
cout << "Value # " << i + 1 << " = " << x[i] << endl; // C++
The + operator has a higher precedence and hence the addition is done before the overloaded << operator.
In the Java version it is all +s and so they are all evaluated left to right.
problem is in system.out.println("");,where all integers will concatinate into string when added using(+) with a string variable .Try different code for different operations with integer and string variables.
You cannot simply add an integer into a string. You must convert an integer to a string with Integer.toString(int),then add the returned value to the string.
This question already has answers here:
How can I pad a String in Java?
(32 answers)
Closed 9 years ago.
Within a method, I have the following code:
s = s + (items[i] + ":" + numItems[i]+" # "+prices[i]+" cents each.\n");
Which outputs:
Candy: 5 # 50 cents each.
Soda: 3 # 10 cents each.
and so on . . .
Within this line, how do I get the 5, 3, etc . . to line up with each other so that it is:
Candy: 5 # 50 cents each.
Soda: 3 # 10 cents each.
This is part of a toString() method, so I can't do it with a System.out.printf
String.format() and the Formatter classes can be used.
Following code will output something like this
/*
Sample Text #
Sample Text#
*/
Code
public static String padRight(String s, int n) {
return String.format("%1$-" + n + "s", s);
}
public static String padLeft(String s, int n) {
return String.format("%1$" + n + "s", s);
}
public static void main(String args[]) throws Exception {
System.out.println(padRight("Sample Text", 15) + "#");
System.out.println(padLeft("Sample Text", 15) + "#");
}
Some more snippet for formatting
String.format("%5s", "Hi").replace(' ', '*');
String.format("%-5s", "Bye").replace(' ', '*');
String.format("%5s", ">5 chars").replace(' ', '*');
output:
***Hi
Bye**
>5*chars
Apart from this Apache StringUtils API has lot of methods like rightPad, leftPad for doing this.
Link
You can use the tab character \t in your toString()
Heres an example:
System.out.println("Candy \t 5");
System.out.println("Soda \t 10");
Candy 5
Soda 10
So in your case
s = s + (items[i] + ": \t" + numItems[i]+" # "+prices[i]+" cents each.\n");
You can maybe use the \t for inserting a tab.
try this
s = s + (makeFixedLengthString(items[i]) + ":" + numItems[i]+" # "+prices[i]+" cents each.\n");
public String makeFixedLengthString(String src){
int len = 15;
for(int i = len-src.length(); i < len; i++)
src+=" ";
return src;
}
I am noticing odd behavior, at least to me, in my program.
Incorrect output:
public static void main(String[] args)
{
while(count < 3)
{
System.out.println("Count: " + count);
System.out.println("" +(count*2)+1);
count++;
}
}
Yields the following print statements:
Count: 1
21
Count: 2
41
Whereas this program:
public static void main(String[] args)
{
while(count < 3)
{
System.out.println("Count: " + count);
System.out.println((count*2)+1 + "");
count++;
}
}
yields this output:
Count: 1
3
Count: 2
5
My question is does Java 7 do something special when you put the empty string, "", at the front of a arithmetic expression that it does not do when the empty string follows that arithmetic expression?
The + operator has two meanings.
number + number means addition; string + anything means string concatenation.
The + operator is left-associative.
Therefore, "" + a + b" is parsed as ("" + a) + b
You have a problem with brackets.
("" +(count*2)) + 1
and
(count*2 + 1) + ""
are not the same.
Whenever I type in a phone number, this program below that I wrote to format phone numbers from the user gives me back weird numbers that I did not even enter at all. Can someone please explain to me why I am getting such weird errors?
I want it so when someone enters just 12345678978 it will format to 1-234-567-8978
If they enter 2345678978 it will format to 234-567-8978
And if they enter 5678978 it will change to 567-8978.
I always get weird numbers that sometimes aren't even what I entered like
12345678978 I get 144-34--567-
2345678978 I get 153-567-8978
5678978 I get 162-8978
I would really appreciate some help. Thanks.
import java.util.Scanner;
public class Test3 {
public static void main(String[] args) {
Scanner y = new Scanner(System.in);
String phoneNumber;
int phoneNumberLength;
System.out.print
("Please enter your phone number WITHOUT spaces or dashes: ");
phoneNumber = y.nextLine();
phoneNumberLength = phoneNumber.length();
if (phoneNumberLength == 11) {
phoneNumber = phoneNumber.charAt(0) + "-" + phoneNumber.charAt(1)
+ phoneNumber.charAt(2)
+ phoneNumber.charAt(3)
+ "-" + phoneNumber.charAt(4) + phoneNumber.charAt(5)
+ phoneNumber.charAt(6)
+ "-" + phoneNumber.charAt(7) + phoneNumber.charAt(8)
+ phoneNumber.charAt(9)
+ phoneNumber.charAt(10);
}
if (phoneNumberLength == 7) {
phoneNumber = phoneNumber.charAt(0) + phoneNumber.charAt(1)
+ phoneNumber.charAt(2)
+ "-" + phoneNumber.charAt(3) + phoneNumber.charAt(4)
+ phoneNumber.charAt(5) + phoneNumber.charAt(6);
}
else {
phoneNumber = phoneNumber.charAt(0) + phoneNumber.charAt(1)
+ phoneNumber.charAt(2)
+ "-" + phoneNumber.charAt(3) + phoneNumber.charAt(4)
+ phoneNumber.charAt(5)
+ "-" + phoneNumber.charAt(6) + phoneNumber.charAt(7)
+ phoneNumber.charAt(8)
+ phoneNumber.charAt(9);
}
System.out.println("So your phone number is " + phoneNumber + "?");
}
By the way. I know it is not formatted correctly but I am very confused with how stackoverflow allows you to add code.
Java is converting the characters from your charAt() calls to numerical values. Use substring methods instead, e.g.
phoneNumber = phoneNumber.substring(0, 3) + "-" + phoneNumber.substring(3);
Any string that starts like this:
number = number.charAt(0) + number.charAt(1) + ...
will cause the problem, because you are adding two char types together. This is treated as integer arithmetic, not string concatenation. It would be a lot better to add substrings together, so that the operator is string concatenation, instead of integer addition.
number = number.substring(0, 3) + '-' + number.substring(3, 6) + ...