Java Foundation - Data Types and Variables

Posted by new2code on Tue, 08 Mar 2022 18:13:11 +0100

Catalog

1. Java data types

2. Variables

2.1 Variable concept

2.2 Classification of variables in Java

2.3 Discussion on Value Range of Basic Data Types

2.4 Integer Variables

2.4.1 integer variable

2.4.2 Long Integer Variables

2.4.3 Short Integer Variables

2.4.4 byte type

Notes in 2.4.5 Operations

2.5 Floating Point Variables

2.5.1 Single Precision Floating Point

2.5.2 Double Precision Floating Point

2.6 Character Variables

2.7 Boolean Type

3. Type Conversion

3.1 Automatic Type Conversion

3.2 Mandatory Type Conversion

3.3 Type Upgrade

4. String type

1. Java data types

Java data types can be divided into two basic data types and reference data types, while the basic data types can be divided into four categories and eight types.

Which four or eight?

There are four types: Integer, Float, Character and Boolean

There are eight types: integer, short integer, long integer, single precision floating point, double precision floating point, character, Boolean, byte (not available in c language).

data typeKeywordMemory occupancyPackaging ClassRange
integerint4 bytesInteger-2^31~2^31-1
Short

short

2 bytesShort-2^15~2^15-1
Long Integerlong8 bytesLong

-2^63~2^63-1

floatfloat4 bytesFloatScoped, generally not concerned
Doubledouble8 bytesDoubleScoped, generally not concerned
Byte typebyte1 byteByte-128~127
Characterchar2 bytesCharacter0~65535
BooleanbolleanNo explicit provisionBolleanOnly true and false

There are several types of reference data types:

String, string, class, interface, enumeration, array, etc.

[Note]: (1) For Booleans, the size is generally one bit, but in the implementation of Java virtual machines of the oracle type, the boolean type array in the Java programming language is encoded as a Java virtual machine byte array, where each boolean element is one byte (8 bits) in size. [bollean, there is no specific size in the JVM, but if it is a boolean array, it will be recognized as a byte array by the JVM]

(2) In Java, whether the operating system is 16-bit or 32-bit, the int type takes up 4 bytes, the long type takes up 8 bytes, and the c language is not (in the case of 16-bit, the int type takes up 2 bytes and the 32-bit type takes up 4 bytes), which just reflects the portability of Java.

(3) There is no so-called unsigned or signed in Java.

(4) Integer defaults to int and floating-point defaults to double.

2. Variables

2.1 Variable concept

In a program, in addition to the constant that is always the same, some content may change frequently, such as people's age, height, score, calculation results of mathematical functions, etc. For these frequently changed content, in Java programs, called variables. Data types are used to define different kinds of variables.

2.2 Classification of variables in Java

Variables in Java are: local variables (variables within methods), member variables (defined in classes, access modifier modifiers, about classes and objects)

[Note] Local variables are initialized when used.

2.3 Discussion on Value Range of Basic Data Types

For example, in Java, the int type takes up four bytes (32 bits), the highest of which is the sign bit, and the remaining 31 bits are the numeric digits. Every bit is binary. There are 2^31 digits in the 31-digit value bits, and there are 1 and 0 symbols, so there are 2* (2^31) digits in total.

When the symbol bit 1, because the data is stored as a complement, 10000000 0000... The complement for 0001 (-1) is 1111 1111 1111.... 1111. There are 2^31 numbers from -1 to -2^31;

When the symbol bit is 0, the count starts at 0~2^31, and since there are 2^31 numbers in total, the exact range is 0~2^31-1.

The same is true for other data types.

2.4 Integer Variables

2.4.1 integer variable

//Variables can be initialized when defined
int a=2;
System.out.println(a);
//It can also be redefined before it is assigned a value
int a;
a=2;
System.Out.println(a);
//Compile error if variable is not initialized

// The range that an int variable can represent:
System.out.println(Integer.MIN_VALUE);
System.out.println(Integer.MAX_VALUE);

(1) When setting an initial value for a variable, the value must not exceed the representation range of int (range -2^31~2^31-1), otherwise overflow will occur;

(2) When setting an initial value for a variable, the value must not exceed the representation range of int, otherwise it will cause an overflow;

(3) int is 4 bytes in any system.

2.4.2 Long Integer Variables

int a = 10;
long b = 10; // long Defined long Integer Variable
long c = 10L; // To distinguish between the int and long types, it is generally recommended that you add L or l after the initial value of the long type variable
long d = 10l; // Generally, L is more uppercase because lowercase L is not well distinguished from 1
// The range that a long variable can represent: This data range extends far beyond the range of int. Enough for most engineering scenarios.
System.out.println(Long.MIN_VALUE);
System.out.println(Long.MAX_VALUE);

2.4.3 Short Integer Variables

short a = 10;
System.Out.println(a);
// The range that a short variable can represent:
System.out.println(Short.MIN_VALUE);
System.out.println(Short.MAX_VALUE);

Short integers are generally used less (range is too small, it is easy to exceed the range of values) or int-based.

2.4.4 byte type

byte b = 10;
System.Out.println(b);
// The range that a byte variable can represent:
System.out.println(Byte.MIN_VALUE);
System.out.println(Byte.MAX_VALUE);

Beware of conversion when using byte types.

For example:

byte b1=128;
byte b2=b1;    //Its output will be -128

byte b3=180;    180-127=53    127+1=-128    127+2=-127...127+53=-76
byte b4=b3;    //The output will be -76

Ultimately, the question of range

Notes in 2.4.5 Operations

Four basic operators: (* /%+ -)

For the operation of integer variables, it is important to note that when dividing in Java, the divisor cannot be zero, otherwise compilation will error

public static void main(String[] args){
    int a=5;
    int b=0;
    System.out.println(a/b);//Compilation error
}

Java refers to abnormal behavior of a program when it runs (or compiles) as an exception.

The following code should also note the following

System.out.println(10%3);    //Result 1
System.out.println(10%-3);    //Result 1
System.out.println(-10%3);    //The result is -1
System.out.println(-10%-3);    //The result is -1

2.5 Floating Point Variables

2.5.1 Single Precision Floating Point

//To distinguish between double and float types, you can add f or F after the right value of the float type
float num = 1.0f; // Writing 1.0F is also possible
System.out.println(num);

The float type accounts for four bytes in Java and also complies with the IEEE 754 standard. Because of the small precision range of the data represented, double is generally preferred in engineering applications and float is not recommended. The packaging type of float is Float.

2.5.2 Double Precision Floating Point

In Java, the value of int divided by int is still int (the decimal part is discarded directly). If you want to get 0.5, you need to use the double type.

int a=1,b=2;
System.out.println(a/b);//The result is not 0.5 but 0.

double a = 1.0;
double b = 2.0;
System.out.println(a / b); // Output 0.5

Why is the following output not 1.21?

double num = 1.1;
System.out.println(num * num); 
// results of enforcement
1.2100000000000002

Parse: Floating-point data storage is involved here.

Operations between doubles cannot be performed directly using doubles: computers are binary. Floating-point numbers cannot be represented exactly in binary. Our CPU indicates that floating-point numbers consist of two components: exponential E and tail M. Such a representation generally loses some precision and some floating-point operations also produce some errors.

In most commercial computing, Java is generally used. Math. The BigDecimal class performs exact calculations.
 

[Note]: 1. double accounts for 8 bytes in any system

2. Floating point numbers are stored in memory differently from integers and cannot be calculated in the form of $2^n$

3. The packaging type of double is Double

4. The memory layout of the double type conforms to the IEEE 754 standard (as with C), and attempts to represent possibly infinite decimals with limited memory space are bound to have certain precision errors, so floating-point numbers are approximations, not exact values.

2.6 Character Variables

char c1 = 'A'; // Capital
char c2 = '1'; // Numeric Characters
System.out.println(c1);
System.out.println(c2);
// Note: Characters in java can be stored for reshaping as well as Chinese
char c3 = 'good';
System.out.println(c3);

1. Character types account for 2 bytes in Java, because Java uses Unicode to represent characters (unlike c, which uses Ascii code to represent characters), which gives Java a wider variety of characters

2. Characters in a computer are essentially integers

3. Use single quotation marks + single letters to represent literal values of characters in Java

2.7 Boolean Type

boolean a = true;
System.out.println(a);
b = false;
System.out.println(b);

1. Boolean type has only true and false values.

2. Java boolean types and int s cannot be converted to each other. There is no such usage as 1 for true and 0 for false.

3. The Java Virtual Machine Specification does not specify how many bytes Boolean takes, nor does it specifically handle the byte code instructions for boolean. In Oracle's virtual machine implementation, Boolean takes up one byte (in the case where Boolean arrays are recognized as byte arrays by the JVM, and each Boolean element takes one byte).

boolean value = true;
System.out.println(value + 1);
// The following errors occurred in code compilation
Test.java:4: error: Binary operators '+' Operand type error
System.out.println(value + 1);
^
First type: boolean
 Second type: int
1 Errors

3. Type Conversion

In Java, when data types involved in operations are inconsistent, type conversions occur. There are two main types of type conversion in Java: automatic type conversion (implicit) and forced type conversion (explicit).

Usually, if you assign a variable, you will consider the range of values for both, make a conversion or compile-time error.

float a=1.0f;
double b=2.0;
b=a;    //Can be compiled
a=b;    //Compilation error, assignment of large value range to small, resulting in loss of precision

3.1 Automatic Type Conversion

Automatic type conversion means that the code does not require any processing, and the compiler handles it automatically when the code is compiled. Features: Data range from small to large will automatically occur.

For example:

System.out.println(1024); // Integer defaults to int
System.out.println(3.14); // Floating-point is double by default
int a = 100;
long b = 10L;
b = a; // A and B are integers, a has a small range, B has a large range, when a is assigned to b, the compiler will automatically promote a to long type, and then assign a value
a = b; // Compilation error, long range is larger than int range, data loss, unsafe

3.2 Mandatory Type Conversion

Force type conversion: When operating, the code needs to be formatted and cannot be automatically completed. Features: Data range from large to small.

For example:

int a = 10;
long b = 100L;
b = a; // Int-->long, data range from small to large, implicit conversion
a = (int)b; // Long-->int, data range from large to small, need to be strong, otherwise compilation fails


float f = 3.14F;
double d = 5.12;
d = f; // Float-->double, data range from small to large, implicit conversion
f = (float)d; // Double-->float, data range from large to small, need to be strong, otherwise compilation fails


a = d; // Error, type incompatible
a = (int)d; // int does not have a double representing a large range of data, needs to be strong, all discarded after the decimal point


byte b1 = 100; // 100 defaults to int, does not exceed byte range, implicit conversion
byte b2 = (byte)257; // 257 Default int, beyond byte range, need to show conversion, otherwise error


boolean flag = true;
a = flag; // Compilation failed: incompatible types
flag = a; // Compilation failed: incompatible types

[Note]

1. Assignment between variables of different numeric types, indicating that smaller types can implicitly be converted to larger types

2. If you need to assign a large-range type to a small-range type, you need to force a type conversion, but you may lose precision

3. When assigning a literal value constant, Java automatically checks the number range

4. Mandatory type conversions are not always successful, and irrelevant types cannot be converted to each other

3.3 Type Upgrade

Small data types are promoted to large data types when different types of data are interoperable

For example (1):

1. Between int and long: int will be promoted to long

int a = 10;
long b = 20;
int c = a + b; // Compilation error: a + b== int + long--> long + long assigns to int without losing data
long d = a + b; // Compilation successful: a + b==>int + long--->long + long assign to long

2. Operation of byte and byte

byte a = 10;
byte b = 20;
byte c = a + b;
System.out.println(c);
// Compile Error
Test.java:5: error: Incompatible Types: from int Convert to byte Possible loss
byte c = a + b;

The reason for the error is that the operation of a+b will elevate a and B of byte type to int type and perform the operation again, then a large range of values will be assigned to a small range of values, which will cause compilation errors.

Conclusion:

Both byte and byte are of the same type, but there were compilation errors. The reason is that although both a and b are bytes, calculating a + b will first elevate both a and b to int, and then calculate it. The result is also int, which is assigned to c. This error will occur. Because the CPU of a computer usually reads and writes data from memory in 4 bytes. For hardware convenience, such as byte and short, which are less than 4 bytes, are promoted to int before participating in the calculation.

byte a = 10;
byte b = 20;
byte c = (byte)(a + b);
System.out.println(c);

[Summary of Type Promotion]:

1. For different types of data mixing operations, small ranges will be promoted to large ranges.

2. For short, byte, which is smaller than 4 bytes, is promoted to 4 bytes of int before operation

4. String type

String classes are used in Java to define string types, allowing two or more strings to be stitched together with'+'.

For example:

(1)

public static void main(String[] args) {
String s1 = "hello";
String s2 = " world";
System.out.println(s1);
System.out.println(s2);
System.out.println(s1+s2); // s1+s2 means: splice s1 and S2 together
}
public static void main(String[] args){
    int a=10,b=20;
    System.out.println("a="+a+" "+"b="+b);//The result is a=10 b=20
    System.out.println("a+b="+(a+b));//Note: It cannot be written ("a+b="+a+b), and this will result in a and B being concatenated as strings, not a+b=30 but a+b=1020
}

In some cases, you need to convert between strings and integer numbers:

1. int to String

int num = 10;
// Method 1
String str1 = num + "";
// Method 2
String str2 = String.valueOf(num);

2. String to int

//Method 1
String str = "100";
int num = Integer.parseInt(str);
//Method 2
String str2="200";
int num2=Integer.ValueOf(str2);

There are many more uses for Integer, which are detailed in the following order. *

Topics: Java