[Basic knowledge of Java] Scope of variables

Introduction

This article is --Start learning Java ――I want to review the basics

For those who say.

About scope

Scope refers to the range that variables can handle. " This variable can be used from here to here, but this variable cannot be used from here to here. " It is like this.

After declaring a variable, the space between {} is the range in which the variable can be used.

If you are not aware of this scope, a compile error will occur, so I will explain the scope with the variables explained below.

Local variables

The variables from {to} are called blocks, and the variables that can be handled in the blocks are called local variables. It can be referenced after the declared position.

public class local {
  public static void main(String args[]){
    int a = 0;

    if(true){
      int b = 0;
    }
    a = 1;//a is main{}Can be referenced between
    b = 1;//Compile error because b is outside the if
  }
   a = 2;//Compile error because it is outside main

   public static void sub(){
     a = 3;//Compile error because it is a method outside main
   }
}

If you have local variables, you might think that there are global variables, There is no such thing as a global variable in Java (* In Java, global variables are not used in principle).

Instance variables

An instance is created in the memory area each time it is new. It can be accessed by ** object.instance variable name **.

food.java


class Food{
  String menu;//Instance variables
  int price;//Instance variables

  public void Info(){
    System.out.println("This is"+ menu + "is");
    System.out.println("The price is"+ price + "It's a yen");
  }

  public void say(){
    System.out.println("Freshly fried"+ menu + "Is the best");
  }
}

Main.java


public class Main {
  public static void main(String args[]){
    Food potato = new Food();//A new address is secured in memory(Instantiation of Food class)

    potato.menu = "Potato";//potato(object).menu(Instance variables)To"Potato"Substitute
    potato.price = 270;//potato(object).price(Instance variables)To"270"Substitute

    System.out.println(potato.menu);//Potato

    potato.Info();
    //This is potato
    //The price is 270 yen

    potato.say();//Freshly fried potatoes are the best

    Food nugget = new Food();//A new address is secured in memory

    nugget.menu = "nugget";//nugget(object).menu(Instance variables)To"nugget"Substitute
    nugget.price = 580;//nugget(object).price(Instance variables)To"580"Substitute

    System.out.println(nugget.menu);//nugget

    nugget.Info();
    //This is a nugget
    //The price is 580 yen

  }

}

Then, here is an example that causes a compile error next

food.java


  public static void say(){
    System.out.println("Freshly fried"+ menu + "Is the best");
  }

If you change the say method of food.java to a static method, Cannot make a static reference to the non-static field menu I get angry with the feeling

Main.java


 potato.say();

This part is also

The static method say() from the type Food should be accessed in a static way I get angry with a feeling.

I will explain later, If you want to make it a static method, you have to define it with a static variable.

About this

You can use the keyword this when referring to your own instance. You can access it with ** this.variable name **. This. Can be omitted.

It is often used to identify the target when the variable defined in the field of the class and the name of the local variable are the same. Local variables take precedence over class variables.

Please take a look at this example.

public class Soccer {

  //Instance variables
  String player = "Messi";

  public static void main(String[] args){

    //Local variables
    String player = "Iniesta";

    System.out.println(player + "is");// イニエスタis
  }
}

As mentioned earlier, local variables have taken precedence. When accessing the player of the class variable, you can specify it by giving it as this.variable name.

Bad example using this: Soccer.java


public class Soccer {

  //Instance variables
  String player = "Messi";

  public static void main(String[] args){

    //Local variables
    String player = "Iniesta";

    System.out.println("Local variables" + player + "is");// Local variablesイニエスタis
    System.out.println("Instance variables" + this.player + "is");// Cannot use this in a static context
  }
}

As you can see in the bad example, you can't just write this as it is.

Correct example: Soccer.java


class Soccer {
  String player = "Messi";

  public void say(String player) {//Make it distinguishable by argument
      System.out.println("Local variables" + player + "is");// Local variablesイニエスタis
      System.out.println("Instance variables" + this.player + "is");// クラス変数メッシis
  }
}

Correct example: Print.java


public class Print {
  public static void main(String[] args) {
      String player = "Iniesta";
      Soccer sc = new Soccer();
      sc.say(player);
  }
}

static variable (class variable)

The static modifier is defined in the class area. You can access it with ** class name.static variable name **. Static variables do not have a value for each object.

Let's look at an example.

Meiji.java


public class Meiji {
  public static String snack;//Static variable

  public void saySnack(){
    System.out.println(snack);
  }
}

Meiji2.java


public class Meiji2 {
  public static void main(String[] args){
    Meiji.snack = "Mountain of mushrooms";//to snack"Mountain of mushrooms"Is stored
    Meiji say1 = new Meiji();//Instantiation of Meiji class
    say1.saySnack();//Mountain of mushrooms
    Meiji say2 = new Meiji();
    say2.saySnack();//Mountain of mushrooms

    Meiji.snack = "Takenoko no Sato";//to snack"Takenoko no Sato"Is stored
    say1.saySnack();//Takenoko no Sato
    say2.saySnack();//Takenoko no Sato
  }
}

As you can see, there is no value for each object, say1 and say2 refer to the same value in memory.

The usage of static variables is I'm still studying, but you can use it to count how many instances you have created from your class. I rewrote Meiji.java and Meiji2.java a little earlier.

Meiji.java


public class Meiji {
  public String snack;//Instance variables
  public static int count = 0;//Initialize static variables

  public void saySnack(){
    System.out.println(snack);
    Meiji.count++;//name of the class.count(static variable)Specify with and increase by 1
  }

  public static void snackCnt(){ //static method (class method)
    System.out.println(Meiji.count);
  }
}

Meiji2.java


public class Meiji2 {
  public static void main(String[] args){
    Meiji.snackCnt();// 0

    Meiji kinoko = new Meiji();//Instantiation of Meiji class
    kinoko.snack = "Mountain of mushrooms";//kinoko(object).snack(Instance variables)To"Mountain of mushrooms"Substitute
    kinoko.saySnack();//Mountain of mushrooms

    Meiji.snackCnt();// 1

    Meiji takenoko = new Meiji();
    takenoko.snack = "Takenoko no Sato";
    takenoko.saySnack();//Takenoko no Sato

    Meiji.snackCnt();// 2

  }
}

Since it is counting up in the saySnack method, You can see that the number increases each time the method is called.

Finally

This time we learned about variables and scopes. Then, the features of the following variables are described. --Local variables --Instance variables --Static variable (class variable)

I think there are still some ways to use this, I will omit it here.

Thank you ☕️

Recommended Posts

[Basic knowledge of Java] Scope of variables
Java basic knowledge 1
Basic knowledge of Java development Note writing
[Basic knowledge of Java] About type conversion
java basic knowledge memo
[Ruby] Basic knowledge of class instance variables, etc.
Basic knowledge of SQL statements
Basic knowledge of Ruby on Rails
Basic knowledge
Basic usage of java Optional Part 1
Basic processing flow of java Stream
Basic structure of Java source code
Item 57 Minimize the scope of local variables
Item 57: Minimize the scope of local variables
Java basic learning content 1 (literals, variables, constants)
[Java] output, variables
Java knowledge summary
Java basic grammar
Java basic grammar
Java variable scope (scope)
[WIP] Java variables
[Java] Basic structure
[Java] [Basic] Glossary
Variables / scope (ruby)
Java basic grammar
Java basic grammar
Java session scope
[Java] Overview of Java
Java exercises [Basic]
Way of thinking when studying basic program knowledge
Summary of basic knowledge of Rails acquired by progate
[Java] Personal summary of classes and methods (basic)
Java and Swift comparison (1) Source control / Scope / Variables
Java review ③ (Basic usage of arrays / reference type)
Java engineers now compare to learn the basic grammar of Ruby Part 1 (Basic, Variables)
[For beginners] Introduction to Java Basic knowledge of Java language ③ Array, selection structure, iteration structure
[Java] Basic summary of Java not covered by Progate ~ Part 1 ~
Expired collection of java
Predicted Features of Java
[Java] Significance of serialVersionUID
NIO.2 review of java
Review of java Shilber
[Beginner] Create a competitive game with basic Java knowledge
[Java] Data type ①-Basic type
java --Unification of comments
Java basic date manipulation
Java review ① (development steps, basic grammar, variables, data types)
Summary of knowledge required to pass Java SE8 Silver
Java basic naming conventions
History of Java annotation
java (merits of polymorphism)
Features of Static variables
Java learning memo (basic)
Java variable scope (range where variables can be seen)
[Introduction to Java] Variable scope (scope, local variables, instance variables, static variables)
NIO review of java
[Java] Variables and types
[Java] Basic method notes
[Java] Three features of Java
Summary of Java support 2018
Java basic data types