sova
sova

Reputation: 5650

Java: set value and check condition at same time

(In the process of writing my original question, I answered it, but the information might be useful to others, and I thought of a new question)

For instance:

int x;
if (x = 5) { ... }

Creates an error:
Type mismatch: cannot convert from int to boolean. (Because assignment doesn't return a
boolean value)

However,

int x; 
if ((x = 5) == 5) { 
    System.out.println("hi!");
}

will print out "hi!"

And similarly,

String myString = "";
if ((myString = "cheese").equals("cheese")) {
    System.out.println(myString);
}

prints out "cheese"

Sadly,

if ((int x = 5) > 2) { ... }

does not work with an in-line declaration. How come? Can I get around this?

Upvotes: 2

Views: 4595

Answers (7)

Stephen C
Stephen C

Reputation: 718886

Sadly,

I suspect that most Java developers would heartily disagree with that sentiment ...

if ((int x = 5) > 2) { ... }

does not work with an in-line declaration. How come?

It does not work because a declaration is not a Java expression, and cannot be used in an Java expression.

Why did the Java designers not allow this? I suspect that it is a combination of the following:

  • Java's syntactic origins are c and C++, and you cannot do this in C or C++ either,
  • this would make the Java grammar more complicated and the syntax harder to understand,
  • this would make it easier to write obscure / cryptic programs in Java, which goes against the design goals, and
  • it is unnecessary, since you can trivially do the same thing in simpler ways. For instance, your example can be rewriten this to make the declaration of x to a separate statement.

Can I get around this?

Not without declaring x in a preceding statement; see above.

(For what it is worth, most Java developers avoid using assignments as expressions. You rarely see code like this:

int x = ...;
...
if ((x = computation()) > 2) {
    ...
}

Java culture is to favour clear / simple code over clever hacks aimed at expressing something in the smallest number of lines of code.)

Upvotes: 6

Upul Bandara
Upul Bandara

Reputation: 5958

if ((int x = 5) > 2) { ... }

Yes this will not compile because you can't declare variables inside the condition section of if clause

Upvotes: 1

Adeel Ansari
Adeel Ansari

Reputation: 39907

You can't declare the variable in condition section. For example

for(int i = 0; j < 9; i++){...}

is completely valid statement. Notice we declare the variable in for but not in a condition clause, now look at this,

for(int i = 0; (int j = 0)<9; i++){...} // Don't try to make logical sense out of it

not allowed.

Upvotes: 0

Sujith Surendranathan
Sujith Surendranathan

Reputation: 2579

In Java, for() allows initialization code, but if() doesn't.

Upvotes: 0

jcomeau_ictx
jcomeau_ictx

Reputation: 38442

Because you didn't declare the int separately as you did in the == test.


jcomeau@intrepid:/tmp$ cat /tmp/test.java
class test {
 public static void main(String[] args) {
  int x;
  if ((x = 5) > 2) System.out.println("OK");
 }
}

Upvotes: 0

akf
akf

Reputation: 39485

The > test will work fine, as long as you declare the int outside of the if condition. Perhaps you are simplifying your condition for the sake of brevity, but there is no reason to put your declaration in the condition.

Can I get around this?

Yes, declare your var outside the condition.

Upvotes: 0

EboMike
EboMike

Reputation: 77752

Your x only exists within the scope of the assignment, so it's already gone by the time you get to > 2. What is the point of this anyway? Are you trying to write deliberately unreadable code?

Your best way to get around this is to declare x in a scope that will remain valid throughout the if statement. Seriously though, I fail to understand what you're doing here. Why are you creating a variable that is supposed to disappear again immediately?

Upvotes: 1

Related Questions