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
Related
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.
In HQL, i have used following query.
queryBuilder.append("SELECT cc FROM com.atulsia.core.model.CoupenCode as cc WHERE cc.segment.id = -1 or "
+" ( CASE WHEN (cc.category.id == "+product.getCategory().getId()+") THEN cc.subCategory.id = -1 ELSE NULL END ) or"
+" cc.subCategory.id = "+product.getSubCategory().getId()+" and cc.status.statusId = 9");
But i am getting exception.
org.hibernate.hql.ast.QuerySyntaxException: unexpected token: =
Thanks in Advance
Your HQL query has two errors:
queryBuilder.append(
"SELECT cc FROM com.atulsia.core.model.CoupenCode as cc
WHERE cc.segment.id = -1 or "
+" ( CASE WHEN (cc.category.id == "+product.getCategory().getId()+") THEN cc.subCategory.id = -1 ELSE NULL END ) or"
+" cc.subCategory.id = "+product.getSubCategory().getId()+" and cc.status.statusId = 9");
Equals in HQL is the same of SQL so you must use one = and not ==
The second:
CASE WHEN (cc.category.id == "+product.getCategory().getId()+")
THEN cc.subCategory.id = -1 <--- You can't assign here
and in ELSE you put NULL.
Aren't congruent
Solution
"SELECT cc FROM com.atulsia.core.model.CoupenCode as cc " +
" WHERE cc.segment.id = -1 or " +
"cc.subCategory.id = " +
" (CASE " +
" WHEN (cc.category.id = "+product.getCategory().getId() + ")" +
" THEN -1 ELSE cc.subCategory.id END ) or " +
" cc.subCategory.id = "+product.getSubCategory().getId()+ " and cc.status.statusId = 9"
I am working on something that should be able to delete nodes from xml files that match a given value so e.g.
if a nodes id is equal to 3 delete it
Here is my problem I am comparing 2 strings one is the string that says what we are looking for and the other is the node value they are both exactly the same yet they are returning false in a .equals()
String i am passing = "James1"
String found = "James1"
There are no differences at all between both of these strings what is going on here?
if (value.item(j).getAttributes().getNamedItem("column").getNodeValue().equals(where)) {
Log.d("DataStore", "Node Value: " + value.item(j).getTextContent() + " length: " + value.item(j).getTextContent().length() + " equal to: " + equalTo + " length: " + equalTo.length());
if (value.item(j).getTextContent().equalsIgnoreCase(equalTo)) {
dataNode.removeChild(rows.item(i));
count++;
}
}
This line here is where it fails but should be a success
if (value.item(j).getTextContent().equalsIgnoreCase(equalTo)) {
Here is what it logs out when it gets that far i can assure you these strings are exactly the same.
Node Value: James2 length: 6 equal to: James2 length: 6
You do not provide enough data to give a definitive answer.
Add this line before the if that is failing :
compareStr( value.item(j).getTextContent(), equalTo);
And add this method to your class or an utility class
public static void compareStr(Object a, Object b)
{
if (a==null && b==null)
{
System.out.println("Both null");
return;
}
if ( a==null || b==null )
{
System.out.println( "1st String is "
+ ( a==null ? "" : "not " )
+ "but 2nd String is "
+ ( b==null ? "" : "not " )
+ "null" );
return;
}
if ( !( a instanceof String) )
{
System.out.println( "1st Object is not a String");
return;
}
if ( !( b instanceof String) )
{
System.out.println( "2nd Object is not a String");
return;
}
String s = (String)a;
String t = (String)b;
if ( s.length()!=t.length() )
{
System.out.println( "Lenghts differ");
return;
}
for ( int i=0; i<s.length(); ++i )
{
if ( s.charAt(i)!=t.charAt(i) )
{
System.out.println( "The character at position " + i + " are different.");
return;
}
}
System.out.println("Strings are equal");
}
It will tell you what is different in both strings.
If they are still equal then you should consider if the involved methods have side effects.
Change your code to :
if (value.item(j).getAttributes().getNamedItem("column").getNodeValue().equals(where)) {
String s = value.item(j).getTextContent();
Log.d("DataStore", "Node Value: " + s + " length: " + s.length() + " equal to: " + equalTo + " length: " + equalTo.length());
compareStr( s, equalTo );
if (s.equalsIgnoreCase(equalTo)) {
dataNode.removeChild(rows.item(i));
count++;
}
}
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.
Could anyone please tell me what is wrong with the following code. It doesn't show any result.
The integer a,b,c are the side of an right angle triangle.(was solving Project Euler problem 39)
If I use || in place of && , it shows the desired result based on the || condition. But doesn't work with the && condition
public static void main(String[] args) {
int a,b,c;
for (a=1;a<120;a++){
for(b=120;b>0;b--){
c= 120-(a+b);
if (((c) > (a+b)) && ((c*c)==(a*a)+(b*b))){
System.out.println(a + " , " + b +" , " + c);
System.out.println("**************");
}
}
}
}
Quite simply, it's because this expression:
((c) > (a+b))
...never returns true in your example for any valid right angled triangles, and since the && condition requires both operands to evaluate to true, the if statement isn't executed.
You can see this quite clearly if you put in the following lines:
System.out.println("C: " + c);
System.out.println("A+B: " + a+b);
second part of && condition will always be false if first it true. if c > (a+b) then c*c > (a+b)*(a+b) => c^2 > a^2 + b^2 + 2ab then c^2 != a^2 + b^2
Isn't a+b always 121? making c always -1, making c > a+b an illogical comparison? Just what are you attempting to do here?
Anyway, add some System.outs after each { so you know what is happening.
Also add System.out.println( c + " " + a + " " + b + " " + (a+b) + " " + (c*c) + " " + ((a*a)+(b*b))); to see all the parameters in your comparison to make sure you get what you expect before the if itself.
Mathematically both this conditions will never be true that is why && results into false and || works as one of the condition is true in a situation.
(c > (a+b)) && (c*c==(a*a)+(b*b))
If a number is greater than sum of two number then square of the number will be also greater then sum of square of two numbers.
try this
int a,b,c;
for (a=1;a<120;a++) {
for(b=120;b>0;b--){
c= 120-(a+b);
System.out.println(c+">"+(a+b)+" && "+(c*c)+" == "+((a*a)+(b*b)));
if (((c) > (a+b)) && ((c*c)==(a*a)+(b*b))){
System.out.println(a + " , " + b +" , " + c);
System.out.println("**************");
}
}
}
}
and check yourself
i.e.
-66>186 && 4356 == 17330
-65>185 && 4225 == 17137
-64>184 && 4096 == 16946
-63>183 && 3969 == 16757
-62>182 && 3844 == 16570
-61>181 && 3721 == 16385
-60>180 && 3600 == 16202
-59>179 && 3481 == 16021
-58>178 && 3364 == 15842
...