Int and Char comparison by "==" [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
Why is this ok? What exactly does it compare?
int i = 10;
char c = 10;
if( c == i)
System.out.println("We are Equal");
And the same in this situation:
String s1 = "Null";
String s2 = new String(s1);
if( s1 == s2)
System.out.println("We are Equal");
I get that we're not comparing the contents of the variable.

In the first example, the two literal values of the integers are being compared, I.e. 10 == 10.
In the second example, your are comparing String objects, meaning the value of the actual Objects, not its content, are getting compared. In order to compare the content of these string objects, I.e. "Blah" == "Blah", you should use the string method String.compare(String strToCompare

Strings are objects. You are comparing references for the strings. Char/ints are primitives so no objects.

Related

Java returning false on comparing two equal strings [duplicate]

This question already has answers here:
What is the difference between == and equals() in Java?
(26 answers)
What is the difference between "text" and new String("text")?
(13 answers)
Closed 3 years ago.
When I execute:
String a = "hello";
String b = "hello";
System.out.println(a==b);
I get output as "true".
But when I run:
String a = new String("hello");
String b = "hello";
System.out.println(a==b);
I get output as "false".
I understand that in the first case, Java makes 'b' point to the same object where 'a' pointed, but why can't it do that in the second case?
String in Java are immutable. Meaning:
String a = "hello";
String b = "hello";
a and b are litterally pointing to the same object in memory
Here you explicitly create a new object
String a = new String("hello");
String b = "hello";
Hence the 2 are not equal.
== compares the memory address. To check if an Object is equal to another in Java you should use the equals method that is on all objects.
If you rewrite System.out.println(a==b); to System.out.println(a.equals(b)); it will be true for both cases
Please read the following well explained answer on stackoverflow:
What is the difference between "text" and new String("text")?

return result of Deque pollFirst() in java [duplicate]

This question already has answers here:
How can I properly compare two Integers in Java?
(10 answers)
Closed 3 years ago.
I was coding an algorithm issue, below code can't pass case
public void pop() {
if (s1.pollFirst() == minStack.peekFirst())
minStack.pollFirst();
}
however below can,
public void pop() {
int tmp = s1.pollFirst() ;
if (tmp == minStack.peekFirst())
minStack.pollFirst();
}
the only difference is how I use s1,pollFirst() return result. I can't figure out real difference here.
Thanks
Comparing two Integer Objects with values less than -128 or bigger than 127 using == will always result in false. However, if you compare Integer with primitive int, it will give you true if the actual value is the same.
int n1=128;
Integer n2=127;
Integer n3=127;
Integer n4=128;
Integer n5=128;
System.out.println(n1==n2); //false
System.out.println(n2==n3); //true
System.out.println(n4==n5); //false
System.out.println(n1==n5); //true
In the second example you are assigning the value to the primitive int, therefore it is automatically unboxed.

The address of a string after concatenation [duplicate]

This question already has answers here:
Are two Java objects with same hashcodes not necessarily equal?
(10 answers)
Hashcode value is same
(9 answers)
How do I compare strings in Java?
(23 answers)
Why do I need to override the equals and hashCode methods in Java?
(31 answers)
Does hashcode number represent the memory address? [duplicate]
(9 answers)
Closed 3 years ago.
I'm trying to see how string object works in Java.
String value1 = "Good";
String value2 = "Good";
System.out.println(Integer.toHexString(value1.hashCode()));
System.out.println(Integer.toHexString(value2.hashCode()));
System.out.println(value1 == value2);
And it shows the same address
21f4dd
21f4dd
true
I know that these 2 variables point to the same object which is stored in heap. But I'm stuck when using concatenation.
String value3 = "Bad";
System.out.println(Integer.toHexString(value3.hashCode()));
value3 += " enough";
System.out.println(Integer.toHexString(value3.hashCode()));
String value4 = "Bad enough";
System.out.println(Integer.toHexString(value4.hashCode()));
System.out.println(value3 == value4);
It shows
103e5
c35f20b
c35f20b
false
After concatenation, there is a new string object whose value is "Bad enough". I assign this object to 2 variables, value3 and value4 also print their address.
My question is that the address of value3 and value4 are the same, so it means they point to the same object but why Java return false when comparing these 2 variables?
When you use + for concatenation, java internally uses StringBuilder. So value3 += " enough"; will be converted to something around the line
value3 = new StringBuilder()
.append(value3)
.append(" enough")
.toString();
here object will be created in the heap memory. Whereas in the value4 case the object is being created in String Pool.
I suggest you to read:
JLS SE8 15.18.1:
An implementation may choose to perform conversion and concatenation
in one step to avoid creating and then discarding an intermediate
String object. To increase the performance of repeated string
concatenation, a Java compiler may use the StringBuffer class or a
similar technique to reduce the number of intermediate String objects
that are created by evaluation of an expression.
Hashcode and equals contract: https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#hashCode()
Hashcode of both the Strings is the same because String overrides default hashCode implementation. It is calculated on the content of String.
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}
The hashcode method of Strings actually doesn't point to the object address in the heap.
To obtain the actual address you can use the Unsafe API. Unfortunately, as far as I know, it isn't officially documented. You can try this to obtain the actual memory address on heap of an object.

How do I return a number representing the count of tiles that match the letter that was passed in to the method? [duplicate]

This question already has answers here:
What is the difference between == and equals() in Java?
(26 answers)
Closed 4 years ago.
For Strings you have to use equals to compare them, because == only compares the references.
Does it give the expected result if I compare chars with == ?
I have seen similar questions on stackoverflow, E.g.
What is the difference between == vs equals() in Java?
However, I haven't seen one that asks about using == on chars.
Yes, char is just like any other primitive type, you can just compare them by ==.
You can even compare char directly to numbers and use them in calculations eg:
public class Test {
public static void main(String[] args) {
System.out.println((int) 'a'); // cast char to int
System.out.println('a' == 97); // char is automatically promoted to int
System.out.println('a' + 1); // char is automatically promoted to int
System.out.println((char) 98); // cast int to char
}
}
will print:
97
true
98
b
Yes, but also no.
Technically, == compares two ints. So in code like the following:
public static void main(String[] args) {
char a = 'c';
char b = 'd';
if (a == b) {
System.out.println("wtf?");
}
}
Java is implicitly converting the line a == b into (int) a == (int) b.
The comparison will still "work", however.

String new Object and comparision [duplicate]

This question already has answers here:
Are two Java objects with same hashcodes not necessarily equal?
(10 answers)
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
As of i know any changes on String a new Object will create,and for some run time activity if there is a content change then a new object will create in Heap are, but i am confusing on below cases, please give idea...
String s8="abcd";
String s9=s8.toUpperCase();
String s11=s8.toUpperCase();
System.out.println("S9 "+s9.hashCode() +" s10 "+s11.hashCode());//S9 -- 2001986 s10 -- 2001986
System.out.println(s9==s11);//false
In the above scenario the address is printing same but the == operator shaowing false.
please tell why address is same and comparision is false.
String s8="abcd"; : Memory will be allocated from constant pool.
String s9=s8.toUpperCase(); New object will be created on heap
String s11=s8.toUpperCase(); Another New object will be created on heap
If you look at the implementation of toUpperCase
public String toUpperCase(Locale locale) {
..
return new String(result, 0, len + resultOffset);
Hence it creates a new object on heap each time. therefore s9 != s11
Note: If two objects are equal then their hashcodes are equal but vice
versa is not true
UPDATE:
String s11=s9.toUpperCase();
s11==s9 // returns true
Because there are not chars which can be modified and therefore s11 and s9 both points to the same object. I strongly recommend to you to read the implementation
== operator is used for reference comperison. Basically when you create s9 and s11 then only 1 object is created in heap. That's why those 2 hashcode is same and 2 different references are pointing same object. That's why s9==s11 has retured false.

Categories