CodeGym /Java Course /Java Syntax /More about variable scope

More about variable scope

Java Syntax
Level 4 , Lesson 1
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."

Comments (188)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Khrysus Level 3, Denver, United States
13 December 2023
Public: A public variable is accessible from any part of your program, including different classes and methods. This is useful when you want a specific value to be widely available throughout your code. For example, if you have a class representing a game score, you might declare a public variable int score; to store the current score. This way, any method in the game can access and update the score easily. Static: A static variable is shared by all instances of a class. This means that when you change the value of a static variable in one object, it changes for all other objects of the same class as well. Static variables are often used to store global values like constants or configuration settings that apply to all objects in the class. For example, you might declare a static variable final int MAX_PLAYERS = 4; in a game class to indicate the maximum number of players allowed. This limit applies to all game instances and cannot be changed individually.
2 November 2023
Some real wisdom on the section about the differnce between static and non-static methods.
Hoist Level 35, San Diego, United States
19 August 2023
This thread is EPIC
abhishe_kira Level 18, India Expert
26 June 2023
As I got stuck in this topic so I'm here to help others. The main aim of this topic is that: - let say you have two class(class1 = Solution and class2 = Main) {Case 1} in class Solution :- you have a static variable as :- 'public static String name'. Note- here 'name' is a variable of String type and having public access modifier, so it can be used in any other class and also it is static. The important thing is that it stores an empty String here. in class Main: you want to use this variable and give it a value for a object (anything in the real world like me and you) 1. You have to use keyword className.variableName ex = Solution.name = "abhi"; {in 2nd case} if you have the same class Solution and Main and in Solution class you have a non static variable as- ''public name'' then it is a non- static variable. So, to use it in another class(Main) you have to use it by using 'this.variableName' ex = this.name = "abhi"; *** Pay more attention here- if in a class you have two or more methods and you want to access a variable of method 1 in method 2, the n also you have to use the same keywords this.variable name (if both methods are non static Ex - public void printSomething{ public String name; } public void setName { this.name = "abhi"; } don't think about method to much for now just pay attention to the variable calling(initialization).
chonksta Level 6, Dallas, United States
23 June 2023
this one had me thinking quite a lot. Just remember that applePrice inside the class brackets and applePrice within a method are DIFFERENT variables. If you want to specify which applePrice to update, you need to put in the class name first e.g. "Cat.name" or "Car.model". The addPrice method is just a tool that is used to update the applePrice that is within the Apple class. Hope this helps.
Anonymous #11359104 Level 3, Darien, United States
23 June 2023
where does the applesPrice come into place? can't seem to link it to anywhere else
Emi Level 3, Delhi, India
21 May 2023
what is " public void run() " ¿¿¿
Reds Level 17, Seattle, United States
8 May 2023
This feels really out of place. I had to go back and make sure that I didn't miss a lesson or something.
Dhora Karthik Goud Level 3, CodeGym University in India, India
19 March 2023
Can any one explain this topic? I am not understanding.
Nadeem Afzal Level 7, Bengaluru, India Expert
7 March 2023
Where is Example 1, Example 2, Example 3 & Example 4, mentioned in the above Lesson?