• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

about varibles initialize

 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
i know that in a method the varibles must initialized before we refer it.in some situations eg;if() and swith() clause ,how can i determin if the varibles are initialized .
int i;
int j=2;
if(j==2)i=0;
System.out.println(i);//this results compile error
int i;
int j=2;
if(2==2)i=0;
System.out.println(i);//this compiles OK
can you tell me ? thank you

 
Ranch Hand
Posts: 327
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
cc to me if i am using a variable in a switch or if statement,
i know the value, but the compiler does not until runtime.
So the condition may or maynot evaluate to true, resulting
that variable i in your eg. is not initialized.
In other case when i use a value in the expression if(), both the compiler and you
know that it is going to be evaluated to either true or false.
So better use in such a way that the other variable i is initialized.
 
Scott Xia
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thank you , Angela
 
Ranch Hand
Posts: 356
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Scott,
In the first code snippet, you are trying to print the value before it is initialized (its initialization is conditional , which may in turn false and there may be no initialization) try this code:
===========================================================
int i;
final int j=2;
if(j==2)i=0;
System.out.println(i);//this compiles OK
===========================================================
Here the variabale j has a final value and it behaves as constant, so the initialization of i is guaranteed (in this condition) and it will compile and execute.
HTH
--Farooq
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic