JavaRush /Courses /New Java Syntax /More about variable scope

More about variable scope

New Java Syntax
Level 3, Lesson 4
Available

"The Professor just can't get out of his rut. Old teachers who are used to lecturing are always like this. There's nothing he can tell you that you can't find in books. You don't learn how to swim by listening to swimming lectures. Lectures are only useful when you're familiar with the subject and know almost as much as your professor."

"Still, his lessons are useful."

"Yep. I mean, we hope they are. The more perspectives on the subject you hear, the closer you'll get to the truth. When you hear just one, all you can do is believe it or disbelieve it. OK, let's get back to business."

"Let's look at a picture I've shown you before."

┏
 ┃public class Variables
 ┃┏
 ┃┃{
 ┃┃   private static String TEXT = "The end.";
 ┃┃  ┗━━━━━━━━━━━━━━━━━━━┛
 ┃┃   public static void main (String[] args)
 ┃┃ ┏                         ┗━━━━━━━┛
 ┃┃ ┃ {
 ┃┃ ┃    System.out.println("Hi");
 ┃┃ ┃    String s = "Hi!";
 ┃┃ ┃  ┏┗━━━━┛
 ┃┃ ┃  ┃ System.out.println(s);
 ┃┃ ┃  ┃ if (args != NULL)
 ┃┃ ┃  ┃ {
 ┃┃ ┃  ┃    String s2 = s;
 ┃┃ ┃  ┃   ┗━━━━┛ ┃┃ ┃  ┃ ┏
 ┃┃ ┃  ┃  ┃ System.out.println(s2);
 ┃┃ ┃  ┃  ┗
 ┃┃ ┃  ┃ }
 ┃┃ ┃  ┃ Variables variables = new Variables();
 ┃┃ ┃  ┃ System.out.println(variables.instanceVariable);
 ┃┃ ┃  ┃ System.out.println(TEXT);
 ┃┃ ┃  ┗
 ┃┃ ┃ }
 ┃┃ ┗
 ┃┃   public String instanceVariable;
 ┃┃  ┗━━━━━━━━━━━━━━━┛
 ┃┃   public Variables()
 ┃┃   {
 ┃┃      instanceVariable = "Instance variable test.";
 ┃┃   }
 ┃┃}
 ┃┗
 ┗ 

1. A variable declared in a method exists (is visible) from the start of its declaration to the end of the method.

2. A variable declared in a code block exists until the end of the code block.

3. A method's parameters exist until the method returns.

4. Variables in an object exist during the entire lifespan of the object that contains them. Their visibility is also governed by special access modifiers.

5. Static (class) variables exist the whole time the program is running. Their visibility is also defined by access modifiers."

"Right. I remember this picture."

"Great. Let me remind you about some key points."

"All variables declared inside methods exist (are visible) from the point where they are declared until the end of the method (Example 1)."

"If a variable is declared in a code block, it exists until the end of the code block (Example 2)."

"If a variable is a method parameter, it exists (is visible) in the entire body of the method (Example 3)."

"If a variable is an instance variable (Example 4), it is linked to a certain object and exists as long as the object exists. If no object exists, then there are no instances of the variable. You can access the variable (i.e. the variable is visible) from all methods of the class, regardless of whether they were declared before or after it. A new variable is created for each object. It is independent of other objects. You can't access an instance variable from static methods."

"If a variable is declared static, i.e. marked with the keyword static, it exists as long as its class exists. The JVM usually loads a class into memory at its first use. That's also when static variables are initialized."

More about variable scope - 1

"The example above declares the Cat class, which has four variables: a, b, s (non-static variables), and count (a static variable). If we create several objects of this class (say, three), each of them will contain its own instances of the class's non-static variables. A static variable is shared by all objects of a class. Technically speaking, it isn't even inside these objects, since it existed even before any Cat objects were created."

"Here's what happens if we declare variable s static:"

More about variable scope - 2

"OK. I think I get it."

"Can you declare variables with the same name?"

"Not inside a method. All variables declared inside a method must have unique names. A method's arguments are also considered local variables."

"What about member variables?"

"Member variables must also be unique for each class."

"But there is an exception: the names of local variables and member variables can be identical."

"If we change such a variable, which one of the two identically named variables will be changed?"

"If there are several visible (accessible) variables in our code – say, an instance variable and a local variable – the local variable will be accessed."

Example with two count variables
class Main
 {
     public int count = 0;     // Declare an instance variable

     public void run()
     {
         count = 15;           // Access the instance variable
         int count = 10;       // Declare a local method variable
         count++;             // Access the method variable
     }
 }

"This code declares two count variables. Line 3 declares an instance variable, and line 8 – a local variable."

"Here's what happens when the run method is executed:"

"In line 7, we access the instance variable and assign the value 15 to it"

"In line 8, we declare (create) a new local variable: count. It masks the instance variable. The local variable is what all subsequent code in the method will see (access)."

"Got it."

"The local variable masks the instance variable. In other words, the local variable is the one to be accessed. However, you can access the instance variable, too. It's just a little more complicated to do so."

Static (class) variable
ClassName.variableName

 // Here are some examples:
 Cat.catsCount
Non-static (instance) variable
this.variableName

 // Here are some examples:
 this.catsCount

"What else can you tell me about static methods and static variables?"

"Static methods and variables are not linked to objects of the class; they are linked to the class itself. If we create ten Variables objects (see the example at the beginning of this level), we will have ten instanceVariable variables (one for each object) and only one shared (static) variable TEXT."

"I have a question."

"What's the difference between static and non-static methods?"

"Let's take a look at how a non-static method works:"

What the code looks like
Cat cat = new Cat();
 String name = cat.getName();
 cat.setAge(17);
 cat.setChildren(cat1, cat2, cat3);
What really happens
Cat cat = new Cat();
 String name = Cat.getName(cat);
 Cat.setAge(cat,17);
 Cat.setChildren(cat, cat1, cat2, cat3);

"When you call a method using <object> dot <method name>, you're actually calling a class method and passing that same object as the first argument. Inside the method, the object is called 'this'. All operations in the method are performed on this object and its data."

"Wow! So that's how it all works!"

"And this is how a static method works."

What the code looks like
Cat cat1 = new Cat();
 Cat cat2 = new Cat();
 int catCount = Cat.getAllCatsCount();
What really happens
Cat cat1 = new Cat();
 Cat cat2 = new Cat();
 int catCount = Cat.getAllCatsCount(null);

"When you call a static method, no object is passed to it. In other words, 'this' equals null. That's why a static method can't access non-static variables and methods (since it has no 'this' to pass to these methods)."

"Hmmm. I think I get it. At least a little bit."

"And here comes Uncle Diego... and his tasks."

3
Task
New Java Syntax, level 3, lesson 4
Locked
This age doesn't work for me…
This age doesn't work for me…
3
Task
New Java Syntax, level 3, lesson 4
Locked
Price of apples
Price of apples
Comments (10)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
vakhet Level 26
15 January 2026
Nice!
19 May 2025
Проблема в том, что в задачах переменным в разных классах дают одинаковые имена. Везде сплошной Apple то с маленькой, то с большой буквы. Это путает и сбивает с толку. Попробуйте так: в методе addPrice переменную int applesPrice обзовите как-то по-другому ( например, int abc), тогда возможно будет легче не путаться в бесконечных эпплах.
Ren Level 21
1 April 2024
убиться об стену...
Andrei Karavai Level 30
23 October 2023
The first task deals with variable of one unit (instance) of the class. It's like you have many cakes in the supermarket, but you want to take a peace of this particular cake. So to make changes to the variable of this particular unit, You should adress to it like "this.age" The second task deals with variable of the whole class. It's like you want to change type of cream an all cakes. For example there are cakes with chocolate cream, apple cream, blueberry cream (every unit or instance can have it's own cream type), but You say I want to change the cream for all of them to something particular. So here You have to adress not the variable of one particular unit, but of all units of the class Cake. So to make changes to the variable of the class , You should adress to it like "ClassName.variable". In our example it is "Apple.applePrice" Please remember, that in the first problem if You write simply "age" inside of function(method) "adjustAge" you work the parameter variable, not with class variable or instance variable. The same goes to the second problem. If You write simply "applePrice" inside of function(method) "addPrice" you work the parameter variable, not with class variable or instance variable.
Jony Level 21
3 May 2023
try me
29 November 2022
the information wasn't enough to solve the exercises...
Feliks6817 Level 4
11 October 2022
Actually got nothing.. Had to google info
LipskyiAlex Level 15
17 September 2022
It's a pity but I understand nothing.
Kristina Ray Level 3
1 June 2022
I wonder if this can be explained in a more simple words?... I don't know yet... maybe one day
19 May 2022
Just painfully awful. You have to learn how to match tasks to the level of the learner. When I don't have a vocabulary to make a Google search to find a solution it makes me wonder: "Why I wasn't provided with necessary info? I don't want to spend hours and days looking for the help at the beginners level". Just like in one of your lessons - "if you don't know it, you don't' know it".