• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

java data types initializing

 
thejaka samarakoon
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • 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?


 
Ankit Garg
Sheriff
Posts: 9528
33
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • 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...
 
Sridhar Gudipalli
Ranch Hand
Posts: 120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This may help!!
 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • 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!







 
Mahmoud Hossam
Ranch Hand
Posts: 74
Linux Netbeans IDE Tomcat Server
  • Mark post as helpful
  • send pies
  • 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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic