Java variable declaration, initialization, data type (cast and promotion)

Purpose of this article

I'm studying Java, and I'm writing an article to output what I've learned and to establish my knowledge. I will describe what I have learned separately as follows.

-Java variable declaration / initialization / data type (cast and promotion) ・ Type conversion -Variable scope ・ Character string operation (in preparation) ・ Array operation (in preparation) ・ Operator (in preparation) ・ Conditional branch (in preparation) ・ Repeat processing (in preparation) ・ About class (in preparation) ・ Abstract class (in preparation) ・ Interface (in preparation) ・ Encapsulation (in preparation) ・ About the module (in preparation)

Variable definition

Defining variables in Java requires the following two steps:

  1. Specify the data type of the value to be put in the variable
  2. Decide the variable name

Example:

  1. int (numerical value) type     int number; int is the data type that represents a number, and number is the variable name. In the above example, the int type variable number is defined.
  2. string type     String text; String is a data type that represents a string and is capitalized. text is the variable name. In the above example, a variable text of type String is defined.

As with 1 and 2, add a semicolon at the end of the sentence.

Variable naming rules

・ The first character is Alphabet uppercase / lowercase, $, _, etc. symbols

-Case sensitive is strictly distinguished.

・ Numbers can be used after the second character.

-There is no limit on the number of characters (length).

-Null, true, false cannot be used.

・ Reserved words cannot be used. Reserved words are names that are already used in the Java language. Example: if, while, switch, etc.

Variable initialization

As shown in the example below, assigning a value at the same time as defining a variable is called variable initialization. Example:

  1. int (integer) type     int number = 3; In the above example, the int type variable number is defined and the number 3 is assigned.
  2. String * * There is no string type that represents multiple characters in the basic Java type. The string type is provided as a class called String. * String text =" character "; In the above example, a String type variable text is defined and the "character" of the string is assigned.

java data type

The types are mentioned in the above explanation, but the types are also subdivided according to the type of value. There are data types depending on the range of data that can be handled. The larger the range of data, the more memory it consumes. Make sure to select the appropriate data type according to the amount of data to be handled and the amount of memory.

Integer type

Data type size Range of values
byte 1byte -Integer value from 128 to 127
char 1byte '\u0000'From'\uffff'An integer value up to. (This is from 0 to 65535)
short 1byte -An integer value from 32768 to 32767
int 1byte -An integer value from 2147483648 to 2147483647.
long 1byte -An integer value from 9223372036854775808 to 9223372036854775807.

Floating point type

Data type size Range of values
float 4byte 32-bit single precision decimal point
double 8byte 63-bit single precision decimal point

Logical type

Data type size Range of values
boolean 1bit A value that is either true or false.

Reference type

There are four reference types: class type, interface type, type variable, and array type. Class-type and interface-type data indicate where the object is, and array-type data indicates where the array object is. The difference from the basic type as before is that the basic type represents the data itself, while the reference type indicates the location of the data. To put it simply, the basic type represents the house itself, and the reference type represents the address of the house.

Example:

Main.java


class Main{
  public static void main(String args[]){
    int a[] = {1};
    int b[] = a;  //Where b has the same reference value as a
    System.out.println(a[0]);  //a and b have the same output result
    System.out.println(b[0]);

    b[0] = 5;  //The referenced value is updated

    System.out.println(a[0]);  //a and b have the same output result
    System.out.println(b[0]);
  }
}

Execution result ↓

1
1
5
5

In the above example, a and b see the same reference by the code "int b [] = a;". Until the reference value changes with the code "b [0] = 5;" on the 5th line, both refer to "1", but after the reference value is updated to "5" Refers to "5".

Cast (type conversion)

Performing variable type conversion is called casting. Variables that were initially int type can be changed to long type and vice versa. When calculating multiplication etc., it can only be done with the same data type. When calculating different types, convert them to the same type. There are two types of Java type conversion methods: automatic conversion method and manual conversion method. If you add the String type and the int type, the int type is automatically converted to the String type.

Example:

test.java


System.out.printIn("Apples" + "5" + "There are");

→ Converted to "Apples" + "5" + "There are",

There are 5 apples.

Is output.

Even if you do a lot of calculations with the integer type int type, the calculation result will be the numeric type. Example:

test.java


System.out.printIn(5/2);

2

Actually, 2.5 is the correct answer, but since 2.5 is a double type, it cannot be calculated between int types. If you want the calculation result of 5/2 to be 2.5,

Main.java


System.out.printIn(5.0/2);

will do. This is because the calculation result of int type and double type is double type (if one is double, the result is double). In this way, when the calculation result is represented by a floating point number, the integer is represented by a decimal number.

Cast when you want to get an accurate value in the calculation between int types.

Main.java


int number1 = 13;
int number2 = 4;
System.out.printIn((double)number1/number2);

3.25

Also, ** casting from large type to small type can result in some data loss. ** ** Note the original base type data range and the cast base type data range.

Main.java


public class Main {
 
    public static void main(String[] args) {
        double doubleMax = Double.MAX_VALUE;
        int result = (int) doubleMax; //Cast the maximum value of double to int type and assign it to the int type variable result
        
        System.out.println(doubleMax);
        System.out.println(result);
    }

}

Execution result ↓

1.7976931348623157E308
2147483647

It does not cause an error, but the maximum value of double type is replaced with the maximum value of int type, which is an unintended value.

Promotion (type promotion)

There is also a promotion for type conversion. Promotion is a mechanism that automatically converts the value to a wider type when calculating the value. For example, when calculating a number of type long, the type of the other value is automatically converted to long.

Calculates a byte type variable a and a long type variable b. An error will occur even if you try to receive the result with the byte type variable answer.

Main.java


class Main{
  public static void main(String args[]){
      byte a = 10;
      long b = 20000;

      byte answer = a * b;
      System.out.println(answer);
  }
}

Execution result ↓

//Type mismatch: cannot convert from long to byte

To get the correct result, change the type of the variable answer that receives the result from byte to long.

Main.java


class Main{
  public static void main(String args[]){
      byte a = 10;
      long b = 20000;

      long answer = a * b;
      System.out.println(answer);
  }
}

Execution result ↓

200000

If neither is a long type, the Byte type, short type, and char type values are converted to int type.

Also, if one is a float and the other is not a double, the other value will be converted to a float.

Main.java


class Main{
  public static void main(String args[]){
      byte a = 10;
      float b = 0.83f;

      byte answer = a * b;
      System.out.println(answer);
  }
}

Execution result ↓

//Type mismatch: cannot convert from float to byte

Main.java


class Main{
  public static void main(String args[]){
      byte a = 10;
      float b = 0.83f;

      float answer = a * b;
      System.out.println(answer);
  }
}

Execution result ↓

8.3

Or, if you cast the calculation result in bytes, no error will occur, but in that case, the decimal point will be omitted, so it will not be an exact answer.

Main.java


class Main{
  public static void main(String args[]){
      byte a = 10;
      float b = 0.83f;

      byte answer = (byte)(a * b);
      System.out.println(answer);
  }
}

Execution result ↓

8

If you calculate with char type or byte type without promotion, the answer will be overwhelming and the answer will not be correct. Also, if you do not cast the calculation between bytes, an error will occur.

Main.java


class Main{
  public static void main(String args[]){
      byte a = 1;
      byte b = 2;

      byte answer = a * b;
      System.out.println(answer);
  }
}

Execution result ↓

//Type mismatch: cannot convert from int to byte Java

To get the correct result, change the type of the variable answer that receives the result from byte to int.

Main.java


class Main{
  public static void main(String args[]){
      byte a = 1;
      byte b = 2;

      int answer = a * b;
      System.out.println(answer);
  }
}

Execution result ↓

 2

Or, if you want to receive the result in bytes, cast the calculation result to bytes.

Main.java


class Main{
  public static void main(String args[]){
      byte a = 1;
      byte b = 2;

      byte answer = (byte)(a * b);
      System.out.println(answer);
  }
}

Execution result ↓

2

in conclusion

As you can see, in java, if you don't pay attention to the type, an error will occur in an unexpected place, so be careful.

Recommended Posts

Java variable declaration, initialization, data type (cast and promotion)
[Introduction to Java] Variables and types (variable declaration, initialization, data type)
Java variable declaration, initialization, and types
java variable declaration
[Introduction to Java] About type conversion (cast, promotion)
[Processing x Java] Data type and object-oriented programming
[Java] Data type ①-Basic type
About Java basic data types and reference type memory
Java learning memo (data type)
Basic data type and reference type
Java programming (variables and data)
About Java variable declaration statements
[Java] Difference between assignment of basic type variable and assignment of reference type variable
Basic data types and reference types (Java)
[Java] Data type / matrix product (AOJ ⑧ Matrix product)
Java SE Bronze Exam Number: 1Z0-818 (Data Declaration and Use) (October 2020)
How to write Java variable declaration
Java basic data types and reference types
[Introduction to Java] About array operations (1D array, 2D array declaration, instantiation, initialization and use)
[Java] Implicit type cast (AOJ10-sum of numbers)
Java date data type conversion (Date, Calendar, String)
Create variable length binary data in Java
Use PostgreSQL data type (jsonb) from Java
[Java ~ Variable definition, type conversion ~] Study memo
[Personal memo] Java data type is annoying
[Java] Data type / string class cheat sheet
Java study # 3 (type conversion and instruction execution)
[Introduction to Java] Variable declarations and types
[Java] Calculation mechanism, operators and type conversion
About Java data types (especially primitive types) and literals
About var used in Java (Local Variable Type)
[Java] Use of final in local variable declaration
Organized memo in the head (Java --Data type)
[Java] char type can be cast to int type
[Java] Difference between "final variable" and "immutable object"