Java Programming: 5 - Variable Scope

CodeMonkeyCharlie · 60K views · 2011 · 6:32

Open on YouTube

C, C++, Rust, Go & systems languagesEducation & learningtutorial

Why Stack Overflow recommends it

Stack Overflow users link it when answering beginners who hit "cannot be resolved to a variable" errors because a variable was declared in a different method or block.

Recommended by 2 people across 2 different months, 2013 to 2018.

What it is

A short 2011 Java tutorial by CodeMonkeyCharlie, part 5 of a beginner series, on variable scope. It explains class (static) variables versus local variables declared inside a method, and how long each lives and who can see it.

What people said

Recommends Zorayr · 2013-06 · Stack Overflow · on “cannot be resolved to a variable,where to declare it”

Since you declared cant in calculeaza() , you cannot use it in salveaza() . You should declare it outside as an instance variable [LINK] if you are going to share it between methods. You can learn more about Java Scope here: Java Programming: 5 - Variable Scope [this video] .

Recommends Michael Ziluck · 2018-06 · Stack Overflow · on “Access value of field from another class”

Think of classes as "molds" for creating new objects. In your main method, you use that mold to create a new Test1 object. In the testing method, you use that same mold to create a new Test1 object. However, in that first object you made, you set the of x to 33, but did not do the same thing with that other object. Think about it like a basketball. You have a mold to make basketballs and use it to make two basketballs. You pump up the first basketball to be 33% full of air, but don't put any air into the second one. Just because the same mold was used, does not mean both basketballs are pumped up to 33% air. Edit: Here is a good video explaining scope that should help you out! [this video]

Cites Bongo · 2015-04 · Stack Overflow · on “How to use file path present in one try block in another in java”

This answer is just an addendum to the answer by Rahul. If the answer by him was helpfull mark his answer as the accepted answer and not mine ! The first question was answered by Rahul, if you want to know in depth why this is working maybe you could google java scope introduction and I guess you get many adresses( for example I found this [LINK] and this [this video] ). The short answer is that every opening { starts a new scope for variables and the scope is ended when } is reached. The second error you encounter is because this input = loader.getSystemResources(file1); expects a String variable like "C:\somefile" but you pass a Path variable into it which the method isn't expecting nor underst