[Introduction to Java] Variables and types (variable declaration, initialization, data type)

Purpose

For those who have just started learning programming including the Java language, and those who have already learned it, for review I'm writing to learn variable declaration, initialization, and data types.

[Introduction to Java Table of Contents] This time it's ** about variables and types **.

・ Variables and types ← Now here ・ Type conversion -Variable Scope -String operation -Array operationOperator ・ 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) -Exception handlingAbout lambda expressionAbout Stream API

Variable declaration and initialization

What is a variable? `A container for holding data used in the program. ``

To distinguish it from other variables

In the Java language, the following should be noted when declaring variables:

-What kind of values are stored, such as numbers and character strings ・ What kind of name should I use? ・ What is the first value to be stored?

Variable declaration

Data type variable name; Must be. (The data type will be described later)

Main.java


class Main {
  public static void main(String args[]) {
    //Variable declaration
    int num;

    //I get an error when I try to output
    System.out.println(num); // The local variable num may not have been initialized
  }
}

This error is a variable declaration but not initialized, Occurs because you used a variable that has no value set.

Variable initialization

After making data type variable name; Variable name = value; Must be.

Main.java


class Main {
  public static void main(String args[]) {
    //Variable declaration
    int num;

    //Variable initialization(Substitute 10 for num)
    num = 10;

    //output
    System.out.println(num); // 10
  }
}
  1. Declare the variable name "num"
  2. Initialize by substituting 10 for num. (Set value)
  3. Output

Variable declaration and initialization at the same time

Data type variable name = value; It is also possible to.

Main.java


class Main {
  public static void main(String args[]) {
    //Variable declaration and initialization
    int num = 10;

    //output
    System.out.println(num); // 10
  }
}

Variable name rules

-Only the following characters can be used as the first character. Alphabet (a ~ z, A ~ Z), dollar sign ($), underscore (_)

・ Numbers can be used after the second character.

-Case sensitive is strictly distinguished.

-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.

Details about reserved words: Official document

About the type

In Java, you had to specify the data type when declaring a variable.

The data types are roughly classified as follows.

Basic data type (primitive type)Reference type

Let's look at each.

Basic data type (primitive type)

boolean type

Mold size Range of values
boolean 1 bit true/Either false

Main.java


class Main {
  public static void main(String args[]) {
    boolean a = true;
    boolean b = false;

    System.out.println(a); // true
    System.out.println(b); // false
  }
}

Integer type

We are dealing with integer data.

Mold size Range of values
byte 8 bits -128〜127
short 16 bit -32768~32767
int 32 bit -2147483648~2147483647
long 64-bit -9223372036854775808~9223372036854775807

Main.java



System.out.println("Minimum value of byte= " + Byte.MIN_VALUE); // Minimum value of byte= -128
System.out.println("Maximum value of byte= " + Byte.MAX_VALUE); // Maximum value of byte= 127

System.out.println("Minimum value of short= " + Short.MIN_VALUE); // Minimum value of short= -32768
System.out.println("Maximum value of short= " + Short.MAX_VALUE); // Maximum value of short= 32767

System.out.println("Minimum value of int= " + Integer.MIN_VALUE); // Minimum value of int= -2147483648
System.out.println("Maximum value of int= " + Integer.MAX_VALUE); // Maximum value of int= 2147483647

System.out.println("Minimum value of long= " + Long.MIN_VALUE); // Minimum value of long= -9223372036854775808
System.out.println("Maximum value of long= " + Long.MAX_VALUE); // Maximum value of long= 9223372036854775807

The relationship is byte <short <int <long.

By the way, if the minimum and maximum values are exceeded, the values will be inverted. (Overflowing digits)

Main.java



System.out.println("Minimum value of previous byte= " + Byte.MIN_VALUE); //Minimum value of byte= -128
byte minByte = Byte.MIN_VALUE;
minByte--;
System.out.println("And the minimum value of byte= " +  minByte); //Minimum value of byte=127 ← inverted

System.out.println("Maximum value of previous byte= " + Byte.MAX_VALUE); //Maximum value of byte= 127
byte maxByte = Byte.MAX_VALUE;
maxByte++;
System.out.println("And the maximum value of byte= " + maxByte); //Maximum value of byte= -128 ← inverted

It is used when calculating integers.

Main.java



int a = 1;
int b = 1;
int sum = a + b;

System.out.println(sum); // 3

Precautions when using long type

When storing an integer that exceeds the int type in a variable, add "L" or "l" at the end.

Main.java


//I get an error
long longNumber = 214748364712342; // The literal 214748364712342 of type int is out of range

long longNumber = 214748364712342L; //Must be suffixed with "L" or "l".

System.out.println(longNumber); // 214748364712342

Floating point type

We are dealing with numerical data including a decimal point.

Mold size Range of values
float 32 bit ±1.40239846×10^-45~±3.40282347×10^38
double 64-bit ±4.94065645841246544×10^-324~±1.79769313486231570×10^308

Main.java



System.out.println("Minimum value of float= " + Float.MIN_VALUE); // Minimum value of float= 1.4E-45
System.out.println("Maximum float= " + Float.MAX_VALUE); // Maximum float= 3.4028235E38

System.out.println("Minimum value of double= " + Double.MIN_VALUE); // Minimum value of double= 4.9E-324
System.out.println("Maximum value of double= " + Double.MAX_VALUE); // Maximum value of double= 1.7976931348623157E308

It is used when doing a small number of calculations.

Main.java



//int type division
int a = 10;
int b = 3;
int result1 = a / b;

System.out.println(result1); // 3

//Float type division

//Floating point numbers are recognized as double type by default
// float c = 10.0; // Type mismatch: cannot convert from double to float

float c = 10F; //Therefore, when assigning to a float type variable, add F or f at the end.
float d = 3f; //Same as above
float result2 = c / d;

System.out.println(result2); // 3.3333333

//Double type division
double e = 10.0D; //Add D or d to the end
double f = 3.0; //However, as mentioned above, it is recognized as dobule type by default, so there is no problem even if it is omitted.
double result3 = e / f;

System.out.println(result3); // 3.3333333333333335

char type

It is used to represent one character.

Data type size Range of values
char 16 bit 16-bit character code

It is used to handle one character.

Precautions when using char type

Enclose in single quotes. It must be one character.

Main.java


//I get an error
char a = 'Ah'; // Invalid character constant
char a = "Ah";  // Type mismatch: cannot convert from String to char

char a = 'Ah';
System.out.println(a); //Ah

Reference type

All types except basic data types, including classes, arrays, interfaces, etc., are reference types.

The variable does not hold the value itself, but the place where the value is located. Reference type because it refers to where it is stored.

Test.java


public class Test {
  public int number = 0;
}

Main.java


class Main {
  public static void main(String args[]) {
    Test test = new Test();
    test.number = 10;
    System.out.println(test.number); // 10

    Test test2 = new Test();
    test2.number = 10;
    System.out.println(test2.number); // 10

    test = test2; //The value of test2 is not assigned to test, but the place where the value of test2 is placed.
    test.number = 99; //Therefore, if you change test to 99 here, it will be changed to test2.

    System.out.println(test.number); // 99
    System.out.println(test2.number); // 99

  }
}

test = test2; The value of test2 is not assigned to test, but the place where the value of test2 is placed is assigned.

test.number = 99; Therefore, if you change test to 99, it will be changed to test2.

Wrapper class

You can treat the value of the basic data type as a reference type.

Although it is a reference type, it is the same as the basic data type and its value does not change. The value itself is assigned, not the place where the value is placed.

Main.java


class Main {
  public static void main(String args[]) {
    Integer num = 10;
    Integer num2 = 10;
    System.out.println(num); // 10
    System.out.println(num2); // 10

    num = num2;
    num = 99;
    System.out.println(num); // 99
    System.out.println(num2); // 10

    String greet = "Good morning";
    String greet2 = "Hello";
    System.out.println(greet); //Good morning
    System.out.println(greet2); //Hello

    greet = greet2;
    greet = "Good Morning";
    System.out.println(greet); // Good Morning
    System.out.println(greet2); //Hello
  }
}

At the end

You learned about variable declaration, initialization, and data types. Next time, I will delve into Type conversion.

Recommended Posts

[Introduction to Java] Variables and types (variable declaration, initialization, data type)
Java variable declaration, initialization, and types
Java variable declaration, initialization, data type (cast and promotion)
[Introduction to Java] Variable declarations and types
[Java] Variables and types
[Introduction to Java] About array operations (1D array, 2D array declaration, instantiation, initialization and use)
Java programming (variables and data)
About Java basic data types and reference type memory
[Introduction to Java] Variable scope (scope, local variables, instance variables, static variables)
Java Primer Series (Variables and Types)
Basic data types and reference types (Java)
How to write Java variable declaration
Java basic data types and reference types
Basics of Java development ~ How to write programs (variables and types) ~
Java starting from beginner, variables and types
java variable declaration
[Java] Introduction to Java
Introduction to java
[Introduction to Java] About type conversion (cast, promotion)
About Java data types (especially primitive types) and literals
[Processing x Java] Data type and object-oriented programming
[Java] Incompatible types error occurred when assigning a character string to a char type variable
[Java] Types of comments and how to write them
[Java] Data type ①-Basic type
[Java] Refer to and set private variables with reflection
Going back to the beginning and getting started with Java ① Data types and access modifiers
Java review ① (development steps, basic grammar, variables, data types)
[Java] Main data types
Introduction to java command
Java basic data types
Introduction to Effective java by practicing and learning (Builder pattern)
Assign a Java8 lambda expression to a variable and reuse it
Initialization with an empty string to an instance of Java String type
[Java] Difference between assignment of basic type variable and assignment of reference type variable
About Java variable declaration statements
[Java] Introduction to lambda expressions
How to use Java variables
[Java] Introduction to Stream API
Java Learning 1 (learning various data types)
[Introduction to rock-paper-scissors games] Java
Evolutions of enums and switch statements! ?? Try to achieve algebraic data types and pattern matching in Java
Java SE Bronze Exam Number: 1Z0-818 (Data Declaration and Use) (October 2020)
[Java] How to convert from String to Path type and get the path
Introduction to Scala from a Java perspective, decompiled and understood (basic)
[Introduction to Java] About lambda expressions
[Java] Basic types and instruction notes
Introduction to Functional Programming (Java, Javascript)
[Java] Data type / matrix product (AOJ ⑧ Matrix product)
[Processing × Java] How to use variables
Java array variables are reference types
Initial introduction to Mac (Java engineer)
Assign evaluation result to Java variable
How to name variables in Java
About Java primitive types and reference types
[Java] Exception types and basic processing
How to use Java enum type
Introduction to Scala from a Java perspective (Class-Tuple edition) to decompile and understand