02-06 Java language foundation (define variables and matters needing attention)

Define variables of different data types

  • class DataType{
          
          
       public static void main(String[] args){
          
          
       	//整数类型
       	byte b = 10;    //占一个字节,-128~127
       	short s = 20;   //占两个字节
       	int i = 30;     //占四个字节,整数默认的数据类型就是int类型
       	long x = 4000000000L;    //占八个字节,最好加大写L,小写L太像1了
       	System.out.println(b);
       	System.out.println(s);
       	System.out.println(i);
       	System.out.println(x);
       }
    }
    

    In java, the default type of integer is int type, such as 10, 20, 30, 40. But 4000000000 exceeds the range of the int type, so an L is added at the end to indicate that this is a long type number. The error message without L is:
    The number of long type does not add L error report

  •  //浮点类型
     float f = 12.4f;      //四个字节
     double d = 23.5;      //八个字节
    

    Floating-point data is of double type by default. If you define float type data without adding f at the end of the number, an error will be reported
    Error defining float type data

  •  //字符类型
     char c = 'a';
     System.out.println(c);
    
  •  //布尔类型
     boolean b1 = true;
     boolean b2 = false;
     System.out.println(b1);
     System.out.println(b2);
    
  • Summary
    Generally, int is used for integer type and double is used for floating point type, both of which are default.
    It is necessary to define long or float data type, remember to add L or F at the end (not case sensitive)

Notes on using variables

  • Scope problem The
    same variable name cannot be defined repeatedly in the same scope

    class DataType2{
          
          
    	public static void main(String[] args){
          
          
    		int x = 10;
    		int x = 20;
    		System.out.println(x);
    	}
    }
    

    Error message:
    Repeated declaration of the same variable in the same scope reports an error

  • Initialization problem
    local variables must be assigned before they are used

    class DataType3{
          
          
    	public static void main(String[] args){
          
          
    		int y;
    		System.out.println(y);
    	}
    }
    

    Error message:
    Insert picture description here

  • One statement can define several variables

    class DataType4{
          
          
    	public static void main(String[] args){
          
          
    		int a = 10, b = 20 ,c = 40, d = 40;
    		System.out.println(a);
    		System.out.println(b);
    		System.out.println(c);
    		System.out.println(d);
    	}
    }
    

Guess you like

Origin blog.csdn.net/qq_37054755/article/details/110731301