Java Primer Series (Variables and Types)

Introduction

Hello. This article is a summary article about variables and types for "people who are starting Java" and "people who are new to Java after a long time".

It does not explain programming itself, such as what variables are, so it may not be suitable for programming beginners.

The following articles are being prepared as an introductory Java series.

--Variables and types ← Now here -Type conversion --Variable scope (in preparation) --String operation (in preparation) --Array operation (in preparation) --Operator (in preparation) --Conditional branch (in preparation) --Repeat processing (in preparation) --About the class (in preparation) --Abstract class (in preparation) --Interface (in preparation) --Encapsulation (in preparation) --About the module (in preparation)

About the type

Although the concept of type inference is introduced from JDK10 I think Java is basically a statically typed language Describes the type.

The molds are roughly divided There are two types: basic type (primitive type) and reference type (class type).

Basic type (primitive type)

There are four types: integer, decimal point, boolean, and character. Unlike c language, there is no unsigned (no minus).

Integer type

There are four types depending on the size.

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

My impression is

Basically, use int, and if the size is not enough, use long. byte is used as an array type when binary data is read from a file or the like. I don't use short at all.

It has become. (If anyone knows something like best practice, please let me know)

If the value range is exceeded, the value will be inverted.

int test = 2147483647;
System.out.println(test); // -> 2147483647
test++;
System.out.println(test); // -> -2147483648
test--;
System.out.println(test); // -> 2147483647

Decimal point type

There are also two types depending on the size.

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

It is used when dealing with values after the decimal point such as division. In the integer type, the numbers after the decimal point are truncated, such as when dividing.

int a = 5, b = 3, c = 0;
c = a / b;
System.out.println(c);
// ->"1" is output.
float a = 5, b = 3, c = 0;
c = a / b;
System.out.println(c);
// -> 「1.6666666 "is output.
double a = 5, b = 3, c = 0;
c = a / b;
System.out.println(c);
// -> 「1.6666666666666667 "is output.

boolean type

A type that can only contain true or false.

boolean a = true, b = false;
boolean c = a == b;
System.out.println(c); // ->"False" is output

char type

A type that handles characters. Use an array when handling it as a character string.

char  a = 'a', b = 'b';
System.out.println(a); // ->Output as "a"
System.out.println(b); // ->Output as "b"
char[] str = {'a', 'b', 'c'};
System.out.println(str);  // ->"Abc" is output

Reference type (class type)

The type of the variable that stores the instance (entity) of the class is called the reference type (class type).

What we call a reference type is It doesn't hold the value itself, it holds where the value is located.

So copying a reference type variable means Instead of copying the value itself Please note that it means copying the information of the place where the value is placed.

The program below copies a reference type variable and then The value is rewritten using the copy destination variable.

public class Test {
	public int value = 0;
}
public class Main {
	public static void main(String[] args) {
		Test x = new Test();
		x.value = 5;
		Test y = new Test();
		y.value = 5;
		System.out.println(x.value); // ->Output as "5"
		System.out.println(y.value); // ->Output as "5"

		x = y;
		x.value = 10;
		System.out.println(x.value); // ->Output as "10"
		System.out.println(y.value); // ->Output as "10"
	}
}

x = y; So, what was copied to the variable x is the "information of the place where the value is placed" in the variable y, so Variables x and y contain information in the same location. Therefore, If you rewrite the value using the variable x, the value pointed to by the variable y will also be changed.

The "location" here is a location in memory space. It's an image similar to a C language pointer (although it's strictly different)

Wrapper class

Java has various classes as standard, There is a wrapper class that wraps the above basic type (primitive type).

For example, Integer class or String class.

Integer class is a class that handles numbers As with the int type, you can use assignments, four arithmetic operations, comparison operations, and so on.

class Main {
  public static void main(String[] args) {
    int a = 5;
    Integer b = 3;
    int c = a * b;
    int d = b;
    System.out.println(c);  // ->"15" is output
    System.out.println(a == b); // ->"False" is output
    System.out.println(d); // ->"3" is output
  }
}

String class is a class that handles strings Various functions for strings such as combining and comparing characters are implemented.


class Main {
  public static void main(String[] args) {
    String a = "a";
    String b = "b";
    String c = a + b;
    String d = b;
    System.out.println(c);           // ->"Ab" is output
    System.out.println(c.length());  // ->"2" is output
    System.out.println(a.equals(b)); // ->"False" is output
    System.out.println(b.equals(d)); // ->"True" is output
  }
}
class Main {
  public static void main(String[] args) {
    Integer i = 5;
    Integer j = 6;
    System.out.println(i);  // ->"5" is output
    System.out.println(j);  // ->"6" is output
    j = i;
    j = 7;
    System.out.println(i);  // ->"5" is output
    System.out.println(j);  // ->"7" is output

    String a = "a";
    String b = "b";
    System.out.println(a);  // ->Output as "a"
    System.out.println(b);  // ->Output as "b"
    b = a;
    b = "B";
    System.out.println(a);  // ->Output as "a"
    System.out.println(b);  // ->Output as "B"
  }
}

Variable declaration

In Java, it is declared in the form of "type name variable name".

Leave a space or tab character between the type name and the variable name.

You can also declare variables of the same type separated by commas.

int a;
int b;
int c, d, e;

Regarding arrays, I plan to write a separate article entitled "Array Manipulation".

Variable initialization

In Java, you can initialize a variable in the form "type name variable name = value".

int a = 5;
int b = 10;
int c = 5, d, e;

Variable declaration location

Depending on the programming language There may be a restriction that the variable declaration is only at the beginning of the processing block, You can declare it anywhere in Java.

class Main {
  public static void main(String[] args) {
    int n = 5;
    for (int i = 0; i < 5; i++) {
      System.out.println(i);
    }

    String msg = "";
    for (int i = 0; i < 5; i++) {
      msg += i;
    }
    System.out.println(msg);
  }
}

Variable name

Characters that can be used

Alphabet, numbers, underscore, $ It will be.

Case sensitive

Uppercase and lowercase letters are treated as different characters.

class Main {
  public static void main(String[] args) {
    String name = "name";
    String Name = "Name";
    System.out.println(name + Name); // ->"Name Name" is output
  }
}

Numbers cannot be used as the first letter

Add an alphabet at the beginning. 変数名の先頭に数字はダメ.png

Reserved words and prepared constants cannot be used

After booking, these are keywords for writing Java programs such as if and class. See the Oracle documentation (https://docs.oracle.com/javase/specs/jls/se11/html/jls-3.html#jls-3.9).

The provided constants are null, true, false. These also cannot be used as variable names.

in conclusion

How was Java's variables and types?

Until a while ago, languages such as ruby and javascript that do not write types I think that the merit of being able to write quickly without a mold was great, but

Recently (2020/05), I think that the necessity for types has been reviewed, such as the appearance of typescript.

end.

Recommended Posts

Java Primer Series (Variables and Types)
[Java] Variables and types
Java starting from beginner, variables and types
Java programming (variables and data)
Java Primer Series (Type Conversion)
Java variable declaration, initialization, and types
[Java] Basic types and instruction notes
Basic data types and reference types (Java)
Java array variables are reference types
About Java primitive types and reference types
Java basic data types and reference types
[Java] Exception types and basic processing
[Introduction to Java] Variables and types (variable declaration, initialization, data type)
Basics of Java development ~ How to write programs (variables and types) ~
[Java] Differences between instance variables and class variables
Java programming (static clauses and "class variables")
[Introduction to Java] Variable declarations and types
[WIP] Java variables
Java and JavaScript
XXE and Java
About Java data types (especially primitive types) and literals
Java and Swift comparison (1) Source control / Scope / Variables
Getters and setters (Java)
[Java] Types of comments and how to write them
[Java] Thread and Runnable
Java true and false
[Java] String comparison and && and ||
printf / arguments / variables / types
[Java] Difference between static final and final in member variables
[Java] Refer to and set private variables with reflection
Java review ① (development steps, basic grammar, variables, data types)
Java --Serialization and Deserialization
[Java] Arguments and parameters
[Swift] Constants and variables
About Java basic data types and reference type memory
Ruby variables and methods
I summarized the types and basics of Java exceptions
timedatectl and Java TimeZone
[Java] Branch and repeat
[Java] Main data types
Equivalence comparison of Java wrapper classes and primitive types
java (classes and instances)
[Java Silver] What are class variables instance variables and local variables?
Java basic data types
[Java] Overload and override
[Java] Make variables in extended for statement and for Each statement immutable
Java version 8 and later features
[Java] Stack area and static area
(Note) Java classes / variables / methods
[Java] Generics classes and generics methods
Java encryption and decryption PDF
Java and Iterator Part 1 External Iterator
About Java class loader types
Java if and switch statements
I investigated Java primitive types
The Java Primer passed the blockage
Java class definition and instantiation
Difference between variables and instance variables
Apache Hadoop and Java 9 (Part 1)
[Java] About String and StringBuilder
[Java] HashCode and equals overrides