[Introduction to Java] Variable scope (scope, local variables, instance variables, static variables)

Purpose

For those who have just started learning programming including the Java language, and those who have already learned it, for review I am writing to learn the scope of variables.

Last time, I learned about Type conversion. This time about ** variable scope **.

[Introduction to Java Table of Contents] -Variables and typesType conversion ・ Variable scope ← Now here -String operation -Array operationOperator ・ Conditional branch (in preparation) ・ Repeat processing (in preparation) ・ About class (in preparation) ・ Abstract class (in preparation) ・ Interface (in preparation) ・ Encapsulation (in preparation) ・ About the module (in preparation) -Exception handlingAbout lambda expressionAbout Stream API

What is the scope of a variable?

The valid range of variables that are literally defined. (The range in which the variable can be used is limited by the place where the variable is declared)

・ Local variables -Instance variables ・ Static variables

There are multiple types of names depending on where you declare them.

Let's look at scope using a simple example.

Local variables

The effective range is different for each {} block unit. It can be used in the block after the position where the variable is declared.

Main.java


class Main {
  public static void main(String args[]) {
    String block1 = "Block 1";
    System.out.println(block1); //Block 1

    {
      String block2 = "Block 2";
      //You can access it because it is in the block that declared block2
      System.out.println(block2); //Block 2
      
      //block1 can be accessed
      System.out.println(block1); //Block 1
    }

    //Since it is outside the block that declared block2, a compile error will occur.
    System.out.println(block2); // block2 cannot be resolved to a variable
  }
}

The above is a single block, so a more concrete example ...

** Variables declared in different methods cannot be accessed from another method. ** **

Main.java


class Main {
  public static void main(String args[]) {
    //Declaring and initializing the block1 variable in the main method
    String block1 = "Block 1";
    System.out.println(block1); //Block 1
  }
  
  public static void method() {
    //This method, which is out of range, cannot access the block1 variable, resulting in a compile error.
    block1 = "Block 3"; // block1 cannot be resolved to a variable
  }
}

** Variables declared in if statements cannot be accessed. ** **

Main.java


class Main {
  public static void main(String args[]) {
    String block1 = "Block 1";
    System.out.println(block1); //Block 1

    boolean flg = true;

    if(flg) {
      String block2 = "Block 2";
    }

    //Since the variable block2 is outside the block because it was defined in the if statement, a compile error will occur.
    block2 = "I want to rewrite block 2"; // block2 cannot be resolved to a variable
}

In both cases, the valid range of {} block unit is different, so access is not possible and a compile error occurs.

By the way, Local-Variable Type Inference has been available since JDK 10. Details will be summarized in a separate article at a later date, so I will omit it this time.

Instance variables

Variables declared directly under the class definition.

Person.java


class Person {
  //Define variables under class (instance variables)
  String name;
  int age;
  int height;

  //It can also be accessed from methods in the class (not accessible from static methods; see below)
  public void checkInfo() {
    System.out.print("Name is"+ name + "、");
    System.out.print("Age is"+ age + "、");
    
    if(age < 20) {
      System.out.print("Minor.");
    }

    System.out.println("How tall are you"+ height + "is.");
  }
}

When multiple objects are created (instantiated) with the new keyword based on the Person class The value of the instance variable is different for each instance, and different values can be handled for each object. Access with variable name to which the object is assigned. Instance variable name.

Main.java



class Main {
  public static void main(String args[]) {
    Person tanaka = new Person(); //Create object with new keyword

    tanaka.name = "Tanaka"; //The variable name tanaka to which the object is assigned assigns a value to the instance variable name.
    tanaka.age = 19; // //The variable name tanaka to which the object is assigned assigns a value to the instance variable age.

    System.out.println(tanaka.name); //Tanaka
    System.out.println(tanaka.age); // 19

    //↓ Local variables had to be declared and initialized,
    //Instance variables are automatically initialized.
    System.out.println(tanaka.height); // 0

    tanaka.checkInfo(); //The name is Tanaka, the age is 19, and he is a minor. Height is 0.


    Person suzuki = new Person(); //Create object with new keyword

    suzuki.name = "Suzuki"; //The variable name suzuki to which the object is assigned assigns a value to the instance variable name.
    suzuki.age = 51; //The variable name suzuki to which the object is assigned assigns a value to the instance variable age.
    suzuki.height = 146; //The variable name suzuki to which the object is assigned assigns a value to the instance variable height.

    System.out.println(suzuki.name); //Suzuki
    System.out.println(suzuki.age); // 51
    System.out.println(suzuki.height); // 146

    suzuki.checkInfo(); //His name is Suzuki, his age is 51, and his height is 146.
  }
}

However, it cannot be accessed from the static method.

Instance variables are instantiated and accessed with variable name to which the object is assigned. Instance variable name. You cannot access it unless you specify which instance it is.

So, if you try to access it without being instantiated, you will get a compile error.

Person2.java


class Person2 {
  //Define variables under the class
  String name;
  int age;

  //Also accessible from methods in the class
  public void checkInfo() {
    System.out.print("Name is"+ name + "、");
    System.out.print("Age is"+ age + "、");
  }

  //Instance variables cannot be accessed from static methods, resulting in a compile error
  public static void checkAge() {
    if(age < 20) {
      System.out.print("Minor."); // Cannot make a static reference to the non-static field age
    }
  }
}

About this

When a local variable and an instance variable have the same name, use this to explicitly indicate the instance variable.

-Define an argument with the same name as the instance variable in the function in the class -When the instance variable and the argument have the same name

Person2.java


class Person2 {
  //Define variables under the class
  String name;
  int age;

  public void getName() {
    //If you do not receive an argument, you can define a variable with the same variable name as the instance variable
    String name = "getName()The name I called from is Yamada";
    //Instead of outputting the instance variable, the name defined in this method is output preferentially.
    System.out.println(name);

    //Use this when you want to output the name of an instance variable
    System.out.println("The name of the instance variable is" + this.name);
  }


  public void setAge(int age) {
    //When the same variable name as the instance variable is received as an argument,
    //If you try to define with the same variable name, an error will occur if there are duplicates.
    // int age = 101; // Duplicate local variable age

    //Use this as described above when assigning the received argument to the instance variable
    this.age = age;
    System.out.println("The age of the instance variable set by setAge is" + age);
  }
}

Main2.java


class Main2 {
  //Instance variables
  public static void main(String[] args) {
    Person2 sato = new Person2();
    sato.name = "Sato";
    sato.getName(); 
    // getName()The name I called from is Yamada
    //The name of the instance variable is output as Sato

    sato.setAge(77);
    //The age of the instance variable set by setAge is output as 77
  }
}

static variable (class variable)

Variables declared directly under the class definition. When declaring a variable, it is treated as a static variable by specifying the static modifier. Instance variables held values for each object, Static variables are grouped together in `one place to hold the value (the same value is used for all objects). ``

** Instance variables are variables for each instance, and static variables (class variables) are variables for each class. ** **

Sample.java


class Sample {
  int number = 99; //Instance variables
  static String color = "yellow"; //static variable (class variable)

  //Method to set a value in a static variable (class variable)
  public void setColor(String value) {
    color = value;
  }
}

Therefore, it can be accessed without instantiating the class. Class name.static variable (class variable) name

Main.java


class Main {
  public static void main(String args[]) {
    Sample sample1 = new Sample();

    sample1.number = 10;
    System.out.println(sample1.number); // 10
    sample1.setColor("Red");
    System.out.println(Sample.color); //Red

    Sample sample2 = new Sample();
    //Since the instance variable number is held for each object, the initial value of 99 is included.
    System.out.println(sample2.number); // 99

    //static variables (class variables)Because the color of is shared a common value
    //The default "yellow" is sample1.Red was set at the timing of setColor.
    //Therefore, if you access a static variable (class variable) here, it will be output as red.
    System.out.println(Sample.color); //Red
  }
}

Since static variables (class variables) are common variables of the class, any changes will affect all the parts used.

Timing to use static variables (class variables)

Example) When you want to keep data on how many people were created.

Human.java


class Human {
  //Instance variables
  String name;

  //static variable(Class variables)
  static int count = 0;

  //Static variables when instantiated(Class variables)To+1 do
  Human() {
    count++;
  }

  public static void humanCount() {
    //Check how many people were created
    System.out.println(count + "Person created");
  }
}

Main.java


class Main {
  public static void main(String[] args) {
    Human yamada = new Human();
    yamada.name = "Yamada";
    System.out.println(yamada.name); //Yamada

    //Output static variable (class variable)
    System.out.println(Human.count); // 1

    Human takeda = new Human();
    takeda.name = "Takeda";
    System.out.println(takeda.name); //Takeda

    //Output static variable (class variable)
    System.out.println(Human.count); // 2

    Human oota = new Human();
    oota.name = "Ota";
    System.out.println(oota.name); //Ota

    //Output static variable (class variable)
    System.out.println(Human.count); // 3

    Human.humanCount(); //Output that 3 people have been created
  }
}

At the end

I learned about the scope of variables.

** If you program without being aware of the scope ... ** ・ An error may occurYou can assign a value to a variable in an unintended place (it has been assigned even though you did not intend to assign it)

It can cause problems such as unexpected movements.

I think that the above troubles can be prevented by implementing it considering the range of influence of the scope.

Next time, I'll delve into the string manipulation (in preparation).

Recommended Posts

[Introduction to Java] Variable scope (scope, local variables, instance variables, static variables)
[Introduction to Java] Variables and types (variable declaration, initialization, data type)
Java variable scope (scope)
Java variable scope
[Java] Introduction to Java
[Introduction to Java] Variable declarations and types
Introduction to java
Introduction to java command
Java variable scope (range where variables can be seen)
[Java Silver] What are class variables instance variables and local variables?
Pass a variable to Scope.
[Java] Introduction to lambda expressions
[java] Reasons to use static
How to use Java variables
[Java] Introduction to Stream API
[Introduction to rock-paper-scissors games] Java
[Introduction to Java] About lambda expressions
[Introduction to Java] About Stream API
Introduction to Functional Programming (Java, Javascript)
[Processing × Java] How to use variables
How to write Java variable declaration
Initial introduction to Mac (Java engineer)
Assign evaluation result to Java variable
How to name variables in Java
[Introduction to Rails] form_with (local: true)
[Basic knowledge of Java] Scope of variables
Java local variables are thread safe
Introduction to java for the first time # 2
Introduction to Programming for College Students: Variables
Difference between Ruby instance variable and local variable
Item 57 Minimize the scope of local variables
Introduction to algorithms with java --Search (depth-first search)
[Introduction to Java] How to write a Java program
Item 57: Minimize the scope of local variables
[Java] Differences between instance variables and class variables
Kotlin scope functions to send to Java developers
Output of the book "Introduction to Java"
Introduction to Java Web Apps Performance Troubleshooting
Introduction to algorithms with java --Search (breadth-first search)
static variable
Java static
[Java] Introduction
Instance concept, class type variables, constructors, static members
[Introduction to Java] About type conversion (cast, promotion)
Introduction to algorithms with java --Search (bit full search)
Road to Java Engineer Part1 Introduction & Environment Construction
About var used in Java (Local Variable Type)
[Monthly 2017/04] Introduction to groovy !! ~ Java grammar / specification comparison ~
An introduction to Groovy for tedious Java engineers
[Introduction to Java] Basics of java arithmetic (for beginners)