开发者

If condition in java

开发者 https://www.devze.com 2023-03-19 21:11 出处:网络
If logic given below works well in C language but it doesn\'t work in java....W开发者_开发问答hy..??

If logic given below works well in C language but it doesn't work in java....W开发者_开发问答hy..??

It gives an error in java while compiling.

class test
  {
    public static void main(String[] args)
    {
    int i;
    if(i=4)
    System.out.println("hello");
    }
  }


You need to use the comparison operator (==) instead of the assignment operator (=) in your if statement.

In C, the result of a valid assignment operator is the value that is assigned. If your example was in C, the resultant code would be equivalent to if(4), which evaluates to a true statement, and the code is always executed without any complaints by the compiler. Java checks for a few cases where you probably mean something else, such as this one.


In C/C++ any non-zero value is considered as true, zero considered false. That is, int and bool are interchangeable. So if (i = 4) is true in C/C++. As i is getting the value 4 and this is equivalent to if (4). But in Java boolean is different from int and you can not use int where boolean is required. Note then, i == 4 is boolean but i = 4 is int. The last one assignment, not compare.


I would not agree that it works well in C. Its confusing, even if it does compile.

This will also print "hello" in C

int i = 0;
if (i == 4) // i == 4 is not true
  cout << "hi";

if (i = 4) // i = 4 which is treated as true
  cout << "hello";

Which is why it is not allowed in Java. You have to write

int i = 0;
if (i == 4) // false
  System.out.println("hello");

The closest you can get to this is problem is using the boolean type.

boolean b = false;
if (b = true)
  System.out.println("hello");

This compiles, but is almost certainly a bug.

One place assignment is commonly used is in reading lines of text

BufferedrReader br = 
String line;
// assigns and checks the value of readLine()
while((line = readLine()) != null) {

}


Note the double equal sign ==

class test
  {
    public static void main(String[] args)
    {
    int i = 4;
    if(i==4)
    System.out.println("hello");
    }
  }


It will compile in C because the condition of and if statement in C can be of type int. However, you assign 4 to i in your condition, and it will not do what you expect it to do in C either.


if (i=4) {
}

will work in C but will not do what you expect. It will in fact check that i is non-0.

Java forces you to have an expression that evaluates to a boolean. Hence you need the == operator. The assignment operator in that case will evaluate to int.

0

精彩评论

暂无评论...
验证码 换一张
取 消