Java variable type Java variable type

Code state Lord 2020-11-10 16:22:42
java variable type java variable


Variables provide named storage that the program can manipulate . Java Each variable in has a type , It determines the size and layout of variable memory ; The range of values that can be stored in this memory ; And the set of operations that can be applied to variables .

Variables need to be declared before they can be used , The following is the basic form of a variable declaration -

data type variable [ = value][, variable [ = value] ...] ;
Java

here data type yes Java One of the data types of ,variable Is the name of the variable . To declare multiple variables of the same type , You can use commas to separate lists .

Here are Java Examples of variable declaration and initialization in -

int a, b, c; // Three statements int Type variable :a, b and c
int a = 10, b = 10; // Initialize their values
byte B = 22; // Declare and initialize a byte Variable of type :B
double pi = 3.14159; // Declare and assign a value to double Variable of type :PI
char a = 'a'; // Statement char Type variable a, And the initialization value is :'a'
Java

This chapter will explain Java The various types of variables in a language .Java There are three variables -

  • local variable
  • Instance variables
  • class / Static variables

1. local variable

  • Local variables are usually used in methods , Declare in a constructor or block .
  • Program entry method , Local variables are created when constructors or blocks are used , And once out of the way , Constructor or block , The variable will be destroyed .
  • Access modifiers cannot be used for local variables .
  • Local variables are only used in declared methods , Visible in constructor or block .
  • Local variables implement the stack level internally .
  • Local variables have no default value , So you should declare a local variable after , Assign it an initial value before the first use .

Example

ad locum ,age Is a local variable . This is dogAge() Method , Its scope is limited to this method .

public class Test {
public void dogAge() {
int age = 0;
age = age + 5;
System.out.println("Dog age is : " + age);
}
public static void main(String args[]) {
Test test = new Test();
test.dogAge();
}
}
Java

Execute the example code above , The following results are obtained :

Dog age is : 5
Shell

Example

The following example uses variables age , But don't initialize it , So there are errors when compiling .

public class Test {
public void dogAge() {
int age;
age = age + 5;
System.out.println("Dog age is : " + age);
}
public static void main(String args[]) {
Test test = new Test();
test.dogAge();
}
}
Java

Execute the example code above , The following results are obtained ( error ):

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

2. Instance variables

  • Instance variables are declared in the class , But in the way , Outside the constructor or block .
  • When allocating space for objects in the heap , A slot will be created for each instance variable value .
  • Use keywords new Instance variables are created when an object is created , And destroy instance variables when destroying objects .
  • Instance variables consist of multiple methods , The value of a constructor or block reference , Or the basic part of the object state that exists throughout the class .
  • Instance variables can be declared at the class level before or after use .
  • You can give instance variables access modifiers .
  • Instance variables for all methods in a class , Constructors and blocks are visible . Usually , It is recommended to make these variables private ( The level of access ). however , You can use access modifiers to provide visibility to subclasses of these variables .
  • Instance variables have default values . For numbers , The default value is 0, For Boolean , It's for false, For object references , It's for null. You can specify values during declaration or in constructors .
  • You can directly access instance variables by calling the variable name in the class . however , In a static method ( When instance variables are accessible ), They should be called with fully qualified names , Such as :ObjectReference.VariableName.

Sample code

import java.io.*;
public class Employee {
// This instance variable is visible to subclasses .
public String name;
// salary The variables are only in Employee Class .
private double salary;
// name The variable is specified in the constructor .
public Employee (String empName) {
name = empName;
}
// by salary Variable assignment
public void setSalary(double empSal) {
salary = empSal;
}
// This method prints employee details .
public void printEmp() {
System.out.println("name : " + name );
System.out.println("salary :" + salary);
}
public static void main(String args[]) {
Employee empOne = new Employee("Maxsu");
empOne.setSalary(15999);
empOne.printEmp();
}
}
Java

Execute the example code above , The following results are obtained :

name : Maxsu
salary :15999.0
Shell

3. class / Static variables

  • Class variables ( Also known as static variables ) Use... In classes static Keyword declaration , But in the way , Outside the constructor or block .
  • Each class has only one copy of each class variable , No matter how many objects are created from it .
  • In addition to being declared constant , Static variables are rarely used . Constants are declared as public/private,final and static The variable of . The initial value of a constant cannot be changed .
  • Static variables are stored in static memory . Except as stated final outside , Static variables are rarely used , And use it as a public or private constant .
  • Static variables are created when the program starts , Static variables are destroyed when the program stops .
  • Visibility is similar to instance variables . however , Most static variables are public , Because they have to be available to that kind of user .
  • The default value is the same as the instance variable . For numbers , The default value is 0; For Boolean types , The default value is false; For object references , The default value is null. You can specify values during declaration or in constructors . Besides , Values can be assigned in special static initialization blocks .
  • You can do this by using the class name ClassName.VariableName Call to access static variables .
  • Declare the class variable as public static final when , Variable name ( Constant ) It's all in capitals . If the static variable is not public and final, The naming syntax is the same as the naming rules for instance and local variables .

Example

import java.io.*;
public class Employee {
// salary A variable is a private static variable
private static double salary;
// DEPARTMENT Is a constant
public static final String DEPARTMENT = " R & D department ";
public static void main(String args[]) {
salary = 19999;
System.out.println(DEPARTMENT + " Average salary :" + salary);
}
}
Java

Execute the example code above , The following results are obtained -

 Average salary of R & D department :19999
Shell

notes - If you access a variable from an external class , It should be regarded as :Employee.DEPARTMENT.



complete Java primary , Advanced corresponding learning routes and materials ! Focus on java Development . Share java Basics 、 Knowledge of principle 、JavaWeb actual combat 、spring Family bucket 、 Design patterns 、 Distributed and interview materials 、 Open source project , Help developers grow !


Welcome to WeChat official account. : Code state Lord

版权声明
本文为[Code state Lord]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云