Basic data types and variables of java series

Posted by Daisy Cutter on Wed, 09 Mar 2022 16:55:59 +0100

Tip: after the article is written, the directory can be generated automatically. Please refer to the help document on the right for how to generate it

Basic data types and variables of java series

preface

In ancient times, great events must be established not only by extraordinary talents, but also by perseverance!

1. Literal constant

A constant is a constant quantity that is fixed during the running of a program

Classification of character constants:

1. String constant: that is, the content enclosed by "", such as "abced", "1234".

2. Shaping constant: that is, the integer directly written in the program (without decimal point).

3. Floating point constant: that is, the decimal number written directly in the program. Such as 3.14, 0.21.

4. Character constant: that is, only one character is placed in the content enclosed by 'A', such as' I '.

5. Boolean constant: there are only two kinds: true and false.

6. Null constant: null.

String, integer, floating point, character and Boolean are all called data types in Java.

Code example

public class test{
    public static void main(String[] args){
         System.Out.println("hello world!");
         System.Out.println(100);
         System.Out.println(3.14);
         System.Out.println('A');
         System.Out.println(true);
         System.Out.println(false);
    }
}

2. Data type of Java

In java, data types are divided into four categories and eight types:

Four types: integer, floating point, character and Boolean.

Eight:

Resolve doubts:

Why are negative numbers one more than positive numbers

This is specified. Take int type as an example:

If you simply calculate the binary of 0, the first bit represents the sign bit, then there are two expressions:

00000000000000000000000000000000

10000000000000000000000000000000

So computer scientists stipulate:

The binary of 0 is 000000000000000000000000000000000

-The binary of 32768 is 1000000000000000000000

The same is true for other data types.

be careful:

  • Whether in 16 bit system or 32-bit system, int occupies 4 bytes and long occupies 8 bytes. (java Security)

  • Both integer and floating point types are signed

  • Integer defaults to int, and floating point defaults to double

    The following code explains the details:

    public class test{
        public static void main(String[] args){
             float = 3.14;
            //No problem, but 3.14 is a double type
            //Therefore, the value of float type should be added with an f
            float = 3.14f;
        }
    }
    

Basic knowledge review:

What are bytes:

  • Bytes are the basic unit of space in a computer

  • Computers use binary representation of data We consider eight bits as one byte

  • Our usual computer is 8GB memory, which means 8G bytes

  • Where 1KB = 1024 Byte, 1MB = 1024 KB, 1GB = 1024 MB

3.java variables

3.1 what are the variables:

In a java program, there must be not only constants, but also quantities that can be changed. For these frequently changed contents, in a java program, they are called variables. Data types are used to define different kinds of variables.

Define the syntax format of the variable:

Data type variable name = initial value;

Code example:

public class test{
    public static void main(String[] args){
int a = 10; 
double d = 3.14;
char c = 'A';
boolean b = true;
System.Out.println(a);
System.Out.println(d);
System.Out.println(c);
System.Out.println(b);
a = 100;//The value of variable a can be modified, but it should be within the value range of int type
// Note: multiple variables of the same type can be defined in one line
int a1 = 10, a2 = 20, a3 = 30;
System.Out.println(a1);
System.Out.println(a2);
System.Out.println(a3);
    }
}

a key:

Compared with c language, java language has very high security, so every variable can not be used directly without giving initial value like c language
for example

public class test{
    public static void main(String[] args){
        int a;
        System.Out.println(a);
        //Will fail to compile.
    }
}

So assign a value to the variable before use:

public class test{
    public static void main(String[] args){
        int a;
        a = 100;
        System.Out.println(a);
    }
}

Therefore, we should form a good code habit. When defining variables, if we don't want to give them a value, we can assign it to 0 first.

3.2 variable knowledge points of shaping class

int type:

  • int is 4 bytes in any system.
  • If there is no suitable initial value, it can be set to 0.
  • When setting the initial value of the variable, the value cannot exceed the representation range of int, otherwise overflow will be caused.
  • The variable must be given an initial value before use, otherwise the compilation will report an error.
  • The wrapper type of int is Integer

long type

  • Add L or l after the initial value of long integer variable. It is recommended to add L (because l will be confused with 1)

  • Long integers occupy 8 bytes in any system

  • The representation range of long integer is: − 2 31 -2^{31} −231 ~ 2 31 − 1 2^{31}-1 231−1

  • The packing type of long is long

    public class test{
        public static void main(String[] avgs){
            long b = 314254L;
            //Add L  
        }
    }
    

short type

  • short takes up 2 bytes in any system
  1. The expression range of short is: - 32768 ~ 32767
  2. When using, be careful not to exceed the scope (generally used less)
  3. The packaging type of short is short

byte type

  • Byte takes up one byte in any system
  1. The range of byte s is: - 128 ~ 127
  2. The packing type of bytes is Byte

Floating point type variable

Double type (double precision floating point)

reflection:

public class test{
    public static void main(String[] avgs){
           int a = 1;		
           int b = 2;
           System.out.println(a / b);   
          // Output 0.5?
          
    }
}

In Java, the value of int divided by int is still int (the decimal part will be discarded directly).

You can output 0.5 Code:

public class test1{
    public static void main(String[] avgs){
           double a = 1;
           double b = 2;
           System.out.println(a / b);   
        
    }
}
public class test2{
    public static void main(String[] avgs){
           int a = 1;
           int b = 2;
           System.out.println(a*1.0 / b*1.0);   
          // Promote int type to double type
    }
}

Think: will the following code output 1.21

public class test3{
    public static void main(String[] avgs){
        double num = 1.1;
        System.out.println(num * num);
    }
}

No, the result should be: 1.210000000000000 2

Because the computer can't calculate the exact value when calculating the floating-point number, there is an error.

Knowledge points:

  • double occupies 8 bytes in any system
  • Floating point numbers and integers are stored in different ways in memory and cannot be used simply 2 n 2^n 2n
  • The packing type of double is double
  • The memory layout of double type complies with IEEE 754 standard (the same as C language). If you try to use limited memory space to represent potentially infinite decimal points, there will be a certain precision error. Therefore, floating-point numbers are approximate values, not exact values.

float type (single precision floating point)

public class test{
    public static void main(String[] avgs){
        float a = 3.14F;
         System.out.println(a);
    }
}

Knowledge points:

  • float type occupies four bytes in Java and also complies with IEEE 754 standard
  • Due to the small range of data accuracy, double is preferred when floating-point numbers are used in engineering, and float is not recommended
  • The packing type of float is float.

3.4 knowledge points of character variables

public class test{
    public static void main(String[] avgs){
        char c1 = 'A';    // capital
        char c2 = '1';    // Numeric character
        System.out.println(c1);
        System.out.println(c2);
        // Note: characters in java can be used to store shaping
        char c3 = 'Handsome';
        System.out.println(c3);
    }
}

Knowledge points:

  • Java uses the form of single quotation mark + single letter to represent the literal value of a character

  • A character in a computer is essentially an integer ASCII is used to represent characters in C language, while Unicode is used to represent characters in Java Therefore, a character takes up two bytes and represents more types of characters, including Chinese.

3.5 knowledge points of Boolean variables

public class test{
    public static void main(String[] avgs){
        boolean b = true;
        System.out.println(b);
        b = false;
        System.out.println(b);
    }
}

Knowledge points

  • There are only two values for boolean variables, true for true and false for false

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

  • In the Java virtual machine specification, there is no explicit provision on how many bytes boolean occupies, and there is no bytecode instruction specially used to process boolean. In the virtual machine implementation of Oracle company, boolean occupies one byte.

    Explanation of professional documents:

    public class test{
        public static void main(String[] avgs){
            boolean value = true;
            System.out.println(value + 1);
    // The following errors occur during code compilation
    //Test.java:4: error: the operand type of binary operator '+' is wrong
    //This is because the boolean type has no specified size, and the addition and subtraction cannot determine how many bytes to skip.
        }
    }
    
    
  • The packing type of Boolean is Boolean.

4.java type conversion

As a strongly typed programming language, Java teaches strict verification when variables of different types are assigned to each other

public class test{
    public static void main(String[] avgs){
        int a = 10;
        long b = 100L;
        b = a;   // Can be compiled
        a = b;   // Compilation failed
    }
}

4.1 automatic type conversion (implicit)

Automatic type conversion is:

The code does not need any processing. When the code is compiled, the compiler will process it automatically.

characteristic:

The conversion from small data range to large data range will be carried out automatically.

public class test{
    public static void main(String[] avgs){
       
        System.Out.println(1024);  
        // Integer is int by default
        System.Out.println(3.14);   
        // Floating point type is double by default
       int a = 100;
       long b = 10L;
       b = a;//Automatic type conversion
       a = b;//Compilation failed
       

Detailed explanation:

b = a: both a and b are integers. The range of a is small and the range of b is large. When a is assigned to b, the compiler will automatically promote a to long type and assign value

a = b: compilation reports an error. The range of long is larger than that of int, and there will be data loss, which is unsafe

public class test{
    public static void main(String[] avgs){
       float f = 3.14F;
       double d = 5.12;
       d = f; 
       f = d; 
      byte b1 = 100;  
      byte b2 = 257; 
    }
}

Detailed explanation:

d = f: the compiler will convert f to double and assign a value

f = d: Double indicates that the data range is large. If you directly give the float to double, you will lose data and it is not safe

byte b1 = 100: the compilation is passed, and 100 does not exceed the range of byte. The compiler implicitly converts 100 to byte.

byte b2 = 257: compilation failed. 257 exceeds the data range of byte and data is lost

4.2 cast (explicit)

public class test{
    public static void main(String[] avgs){
        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, strong conversion is required, 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, the data range is from large to small, which needs to be forcibly converted, otherwise the compilation fails
        a = d;   
    // Error reported, incompatible types
        a = (int)d;   
    // The data range of double is not as large as that of int, so it needs to be forcibly converted, and all data will be discarded after the decimal point
        byte b1 = 100;        
    // 100 is int by default and does not exceed the byte range. Implicit conversion
        byte b2 = (byte)257; 
    // 257 is int by default. If it exceeds the byte range, the conversion needs to be displayed, otherwise an error is reported
        boolean flag = true;
        a = flag;   
    // Compilation failed: incompatible types
        flag = a;   
    // Compilation failed: incompatible types
    }
}

Summary:

  1. Assignment between variables of different numeric types indicates that types with smaller range can be implicitly converted to types with larger range
  2. If you need to assign a type with a large range to a type with a small range, you need to force type conversion, but the precision may be lost
  3. When assigning a literal constant, Java will automatically check the range of numbers
  4. Cast type conversion may not succeed. Irrelevant types cannot be converted to each other

5.java type promotion

Rules for type promotion:

When different types of data operate with each other, the data with small data type will be promoted to the data with large data type.

Operation of int and long

public class test{
    public static void main(String[] avgs){
        int a = 10;
        long b = 20;
        int c = a + b;  
   // Compilation error: a + b = = "int + long -- > long + long will lose data when assigning to int
        long d = a + b;  
   // Compilation succeeded: a + B = = > int + long --- > long + long assigned to long  

Operation of byte and byte

public class test{
    public static void main(String[] avgs){
        byte a = 10;
        byte b = 20;
        byte c = a + b;
        System.out.println(c);
    }
}

Error message:
Test.java:5: error: incompatible type: conversion from int to byte may be lost
byte c = a + b;

Why error reporting:

Byte and byte are of the same type, but there is a compilation error The reason is that although both a and b are bytes, the calculation of a + b will first promote both a and b to int, and then calculate. The result is also int, which is assigned to c, and c is a byte type, so the above error will occur

Why should byte type be promoted to int type when calculating:

Because the CPU of the computer usually reads and writes data from the memory in units of 4 bytes For the convenience of hardware implementation, types less than 4 bytes, such as byte and short, will be promoted to int first, and then participate in the calculation

Modification:

public class test{
    public static void main(String[] avgs){
        byte a = 10;
        byte b = 20;
        byte c = (byte)(a + b);
        System.out.println(c);
    }
}

Summary:

  • For mixed operations of different types of data, those with a small range will be promoted to those with a large range

  • For short and byte types smaller than 4 bytes, they will be promoted to 4-byte int before operation

6. String type of Java (understand)

public class test{
    public static void main(String[] avgs){
        String s1 = "hello";
        String s2 = " world";
        System.out.println(s1);
        System.out.println(s2);
        System.out.println(s1+s2);   
        // s1+s2 indicates that s1 and s2 are spliced
    }
}

effect:

Operation in string splicing:

public static void main13(String[] args) {
        int m = 10;
        int n = 20;
        System.out.println("a+b = "+(a+b));
        System.out.println("a-b = "+(a-b));
        System.out.println("a*b = "+(a*b));
        System.out.println("a/b = "+(a/b));
        
    }
}

summary

Make a useful Jiaxin candy! Encourage with you ^^

Topics: Java Back-end