• 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

java data types initializing

 
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have a problem in when primitive data types initialized.




this will give the output or error as the variable y is getting read before being properly initialized.but in this below code the variables got initialized to 0,what is the difference here.can anyone explain?


 
Sheriff
Posts: 9707
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Local variables (variables declared inside methods) are not automatically initialized. Fields declared at class level are automatically initialized to the default value of their datatype...
 
Ranch Hand
Posts: 120
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This may help!!
 
Ranch Hand
Posts: 2066
IntelliJ IDE Clojure Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


The local variable should be initialized before they are used. The compiler will evaluate this value in all possible ways, that it thinks. And since we know that, in the above code, you initialized the variable y in all logically possible way with a poor if conditions, that's way it flags Compilation Error, saying that the variable y may not be initialized, if you change the as follows, you won't get Compilation Error. because you initialized the variable y in all the possible ways, that it thinks!







 
Ranch Hand
Posts: 74
Netbeans IDE Tomcat Server Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
the compiler can't know for sure if the If-statements are going to execute,so it thinks that y is uninitialized
 
Look! It's Leonardo da Vinci! And he brought a tiny ad!
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic