Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

why will this compile coreectly  RSS feed

 
Chad McAtee
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey folks,

I am new to this site as well as java programming. Dont understand the logic behind while this compiles correctly.



also with the if(true) statement what condition is being tested as being true?

However this compiles with the error variable not initialized
 
Markas Korotkovas
Greenhorn
Posts: 21
Eclipse IDE Java Mac
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
it makes it a lot easier to read your post if you surround your code by {code} brackets. But anyway in the first snippet you are declaring 2 int variables weight and thePrice. You are also initializing the weight with a value of 10. thePrice is not initialized at this point. The condition if(true) is alway true, so the next statement right after it will always execute and initialize thePrice with a value of 1000. By changing the condition in the second snippet the statement of never executes and when you get to the line that prints the result thePrice variable is never initialized and therefore will result in an error.
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the ranch Chad.

The code brackets Markas is talking about are explained here. I've added them for you this time.
 
Anbarasu Aladiyan
Ranch Hand
Posts: 182
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Below are some small snippets and behavior of compiler:
Above code causes compiler error because value of 'a' can be changed
Above cod compiles fine because if condition cannot be false
Above cod compiles fine because value of a cannot be changed (since a is final)
Above cod compiles fine because thePrice variable will be initialized to at least some value.

So compiler expects a constant (because it should not get changed by any other codes) to make sure conditions succeeds always.
 
Anbarasu Aladiyan
Ranch Hand
Posts: 182
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
and Welcome to javaranch
 
Jatin Vij
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@<Anbarasu Aladiyan> That's an awesome explaination! Helped me brush up my concepts even though I've been writing in Java for some time now.
Good job!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!