课程: Learning Java 17
Understanding scope
- [Instructor] In the fortune teller program, only the if block or the else block was executed, not both. This has to do with a topic called scope. Scope refers to the region of a program where a piece of code is accessible or in which it can be used. Every time we use curly braces in Java, we're 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 braces. Why does this matter? Let's say I created an int variable called favoriteNumber with the value five in the if block. The variable's scope is within the block in which it's 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 wasn't created in the curly braces of the else block, it cannot be used in the else block because the else block is outside the variable scope. Now let's say we create a string variable called favoriteFood outside the if-else block. It's in the main function and we give it the value pizza. Since favoriteFood is created outside the if-else block in the parent set of parentheses, the variable can be accessed and assigned a new value within both the if block and the else block. The favoriteFood scope or where favoriteFood can be accessed is anywhere within the curly braces it was created in.
随堂练习,边学边练
下载课堂讲义。学练结合,紧跟进度,轻松巩固知识。