From the course: Learning Java 11

Unlock the full course today

Join today to access over 24,000 courses taught by industry experts.

Understanding scope in Java

Understanding scope in Java - Java Tutorial

From the course: Learning Java 11

Understanding scope in Java

- [Instructor] In the Fortune Teller program, during the program's execution, only the if block or the else block was executed. All of this had to do with the topic called scope. Scope refers to the region of the program where a piece of code is accessible or in which it can be used. Every time we use curly braces in Java, we are creating a block in the program. This is why the if block and the else block are separate. They are in different sets of curly brackets. Why does this matter? Let's say I created an int variable named favoriteNumber, with the value, five, in the if block. This variable scope is within the block in which it was created. That's where the variable is accessible and can be used. I can reference it or change its value anywhere inside the if block. However, since it was not created in the curly braces of the else block, it cannot be used in the else block, because the else block is outside this…

Contents