From the course: Learning Java 11
Unlock the full course today
Join today to access over 22,600 courses taught by industry experts or purchase this course individually.
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 variable's scope. Now, let's say we created a string variable called…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.
Contents
-
-
-
-
-
(Locked)
Mapping out program control flow3m 57s
-
(Locked)
Operators in Java2m 26s
-
(Locked)
Decision-making with if in Java4m 8s
-
(Locked)
Understanding scope in Java1m 39s
-
(Locked)
While loops (conceptually)1m 53s
-
(Locked)
While loops in Java3m 19s
-
(Locked)
Challenge: Multiple choice2m 22s
-
(Locked)
Sample solution: Multiple choice5m 1s
-
(Locked)
-
-
-
-