search
HomeJavajavaTutorialJAVA Getting Started Tutorial | Chapter 3 Variable Types

We can know from the previous article that data types in java are divided into basic data types and reference data types .

#The object-oriented principle of Java is: data and operations on data must be bound together. This is a class, that is, a reference data type. Therefore, a class is also a type. Java does not need to set basic types. It only sets basic types to improve operating efficiency. The main difference between basic types and reference types is:

  1. The variable name of the basic type is the variable itself.

  2. #The name of a reference type variable is the storage location of complex data.

We know that there are three major categories of variable types supported by the Java language:

  • Local variables

  • Member variables

  • Class variables (Static variable)

This chapter actually starts from the scope and explains the scope of the variable type. Why is it called a scope? Let’s first look at the code and concepts below.


Java local variables

  • Local variables are declared in methods, constructors, or statement blocks;

  • Local variables are created when methods, constructors, or statement blocks are executed, and when their execution is completed After that, the variable will be destroyed;

  • Access modifiers cannot be used for local variables;

  • Local variables are only declared in the method, Visible in the constructor or statement block;

  • Local variables are allocated on the stack.

  • Local variables have no default value, so after a local variable is declared, it must be initialized before it can be used.

Example 1

In the following example age is a local variable. It is defined in the pupAge() method, and its scope is limited to this method.

package com.dujinyang.immqy;
 
public class Test{ 
   public void getAge(){
      int age=1;
      age = age + 9;
      System.out.println("--小狗的年龄 : " + age);
   }
   
   public static void main(String args[]){
      Test test = new Test();
      test.getAge();
   }
}

The above example compilation and running results are as follows:

--小狗的年龄是:10

Instance 2

In the following example, the age variable is not initialized, so an error will occur during compilation:

package com.dujinyang.immqy;
 
public class Test{ 
   public void getAge(){
      int age;
      age = age + 9;
      System.out.println("--小狗的年龄 : " + age);
   }
   
   public static void main(String args[]){
      Test test = new Test();
      test.getAge();
   }
}

The compiler will report an error directly:

Test.java:4:variable number might not have been initialized
age = age + 9;
         ^1 error

实例变量

  • 实例变量声明在一个类中,但在方法、构造方法和语句块之外;

  • 当一个对象被实例化之后,每个实例变量的值就跟着确定;

  • 实例变量在对象创建的时候创建,在对象被销毁的时候销毁;

  • 实例变量的值应该至少被一个方法、构造方法或者语句块引用,使得外部能够通过这些方式获取实例变量信息;

  • 实例变量可以声明在使用前或者使用后;

  • 访问修饰符可以修饰实例变量;

  • 实例变量对于类中的方法、构造方法或者语句块是可见的。一般情况下应该把实例变量设为私有。通过使用访问修饰符可以使实例变量对子类可见;

  • 实例变量具有默认值。数值型变量的默认值是0,布尔型变量的默认值是false,引用类型变量的默认值是null。变量的值可以在声明时指定,也可以在构造方法中指定;

  • 实例变量可以直接通过变量名访问。但在静态方法以及其他类中,就应该使用完全限定名:ObejectReference.VariableName。

实例

import java.io.*;
public class Employee{
   // 这个实例变量对子类可见
   public String name;
   // 私有变量,仅在该类可见
   private double salary;
   //在构造器中对name赋值
   public Employee (String empName){
      name = empName;
   }
   //设定salary的值
   public void setSalary(double empSal){
      salary = empSal;
   }  
   // 打印信息
   public void printEmp(){
      System.out.println("名字 : " + name );
      System.out.println("薪水 : " + salary);
   }
 
   public static void main(String args[]){
      Employee empOne = new Employee("KARL-dujinyang");
      empOne.setSalary(1000);
      empOne.printEmp();
   }
}

以上实例编译运行结果如下:

$ javac Employee.java 
$ java Employee名字 : KARL-dujinyang薪水 : 1000.0

类变量(静态变量)

  • 类变量也称为静态变量,在类中以static关键字声明,但必须在方法构造方法和语句块之外。

  • 无论一个类创建了多少个对象,类只拥有类变量的一份拷贝。

  • 静态变量除了被声明为常量外很少使用。常量是指声明为public/private,final和static类型的变量。常量初始化后不可改变。

  • 静态变量储存在静态存储区。经常被声明为常量,很少单独使用static声明变量。

  • 静态变量在程序开始时创建,在程序结束时销毁。

  • 与实例变量具有相似的可见性。但为了对类的使用者可见,大多数静态变量声明为public类型。

  • 默认值和实例变量相似。数值型变量默认值是0,布尔型默认值是false,引用类型默认值是null。变量的值可以在声明的时候指定,也可以在构造方法中指定。此外,静态变量还可以在静态语句块中初始化。

  • 静态变量可以通过:ClassName.VariableName的方式访问。

  • 类变量被声明为public static final类型时,类变量名称一般建议使用大写字母。如果静态变量不是public和final类型,其命名方式与实例变量以及局部变量的命名方式一致。

实例

import java.io.*;
 
public class Employee {
    //salary是静态的私有变量
    private static double salary;
    // DEPARTMENT是一个常量
    public static final String DEPARTMENT = "深圳的";
    public static void main(String args[]){
    salary = 1000;
        System.out.println(DEPARTMENT+"平均工资:"+salary);
    }
}

以上实例编译运行结果如下:

深圳的平均工资:1000.0

注意:如果其他类想要访问该变量,可以这样访问:Employee.DEPARTMENT。因为它是静态的,static的关键字。

In this chapter we learned about Java variable types. In the next chapter we will introduce the use of Java modifiers.

The above is the content of JAVA Getting Started Tutorial | Chapter 3 Variable Types. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software