Language – Java/C++ | Type – Problem (Code) | Last date 19-Apr-2009 12:00 p.m. IST | Points 5
I was attending a session the other day and the instructor was adamant that the Java language is pretty cool (which it is – I just love it). To illustrate his point he referred to the fact that we cannot use a ‘=’ sign in a ‘if condition’ causing problems like it did in C/C++.
"Of course you can use a single = to in a 'if condition'. I have seen that happen so many times" I blurred out. "No way" he challenged. Care to take up this challenge for me?
Got an answer? Why don’t you leave it here.
I suppose you refer to this:
ReplyDeleteboolean b;
if (b = true) {
// compilation warning, but no error
}
The only thing that Java doesn't do is automatically consider non-null values as boolean values. Assignment expressions do not receive special treatment.
int i = 0;
ReplyDeleteif ((i = 1) == 0) {
System.out.println("This should not happen!");
} else {
System.out.println("It worked!");
}
boolean t = true;
ReplyDeleteboolean f = false;
if (t = f) {
// just a warning
}
if (!(t = f)) {
// not even a warning
}
boolean foo = true;
ReplyDeleteif (foo = false) {
// unreachable
}
Scenario 1, it fails
ReplyDeletepublic class SimpleTest1 {
public static void main(String[] args) {
int i = 10;
if (i = 9) {
System.out.println("i not equal to 10");
}
}
}
Scenario 2, it works fine
public class SimpleTest2 {
public static void main(String[] args) {
boolean possible = false;
if (possible = true) {
System.out.println("possible is true");
}
}
}
In scenario 1, it fails with the following error
SimpleTest1.java:6: incompatible types
found : int
required: boolean
if (i = 9) {
^
1 error
This is because, if statement always excepts the expression should result in boolean value.
A common example is
ReplyDeleteBufferedReader br = ...
String line;
while((line = br.readLine()) != null) {
// do something with the line
}
Another odd use of = is in combination with assert.
ReplyDelete// debug is true is assertions have been turned on.
boolean debug = false;
assert debug = true;