In the Java language, all variables must be declared before they are used. The basic format for declaring variables is as follows:
Type identifier [= value][, identifier [= value] ...];
Format Description: Type is a Java data type. Identifier is the variable name. You can declare multiple variables of the same type by separating them with commas.
The following is a list of the declaration instances for some variables. Note that some of the initialization procedures are included.
int A, b, C; Declares three integers of type int: A, B, c
int d = 3, E = 4, f = 5; Declares three integers and assigns an initial value
byte z = 22; Declaring and Initializing Z
String s = "Runoob"; Declaring and initializing the string s
Double pi = 3.14159; A double-precision floating-point variable pi is declared
char x = ' x '; The value of the declared variable x is the character ' X '.
The types of variables supported by the Java language are:
Local variables
Member variables
class variables
Java Local Variables
A local variable is declared in a method, a construction method, or a block of statements;
Local variables are created when methods, construction methods, or block of statements are executed, and when they are executed, the variables are destroyed;
Access modifiers cannot be used for local variables;
A local variable is only visible in the method, construction method, or block of statements that declares it;
Local variables are allocated on the stack.
The local variable has no default value, so the local variable is declared and must be initialized before it can be used.
Instance variable
Instance variables are declared in a class, but outside of methods, construction methods, and statement blocks;
When an object is instantiated, the value of each instance variable is then determined;
Instance variables are created when the object is created and destroyed when the object is destroyed;
The value of the instance variable should be referenced by at least one method, construct method, or statement block, so that the external can obtain instance variable information through these methods;
Instance variables can be declared before use or after use;
An access modifier can modify an instance variable;
Instance variables are visible to methods, construction methods, or block statements in a class. In general, you should set the instance variable to private. By using the access modifier, the instance variable is visible to the child class;
The instance variable has a default value. The default value for a numeric variable is 0, the default value for a Boolean variable is false, and the default value for the reference type variable is null. The value of a variable can be specified at the time of declaration, or it can be specified in a constructor method;
Instance variables can be accessed directly from the variable name. However, in static methods and other classes, you should use the fully qualified name: Obejectreference.variablename.
Instance:
Import java.io.*;
public class employee{
This instance variable is visible to the child class
public String name;
Private variable, only visible in this class
private double salary;
Assigning a value to name in the constructor
Public Employee (String empname) {
name = EmpName;
}
Set the value of the salary
public void Setsalary (double empsal) {
salary = Empsal;
}
Printing information
public void Printemp () {
System.out.println ("Name:" + name);
System.out.println ("Salary:" + salary);
}
public static void Main (String args[]) {
Employee Empone = new Employee ("Runoob");
Empone.setsalary (1000);
Empone.printemp ();
}
}
class variables (static variables)
Class variables, also known as static variables, are declared in the class with the static keyword, but must be outside the method construction method and statement block.
No matter how many objects a class creates, the class has only one copy of the class variable.
Static variables are seldom used except when declared as constants. Constants are variables declared as public/private,final and static types. Constants cannot be changed after initialization.
Static variables are stored in a static storage area. are often declared as constants, and static declaration variables are seldom used alone.
Static variables are created at the beginning of the program and are destroyed at the end of the program.
has similar visibility to instance variables. However, in order to be visible to the consumer of a class, most static variables are declared as public types.
The default value is similar to the instance variable. The default value for numeric variables is 0, the Boolean default is False, and the reference type default value is null. The value of a variable can be specified at the time of declaration, or it can be specified in a constructor method. In addition, static variables can be initialized in static statement blocks.
Static variables can be accessed by: Classname.variablename.
Class variable names are generally recommended to use uppercase when the class variable is declared as public static final type. If the static variable is not public and final, it is named in the same way as the instance variable and the local variable.
Instance:
Import java.io.*;
public class Employee {
Salary is a static private variable
private static double salary;
Department is a constant
public static final String DEPARTMENT = "Developer";
public static void Main (String args[]) {
Salary = 10000;
System.out.println (department+ "average salary:" +salary);
}
}
Java four class eight data types
Basic data type:
First Class: Logical Type Boolean
Type II: Text Char
Type III: Integer (Byte, short, int, long)
Char type accounted for 2 bytes
Short from 32768 to 32767
int from-2147483648 to 2147483647 total 10-bit
Long from 9223372036854775808 to 9223372036854775807 total 19 bits
Class Fourth: Floating-point type (float, double)
In mathematics, 0 to 1 have countless floating-point numbers, and the computer is discrete, so when there are errors, the computer with precision (after a few decimal points to indicate the correct), compared with floating-point a==0.1 is not appropriate, should be a-0.1==0; If a is 0.1, even if there is an error a-0.1== 0 because both a and 0.1 are represented as a computer binary with errors
Reference data type:
- In Java, a variable of a reference type is very similar to a C + + pointer. A reference type points to an object, and a variable that points to an object is a reference variable. These variables are specified at the time of declaration as a specific type, such as employee, Pubby, and so on. Once a variable is declared, the type cannot be changed.
- objects, arrays are reference data types.
- The default value for all reference types is null.
- A reference variable can be used to refer to any type that is compatible with it.
- Example: Site site = new site ("Runoob").
Strong, soft, weak, and virtual references to objects
In previous versions of JDK 1.2, if an object was not referenced by any variable, the program could no longer use the object. That is, only the object is in the accessible (reachable) state before the program can use it. Starting with JDK version 1.2, the reference to the object is divided into 4 levels, giving the program more flexibility in controlling the object's life cycle. These 4 levels are high to low in order: Strong references, soft references, weak references, and virtual references.
⑴ Strong references (strongreference)
Strong references are the most commonly used references. If an object has a strong reference, the garbage collector will never recycle it.When there is not enough memory space,Java virtual machines would rather throw outofmemoryerrorErrors, causes the program to terminate abnormally, and does not rely on the arbitrary collection of strongly referenced objects to resolve out-of-memory issues. PS: Strong references are actually the meaning of our usual a = new A ().
⑵ Soft Reference (SoftReference)
If an object has only soft references, enough memory space is available, the garbage collector does not recycle it, and if the memory space is insufficient, the memory of those objects is reclaimed. The object can be used by the program as long as it is not reclaimed by the garbage collector. Soft references can be used to implement memory-sensitive caches (see below for an example).
A soft reference can be used in conjunction with a reference queue (Referencequeue), and if the object referenced by the soft reference is reclaimed by the garbage collector, the Java Virtual machine will add the soft reference to the reference queue associated with it.
⑶ Weak references (weakreference)
The difference between a weak reference and a soft reference is that an object with only a weak reference has a shorter life cycle. As the garbage collector thread scans the area of memory it governs, once an object with only a weak reference is found, its memory is reclaimed, regardless of whether the current memory space is sufficient or not. However, because the garbage collector is a low-priority thread, it is not necessarily quick to discover objects that have only weak references.
A weak reference can be used in conjunction with a reference queue (Referencequeue), and if the object referenced by the weak reference is garbage collected, the Java virtual machine adds the weak reference to the reference queue associated with it.
⑷ Virtual Reference (phantomreference)
"Virtual Reference", as the name implies, is a dummy, unlike several other references, a virtual reference does not determine the object's life cycle. If an object holds only virtual references, it can be reclaimed by the garbage collector at any time, just as there are no references.
virtual references are primarily used to track activities that objects are reclaimed by the garbage collector. One difference between a virtual reference and a soft reference and a weak reference is that the virtual reference must be used in conjunction with the reference queue (Referencequeue). When the garbage collector prepares to reclaim an object, if it finds that it has a virtual reference, it will add the virtual reference to the reference queue associated with it before reclaiming the object's memory.
Referencequeue queue = new referencequeue ();
Phantomreferencepr=NewPhantomreference (Object,Queue);
The program can see if the referenced object is going to be garbage collected by judging whether the reference queue has been added to the virtual reference. If the program discovers that a virtual reference has been added to the reference queue, it can take the necessary action before the memory of the referenced object is reclaimed.
Building a cache of sensitive data using soft references
1 Why you need to use soft references
First, we look at an example of an employee information query system. We will use an employee information query system implemented in the Java language to query employee profile information stored in a disk file or database. As a user, we may have to go back and look at employee profile information that was viewed a few minutes or even seconds ago (again, we often use the back button when we browse the Web page). At this point we usually have two ways of implementing the program: one is to keep the employee information viewed in the past in memory, the life cycle of each Java object that stores the employee profile information throughout the application, and the other is when the user starts to view the profile information of the other employee, Ends a reference to the Java object that stores the currently viewed employee profile information, allowing the garbage collection thread to reclaim the memory space it occupies, and reconstruct the employee's information when the user needs to browse the employee's profile information again. Obviously, the first implementation will result in a lot of memory waste, and the second implementation is flawed even if the garbage collection thread has not been garbage collected, the object containing the employee profile information is still intact in memory, and the application is rebuilding an object. We know that access to disk files, access to network resources, query databases and other operations are important factors affecting the performance of application execution, if you can regain those who have not yet been recycled Java object references, will reduce unnecessary access, greatly improve the speed of the program.
2 If you use a soft reference
The SoftReference feature is that an instance of it holds a soft reference to a Java object, and the existence of the soft reference does not prevent the garbage collection thread from reclaiming the Java object. That is, once SoftReference has saved a soft reference to a Java object, the Get () method provided by the SoftReference class returns a strong reference to the Java object before the garbage thread recycles the Java object. Also, once a garbage thread reclaims the Java object, the Get () method returns NULL.
look at the following code:
MyObject aRef = new
MyObject ();
softreference Span style= "COLOR: #0000c0" >asoftref= new SoftReference (aref);
At this point, for this MyObject object, there are two reference paths, one is a soft reference from the SoftReference object, and one is a strong reference from the variable areference, so this MyObject object is a strong object.
Then we can end the areference strong reference to this MyObject instance:
ARef = null;
Since then, the MyObject object has become a soft and accessible object. If the garbage collection thread is in memory garbage collection, it does not always retain the object because it has a softreference reference to the object. The Java Virtual machine's garbage collection thread treats soft-and object-and other generic Java objects differently: The cleanup of soft and object is determined by the garbage collection thread according to its memory requirements based on its particular algorithm. That is, the garbage collection thread reclaims the soft objects before the virtual machine throws OutOfMemoryError, and the virtual machine takes priority to reclaim the soft objects that are unused for long periods of time, and the "new" soft-anti-objects that have just been built or used are retained by the VM as much as possible. Before we recycle these objects, we can pass:
myobject anotherref= (MyObject) asoftref . get (); The
re-obtains a strong reference to the instance. After the collection, the call to get () method can only get null.
3 Use Referencequeue to clear the SoftReference
Referencequeue queue = new
Referencequeue ();
SoftReference
Ref=New
SoftReference (amyobject, queue);
Then when the SoftReference soft-referenced amyohject is reclaimed by the garbage collector, ref's strongly referenced SoftReference object is included in the Referencequeue. That is, the object saved in Referencequeue is the reference object, and it is the reference object that has lost the object it is soft referenced. Also from the name of Referencequeue, it is a queue, when we call its poll () method, if this queue is not empty queue, then will return the queue in front of the reference object.
At any time, we can call Referencequeue's poll () method to check if there are non-strong objects that it cares about being recycled. If the queue is empty, a null is returned, otherwise the method returns a reference object in front of the queue. Using this method, we can check which softreference the soft reference object has been recycled. So we can get rid of the SoftReference objects that have lost the soft reference object. The usual ways are:
SoftReference ref = null;
while (ref = (employeeref) q. Poll ()) = null) {
Clear ref
}
02-java variables and basic data types (1)