1
public class If {
public static void main(String[] args) {

var myVar = "Emma";
int myInt = 1;

    if (!(myVar == myInt)) {

        System.out.println("Access granted.");

    }

}
}

I am learning Java now. What I should do now is to print out 'true'.

First, I tried declaring the var and int. Then I put ! operator to change 'false' into 'true'.

I thought this would work, but it doesn't. Why doesn't it work? Shouldn't I declare anything when I use the if statement? Thank you

5
  • 1
    var in Java?? Commented May 20, 2017 at 17:10
  • 1
    var is not used to declare variables in Java. Commented May 20, 2017 at 17:10
  • 1
    var is not a type in java. So your code does not compile Commented May 20, 2017 at 17:10
  • 1
    javascript ? scala? Commented May 20, 2017 at 17:11
  • I guess myvar is a String. You have to use equals to compare Commented May 20, 2017 at 17:13

3 Answers 3

2

the accepted answer is wrong

Contarary to what @dasblinkenlight's answer suggests, you can't compare the values of different type, even with equals. You first need to convert them into same type and then call equals, ofcourse it depends on how a class has overridden equals() method as well, e.g.:

String myVar = "1";
int myInt = 1;
System.out.println(myVar.equals(String.valueOf(myInt)));
System.out.println(myVar.equals(myInt));

This will print true and false with and without conversion.

Sign up to request clarification or add additional context in comments.

Comments

1
  1. You can't equal string to integer type. It's different types. Read OCA.
  2. Make variable strong type. Not var but string.
  3. Not (!(statement)) but (!statement)

Comments

-1

== cannot be used for comparison between an int and a String. However, you can use equals method:

if (!myVar.equals(myInt)) {
    ...
}

This is possible because of autoboxing.

Obviously, the comparison is going to fail regardless of the value of 'myVar' because the types are different. If you need to compare a string to an int reliably, first convert your string to int, and then compare with ==.

Of course, you need to declare myVar properly with String type.

2 Comments

equals with String and int will return false, even if the values are same. E.g. String var = "5";int var1 = 5;System.out.println(var.equals(var1));
@DarshanMehta of course, this will never return true. I assumed that's what OP wanted to achieve, though. Anyway, I added a brief explanation of what to do if he wanted to compare a string and an int.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.