how is the equality between objects done? - java

if we create 3 variables of int type using different declaration statements, for instance,
Integer i = 10;
Integer j = new Integer(10);
int k = 10;
and we compare them for equality, we get i == k and j == k but not i==j.
what is the reason for this?

Since i has type Integer and k has type int, the expression i == k triggers unboxing: it is equivalent to i.intValue() == k (even to the point that it would raise a NullPointerException if i were null). Similarly for j == k. But since i and j both have type Integer, no autounboxing is performed, so i == j simply checks to see if they are the same object — the same instance of Integer.

Because k is primitive and when you compare it with others you only compare its integer value.But the other two are objects. When you compare them with == operator you only check if they are the same object or not.
You should use equals() method to compare Integer objects.The following will return true in your program.
i.equals(j);

Related

While comparing a[j]=42 , I am getting message "cannot from convert int to boolean"

I have this small part of a code. When I compare array a[j] != 42, it works like a charm. But if I tweak it to a[j] = 42 , it says:
cannot convert from 'int' to 'boolean'
What wrong I am doing?
for(int i = 0; i <= 9; i++) {
a[i] = Integer.parseInt(br.readLine());
int j = 0;
do {
if (a[j] = 42)
System.out.println(a[j]);
else {
flag=0;break;
}
j++;
} while (flag == 1);
}
a[j]!=42 is a comparison. a[j]=42 on the other hand, is an assignment of the value.
The correct way to compare them is: a[j] == 42
As the other answers already mention a[j]=42 is an assignment. What you want it to compare two values. I want to include a little bit more information to what exactly is going on here.
Explanation: What your code does is assign 42 to a[j]. a[j] would be contain / be equal to 42 after that line. The assignment itself is fine.
But the compiler expects a boolean expression inside its if (...) to determine wether it should enter the following code block or the one of the else-branch. The assignment operator = in Java returns the assigned value. Therefore the statement a[j]=42 returns 42 which the compiler then wants to get a boolean value from, which it cannot since it cannot convert from int to boolean.
Solution: Use the == operator instead which does not assign at but compares the two values and returns a boolean wether or not the two are identical: if (a[j] == 42)
You must use == for comparing:
if (a[j] == 42)
if(a[j]=42)
This is equivalent to:
a[j] = 42
if(a[j]) {
}
Now, since you are checking 42 as boolean, you get the error: cannot covert from 'int' to 'boolean'
As other answers suggest, you need == for comparison.

Whats the difference between = and == in java?

I know that == means equal to but I cannot figure out what = means.
A single = is assignment. A value is assigned to a variable.
int a = 1; // <-- assign 1 to a.
JLS-15.26.1. Simple Assignment Operator = says (in part)
A compile-time error occurs if the type of the right-hand operand cannot be converted to the type of the variable by assignment conversion (§5.2).
The == is the equality operator, JLS-15.21. Equality Operators says (in part),
The operators == (equal to) and != (not equal to) are called the equality operators.
= means assignment operator which assigns the value on its right to the operand on its left whereas == (Equal to) means equality check.
Say, you want to assign 1 into a variable i, so you have to write:
i = 1;
But if you want to check whether the value of i is 1 or not, you have to check:
if (i == 1) {
//do something
} else {
// do something else
}
= is the assignment operator. E.g., a = 5 means assigning the value of 5 to the variable a.
the operator "=" assign the value to a certain instance
but
an operator "==" means a certain instance has a value of something
example
x = 2; //It means x is 2
x == 2; //means x has a value of 2
= is the assignment operator which is used to assign a value to a variable, property or fields. While == is used to check a condition for example in a if condition
int houseAddress = 1;
This means that the variable houseAddress is given the value of 1, so you can think of this as the address of the house is equal to 1;
if(houseAddress == 1){
//do something
}
This code is saying whether houseAddress is equal to 1 this would return TRUE or FALSE in this case we know that houseAddress is 1 so it return TRUE.
Hope this helps its missing a few technical detail which might confuse you so its missed out.

How to check whether an element of a character array is empty?

I need to check if an element of a java array of characters is empty. I tried out the following code but didn't work. What's wrong?
char c[] = new char[3];
c[0] = 'd';
for (int i = 0; i < c.length; i++) {
if(c[i] == null) {
System.out.println(i + " is empty");
}
}
Let's take arrays out of the equation - an array is just a collection of variables, really. Let's consider a single variable. Suppose we had a method like this:
public boolean isEmpty(char c)
What would that do? The value of c cannot be null, because char is a primitive type. It could be U+0000 (aka '\u0000' or '\0' as character literals in Java), and that's the default value of char (for array elements and fields) but it's not the same as a null reference.
If you want a type which is like char but is a reference type, you should consider using Character - the wrapper type for char just like Integer is for int. Or if you know that you'll never use U+0000 as a valid value, you could just stick with that.
However, a better alternative would often be to design your code so that you don't need the concept of "empty or not empty". We don't know what you're trying to achieve here, but it's usually a good thing to at least consider. For arrays, the alternative is often to use an ArrayList<E> - but of course you can't have an ArrayList<char> in Java as Java generics don't allow primitive type arguments :(
An element of a primitive array can't be null. It will always have a default value if you didn't initialize it yourself. The default for char is 0.
Use Character class instead primitive char.
Character c[] = new Character[3];
c[0] = 'd';
for(int i = 0; i < c.length; i++){
if(c[i] == null){
System.out.println(i + " is empty");
}
}
You cannot use null as char is a primitive type. null only works for objects. use \0 as it's the primitive version of null.
primitive char's default value is 0. you can check it with 0
char c[] = new char[3];
c[0] = 'd';
for(int i = 0; i < c.length; i++){
if(c[i] == 0){
System.out.println(i + " is empty");
}
}
even, char=0 is also a character
Is your code compiling?
You should be seeing an error message at this code line if(c[i] == null)
And from error message, compiler is clearly revealing that "the operator == is undefined for argument type(s) char,null".
This should suffice that element of a primitive array (character array in this case)can't be null.
Replace null with '\0' with the quotes

Java - If statement not catching when variable equals string [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I compare strings in Java?
(This may be a duplicate, I was not aware of .equals. My apologies.)
I was messing around in Java today when I decided to make a 4 character string generator. I have the program generate every possible combination of characters that I defined. This isn't for a project, I just wanted to see if this was possible. My problem lies with the string checking. I'll post the code first.
String text = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
char[] chars = text.toCharArray();
String name = "Mike";
String pass;
outerLoop:
for (int a = 0; a < chars.length; a ++) {
for (int b = 26; b < chars.length; b++) {
for (int c = 26; c < chars.length; c++) {
for (int d = 26; d < chars.length; d++) {
pass = chars[a]+""+chars[b]+""+chars[c]+""+chars[d];
System.out.println(pass);
if (pass == name){
System.out.print("password");
break outerLoop;
}
}
}
}
}
The nested if will check if pass is equal to Mike. If it is, then it prints password and will break the for loop.
Is pass = chars[a]... the correct way to do this? When I tested it without the if, I had it print out pass and it printed all of the combinations correctly. It did print Mike, but it did not catch in the if.
I also changed the nested for loops so they start with the lower case because the program was taking a while to run when I made minor changes.
if (pass == name){
should be
if (pass.equals(name)){
use String.equals() method to check string equality. == operator simply checks if two reference variables refer to the same object. equals() method checks if two strings are meaningfully equal.
Strings should be compared using equals()
This comes up at least once per day. There should be a "close question" option dedicated to it. Nevertheless, here goes again...
The == operator tests if the two operands are the same instance.
The .equals() method compares the values of the two operands, but only if the class has implemented this method (which String does), otherwise it behaves the same as == (which is how the Object class implements it).

Setting a variable to a value in if statement

static int findPerson(String n, int NP, Friend[] giftGivers){
int index = 0;
for (int i = 0; i < NP; i++){
if (giftGivers[i].name == n){
index = i;
}
}
return index;
}
I have this code in Java for a method to search through an array of Friends to find the index number of the person with the name input by String n. however i have found that the index number does not set to the index number it is should be. Is it because it is in the if statement?
if (giftGivers[i].name == n) is wrong, use if (giftGivers[i].name.equals(n))
BTW, there is no need to use NP. It's C-style, not necessary (actually, pretty dangerous) in Java. Instead of
for (int i = 0; i < NP; i++),
just say for (int i = 0; i < giftGivers.length; i++)
You need to use equals to compare strings not ==.
== will compare the object references rather than the actual string value.
If you don't care about case, then there is also an equals method that ignores case
(giftGivers[i].name == n){
should be
(giftGivers[i].name.equals(n)){
String/Object comparison should use .equals() instead of ==
== will check for reference equality. equals() check for object equality.
.equals() method checks for equality of two string objects, == operator checks if two refrence variables point to the same String object.
In your case you have to use .equals() method
if (giftGivers[i].name.equals(n))
refer to String API.
Note that if you wanna check if two strings are equal case insensitive use equalsIgnoreCase()

Categories