wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes What is the difference between these boolean expression Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "What is the difference between these boolean expression" Watch "What is the difference between these boolean expression" New topic
Author

What is the difference between these boolean expression

Avais Aziz
Greenhorn

Joined: Oct 07, 2001
Posts: 16
Please shed some light
when I write the following code I get compile time error, it
says that b is not initialized
and when I change the boolean expression to true it works.

Now if I change it like below it works fine

Martin Rennix
Ranch Hand

Joined: Sep 30, 2001
Posts: 34
The code in the first example fails to compile because the b=2 line is dependant on a conditional that could be false. In other words (a>3) might not always be true, in which case b would never get initialised. It's because you have a variable (a) in the conditional expression.
The second example compiles ok because the conditional is always true and hence b will always be initialised.
Bottom line is always initialise your variables when you declare them!
Martin
Avais Aziz
Greenhorn

Joined: Oct 07, 2001
Posts: 16
Thanks! Martin
I asked many people but this is the first proper
answer to this question. Thanks again
Avais
Terence Doyle
Ranch Hand

Joined: May 30, 2001
Posts: 328
HI,
Two solutions:
If you declare a as final the code compiles because the condition will always be true.
OR
if you declare b ouside main() like this:
static int b;
it will then be a class member variable and automatically be assigned a default value at class construction time.
Method variables are not assigned any value because they are considered local variables and must be manually initialised.

Bye,

------------------
Terry Doyle
Sun Certified Programmer for Java 2 Platform


Raising Flares debut album 'Ignition' out now

http://www.raisingflares.com

Terry Doyle <br />SCPJ 1.4 , SCWCD , SCMAD(Beta)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: What is the difference between these boolean expression
 
Similar Threads
Operator Precedence involving && and ||
Presidence in an IF statement
operators
Can you explain me how the static works in this example?
IS this question good? why