-
August 13th, 2010, 01:28 PM
#1
If statement
why is this java code wrong?
int i=1;
if(i=1)(not checkin a condition but assigning)
{}
and also
if(int i==1)(declaring a variable inside 'if' statement)
{}
-
August 13th, 2010, 01:44 PM
#2
Re: If statement
Originally Posted by arpit2309
why is this java code wrong?
int i=1;
if(i=1)(not checkin a condition but assigning)
{}
In java you can not assign a variable inside a condition
and also
if(int i==1)(declaring a variable inside 'if' statement)
{}
This would evaluate to true - place System.out.println("this works") inside the {}
In java a single = sign assigns a value to a variable - i.e. i=1 sets the variable i to the value 1.
i == 1 is an equality checker, which checks that the variable has the same value as the object on the other side of the == signs. In your example, you set i to be 1 and the == part evaluates to true as it is essentally a (1 equals 1) query.
Last edited by themoffster; August 13th, 2010 at 01:46 PM.
-
August 13th, 2010, 01:58 PM
#3
Re: If statement
I think u didn't get me!!!
Actually i am sry for this!!
These are actually two different codes!!!
Code 1:
int i=1;//settin i=1
if(i=1)(now not checking but assigning:::IN C language this works as cosidered always true)
{}
Code 2:
if(int i==1)(declaring a variable inside 'if' statement)
{}
-
August 13th, 2010, 03:25 PM
#4
Re: If statement
I think u didn't get me!!!
Actually i am sry for this!!
Please don't use text speak, many people here are not native English speakers and may struggle to understand what you are trying to say.
int i=1;//settin i=1
if(i=1)(now not checking but assigning:::IN C language this works as cosidered always true)
{}
In Java the result of a conditional test has to be a boolean, there's no assumption that 0 is false and anything else is true. However it's not strictly true to say you can't make an assignment in a comparison statement, the following is valid even if it isn't very good style:
Code:
if((i=getSomeValue()) == 1)
{// do something }
if(int i==1)(declaring a variable inside 'if' statement)
{}
This won't work because you are comparing the variable 'i' against '1' but you haven't initialized 'i' yet. The question is even if this was valid why would you want to do this, the scope of 'i' would be limited to the conditional statement.
-
August 21st, 2010, 07:42 AM
#5
Re: If statement
Thanks Keang!!!
It was a nice reply!!!
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|