Java data types

xingyun86 2021-5-30 1410

In this part of the Java tutorial, we will talk about data types.

Computer programs, including spreadsheets, text editors, calculators, or chat clients, work with data. Tools to work with various data types are essential part of a modern computer language. A  is a set of values and the allowable operations on those values.

Java programming language is a statically typed language. It means that every variable and every expression has a type that is known at compile time. Java language is also a strongly typed language because types limit the values that a variable can hold or that an expression can produce, limit the operations supported on those values, and determine the meaning of the operations. Strong static typing helps detect errors at compile time. Variables in dynamically typed languages like Ruby or Python can receive different data types over the time. In Java, once a variable is declared to be of a certain data type, it cannot hold values of other data types.

There are two fundamental data types in Java: primitive types and reference types. Primitive types are:

  • boolean
  • char
  • byte
  • short
  • int
  • long
  • float
  • double

There is a specific keyword for each of these types in Java. Primitive types are not objects in Java. Primitive data types cannot be stored in Java collections which work only with objects. They can be placed into arrays instead.

The reference types are:

  • class types
  • interface types
  • array types

There is also a special null type which represents a non-existing value.

In Ruby programming language, everything is an object. Even basic data types.

#!/usr/bin/ruby

4.times { puts "Ruby" }

This Ruby script prints four times "Ruby" string to the console. We call a times method on the 4 number. This number is an object in Ruby.

Java has a different approach. It has primitive data types and wrapper classes. Wrapper classes transform primitive types into objects. Wrapper classes are covered in the next chapter.

Boolean values

There is a duality built in our world. There is a Heaven and Earth, water and fire, jing and jang, man and woman, love and hatred. In Java the boolean data type is a primitive data type having one of two values: true or false.

Happy parents are waiting a child to be born. They have chosen a name for both possibilities. If it is going to be a boy, they have chosen Robert. If it is going to be a girl, they have chosen Victoria.

com/zetcode/BooleanType.java
package com.zetcode;

import java.util.Random;

public class BooleanType {

    public static void main(String[] args) {

        String name = "";
        Random r = new Random();
        boolean male = r.nextBoolean();

        if (male == true) {

            name = "Robert";
        }

        if (male == false) {

            name = "Victoria";
        }

        System.out.format("We will use name %s%n", name);

        System.out.println(9 > 8);
    }
}

The program uses a random number generator to simulate our case.

Random r = new Random();
boolean male = r.nextBoolean();

The Random class is used to produce random numbers. The nextBoolean() method returns randomly a boolean value.

if (male == true) {

    name = "Robert";
}

If the boolean variable male equals to true, we set the name variable to "Robert". The if keyword works with boolean values.

if (male == false) {

    name = "Victoria";
}

If the random generator chooses false than we set the name variable to "Victoria".

System.out.println(9 > 8);

Relational operators result in a boolean value. This line prints true to the console.

$ java BooleanType.java
We will use name Robert
true
$ java BooleanType.java
We will use name Robert
true
$ java BooleanType.java
We will use name Victoria
true

Running the program several times.

Integers

Integers are a subset of the real numbers. They are written without a fraction or a decimal component. Integers fall within a set Z = {..., -2, -1, 0, 1, 2, ...} Integers are infinite.

In computer languages, integers are (usually) primitive data types. Computers can practically work only with a subset of integer values, because computers have finite capacity. Integers are used to count discrete entities. We can have 3, 4, or 6 humans, but we cannot have 3.33 humans. We can have 3.33 kilograms, 4.564 days, or 0.4532 kilometers.

TypeSizeRange
byte8 bits-128 to 127
short16 bits-32,768 to 32,767
char16 bits0 to 65,535
int32 bits-2,147,483,648 to 2,147,483,647
long64 bits-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
Table: Integer types in Java

These integer types may be used according to our needs. We can then use the byte type for a variable that stores the number of children a woman gave birth to. The oldest verified person died at 122, therefore we would probably choose at least the short type for the age variable. This will save us some memory.

Integer literals may be expressed in decimal, hexadecimal, octal, or binary notations. If a number has an ASCII letter L or l suffix, it is of type long. Otherwise it is of type int. The capital letter L is preferred for specifying long numbers, since lowercase l can be easily confused with number 1.

int a = 34;
byte b = 120;
short c = 32000;
long d = 45000;
long e = 320000L;

We have five assignments. Values 34, 120, 32000, and 45000 are integer literals of type int. There are no integer literals for byte and short types. If the values fit into the destination type, the compiler does not complain and performs a conversion automatically. For long numbers smaller than Integer.MAX_VALUE, the L suffix is optional.

long x = 2147483648L;
long y = 2147483649L;

For long numbers larger than Integer.MAX_VALUE, we must add the L suffix.

When we work with integers, we deal with discrete items. For instance, we can use integers to count apples.

com/zetcode/Apples.java
package com.zetcode;

public class Apples {

    public static void main(String[] args) {

        int baskets = 16;
        int applesInBasket = 24;

        int total = baskets * applesInBasket;

        System.out.format("There are total of %d apples%n", total);
    }
}

In our program, we count the total amount of apples. We use the multiplication operation.

int baskets = 16;
int applesInBasket = 24;

The number of baskets and the number of apples in each basket are integer values.

int total = baskets * applesInBasket;

Multiplying those values we get an integer, too.

$ java Apples.java
There are total of 384 apples

This is the output of the program.

Integers can be specified in four different notations in Java: decimal, octal, hexadecimal, and binary. The binary notation was introduced in Java 7. Decimal numbers are used normally as we know them. Octal numbers are preceded with a 0 character and followed by octal numbers. Hexadecimal numbers are preceded with 0x characters and followed by hexadecimal numbers. Binary numbers start with 0b and are followed by binary numbers (zeroes and ones).

com/zetcode/IntegerNotations.java
package com.zetcode;

public class IntegerNotations {

    public static void main(String[] args) {

        int n1 = 31;
        int n2 = 0x31;
        int n3 = 031;
        int n4 = 0b1001;

        System.out.println(n1);
        System.out.println(n2);
        System.out.println(n3);
        System.out.println(n4);
    }
}

We have four integer variables. Each of the variables is assigned a value with a different integer notation.

int n1 = 31;
int n2 = 0x31;
int n3 = 031;
int n4 = 0b1001;

The first is decimal, the second hexadecimal, the third octal, and the fourth binary.

$ java IntegerNotations.java
31
49
25
9

We see the output of the program.

Big numbers are difficult to read. If we have a number like 245342395423452, we find it difficult to read it quickly. Outside computers, big numbers are separated by spaces or commas. Since Java SE 1.7, it is possible to separate integers with an underscore.

The underscore cannot be used at the beginning or end of a number, adjacent to a decimal point in a floating point literal, and prior to an F or L suffix.

com/zetcode/UsingUnderscores.java
package com.zetcode;

public class UsingUnderscores {

    public static void main(String[] args) {

        long a = 23482345629L;
        long b = 23_482_345_629L;

        System.out.println(a == b);
    }
}

This code sample demonstrates the usage of underscores in Java.

long a = 23482345629L;
long b = 23_482_345_629L;

We have two identical long numbers. In the second one we separate every three digits in a number. Comparing these two numbers we receive a boolean true. The L suffix tells the compiler that we have a long number literal.

Java byteshortint and long types are used do represent fixed precision numbers. This means that they can represent a limited amount of integers. The largest integer number that a long type can represent is 9223372036854775807. If we deal with even larger numbers, we have to use the java.math.BigInteger class. It is used to represent immutable arbitrary precision integers. Arbitrary precision integers are only limited by the amount of computer memory available.

com/zetcode/VeryLargeIntegers.java
package com.zetcode;

import java.math.BigInteger;

public class VeryLargeIntegers {

    public static void main(String[] args) {

        System.out.println(Long.MAX_VALUE);

        BigInteger b = new BigInteger("92233720368547758071");
        BigInteger c = new BigInteger("52498235605326345645");

        BigInteger a = b.multiply(c);

        System.out.println(a);
    }
}

With the help of the java.math.BigInteger class, we multiply two very large numbers.

System.out.println(Long.MAX_VALUE);

We print the largest integer value which can be represented by a long type.

BigInteger b = new BigInteger("92233720368547758071");
BigInteger c = new BigInteger("52498235605326345645");

We define two BigInteger objects. They both hold larger values that a long type can hold.

BigInteger a = b.multiply(c);

With the multiply() method, we multiply the two numbers. Note that the BigInteger numbers are immutable. The operation returns a new value which we assign to a new variable.

System.out.println(a);

The computed integer is printed to the console.

$ java VeryLargeIntegers.java
9223372036854775807
4842107582663807707870321673775984450795

This is the example output.

Arithmetic overflow

An arithmetic overflow is a condition that occurs when a calculation produces a result that is greater in magnitude than that which a given register or storage location can store or represent.

com/zetcode/Overflow.java
package com.zetcode;

public class Overflow {

    public static void main(String[] args) {

        byte a = 126;

        System.out.println(a);
        a++;

        System.out.println(a);
        a++;

        System.out.println(a);
        a++;

        System.out.println(a);
    }
}

In this example, we try to assign a value beyond the range of a data type. This leads to an arithmetic overflow.

$ java Overflow.java
126
127
-128
-127

When an overflow occurs, the variable is reset to negative upper range value.

Floating point numbers

Real numbers measure continuous quantities, like weight, height, or speed. Floating point numbers represent an approximation of real numbers in computing. In Java we have two primitive floating point types: float and double. The float is a single precision type which store numbers in 32 bits. The double is a double precision type which store numbers in 64 bits. These two types have fixed precision and cannot represent exactly all real numbers. In situations where we have to work with precise numbers, we can use the BigDecimal class.

Floating point numbers with an F/f suffix are of type floatdouble numbers have D/d suffix. The suffix for double numbers is optional.

Let's say a sprinter for 100m ran 9.87s. What is his speed in km/h?

com/zetcode/Sprinter.java
package com.zetcode;

public class Sprinter {

    public static void main(String[] args) {

        float distance;
        float time;
        float speed;

        distance = 0.1f;

        time = 9.87f / 3600;

        speed = distance / time;

        System.out.format("The average speed of a sprinter is %f km/h%n", speed);
    }
}

In this example, it is necessary to use floating point values. The low precision of the float data type does not pose a problem in this case.

distance = 0.1f;

100m is 0.1km.

time = 9.87f / 3600;

9.87s is 9.87/60*60h.

speed = distance / time;

To get the speed, we divide the distance by the time.

$ java Sprinter.java
The average speed of a sprinter is 36.474163 km/h

This is the output of the program. A small rounding error in the number does not affect our understanding of the sprinter's speed.

The float and double types are inexact.

com/zetcode/FloatingInPrecision.java
package com.zetcode;

public class FloatingInPrecision {

    public static void main(String[] args) {

        double a = 0.1 + 0.1 + 0.1;
        double b = 0.3;

        System.out.println(a);
        System.out.println(b);

        System.out.println(a == b);
    }
}

The code example illustrates the inexact nature of the floating point values.

double a = 0.1 + 0.1 + 0.1;
double b = 0.3;

We define two double values. The D/d suffix is optional. At first sight, they should be equal.

System.out.println(a);
System.out.println(b);

Printing them will show a very small difference.

System.out.println(a == b);

This line will return false.

$ java FloatingInPrecision.java
0.30000000000000004
0.3
false

There is a small margin error. Therefore, the comparison operator returns a boolean false.

When we work with money, currency, and generally in business applications, we need to work with precise numbers. The rounding errors of the basic floating point types are not acceptable.

com/zetcode/CountingMoney.java
package com.zetcode;

public class CountingMoney {

    public static void main(String[] args) {

        float c = 1.46f;
        float sum = 0f;

        for (int i=0; i<100_000; i++) {

            sum += c;
        }

        System.out.println(sum);
    }
}

The 1.46f represents 1 euro and 46 cents. We create a sum from 100000 such amounts.

for (int i=0; i<100_000; i++) {

    sum += c;
}

In this loop, we create a sum from 100000 such amounts of money.

$ java CountingMoney.java
146002.55

The calculation leads to an error of 2 euros and 55 cents.

To avoid this margin error, we utilize the BigDecimal class. It is used to hold immutable, arbitrary precision signed decimal numbers.

com/zetcode/CountingMoney2.java
package com.zetcode;

import java.math.BigDecimal;

public class CountingMoney2 {

    public static void main(String[] args) {

        BigDecimal c = new BigDecimal("1.46");
        BigDecimal sum = new BigDecimal("0");

        for (int i=0; i<100_000; i++) {

            sum = sum.add(c);
        }

        System.out.println(sum);
    }
}

We do the same operation with the same amount of money.

BigDecimal c = new BigDecimal("1.46");
BigDecimal sum = new BigDecimal("0");

We define two BigDecimal numbers.

for (int i=0; i<100_000; i++) {

    sum = sum.add(c);
}

The BigDecimal number is immutable, therefore a new object is always assigned to the sum variable in every loop.

$ java CountingMoney2.java
146000.00

In this example, we get the precise value.

Java supports the scientific syntax of the floating point values. Also known as exponential notation, it is a way of writing numbers too large or small to be conveniently written in standard decimal notation.

com/zetcode/ScientificNotation.java
package com.zetcode;

import java.math.BigDecimal;
import java.text.DecimalFormat;

public class ScientificNotation {

    public static void main(String[] args) {

        double n = 1.235E10;
        DecimalFormat dec = new DecimalFormat("#.00");

        System.out.println(dec.format(n));

        BigDecimal bd = new BigDecimal("1.212e-19");

        System.out.println(bd.toEngineeringString());
        System.out.println(bd.toPlainString());
    }
}

We define two floating point values using the scientific notation.

double n = 1.235E10;

This is a floating point value of a double type, written in scientific notation.

DecimalFormat dec = new DecimalFormat("#.00");

System.out.println(dec.format(n));

We use the DecimalFormat class to arrange our double value into standard decimal format.

BigDecimal bd = new BigDecimal("1.212e-19");

System.out.println(bd.toEngineeringString());
System.out.println(bd.toPlainString());

The BigDecimal class takes a floating point value in a scientific notation as a parameter. We use two methods of the class to print the value in the engineering and plain strings.

$ java ScientificNotation.java
12350000000.00
121.2E-21
0.0000000000000000001212

This is the example output.

Enumerations

An  type is a special data type that enables for a variable to be a set of predefined constants. A variable that has been declared as having an enumerated type can be assigned any of the enumerators as a value. Enumerations make the code more readable. Enumerations are useful when we deal with variables that can only take one out of a small set of possible values.

com/zetcode/Enumerations.java
package com.zetcode;

public class Enumerations {

    enum Days {

        MONDAY,
        TUESDAY,
        WEDNESDAY,
        THURSDAY,
        FRIDAY,
        SATURDAY,
        SUNDAY
    }

    public static void main(String[] args) {

        Days day = Days.MONDAY;

        if (day == Days.MONDAY) {

            System.out.println("It is Monday");
        }

        System.out.println(day);

        for (Days d : Days.values()) {

            System.out.println(d);
        }
    }
}

In our code example, we create an enumeration for week days.

enum Days {

    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY
}

An enumeration representing the days of a week is created with a enum keyword. Items of an enumeration are constants. By convention, constants are written in uppercase letters.

Days day = Days.MONDAY;

We have a variable called day which is of enumerated type Days. It is initialized to Monday.

if (day == Days.MONDAY) {

    System.out.println("It is Monday");
}

This code is more readable than if comparing a day variable to some number.

System.out.println(day);

This line prints Monday to the console.

for (Days d : Days.values()) {

    System.out.println(d);
}

This loop prints all days to the console. The static values() method returns an array containing the constants of this enum type, in the order they are declared. This method may be used to iterate over the constants with the enhanced for statement. The enhanced for goes through the array, element by element, and prints them to the terminal.

$ java Enumerations.java
It is Monday
MONDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY

This is the example output.

It is possible to give some values to the enumeration constants.

com/zetcode/Enumerations2.java
package com.zetcode;

enum Season {

    SPRING(10),
    SUMMER(20),
    AUTUMN(30),
    WINTER(40);

    private int value;

    private Season(int value) {
        this.value = value;
    }

    public int getValue() {

        return value;
    }
}

public class Enumerations2 {

    public static void main(String[] args) {

        for (Season season : Season.values()) {
            System.out.println(season + " " + season.getValue());
        }
    }
}

The example contains a Season enumeration which has four constants.

SPRING(10),
SUMMER(20),
AUTUMN(30),
WINTER(40);

Here we define four constants of the enum. The constants are given specific values.

private int value;

private Season(int value) {
    this.value = value;
}

When we define the constants, we also have to create a constructor. Constructors will be covered later in the tutorial.

SPRING 10
SUMMER 20
AUTUMN 30
WINTER 40

This is the example output.

Strings and chars

String is a data type representing textual data in computer programs. A string in Java is a sequence of characters. A char is a single character. Strings are enclosed by double quotes.

com/zetcode/StringsChars.java
package com.zetcode;

public class StringsChars {

    public static void main(String[] args) {

        String word = "ZetCode";

        char c = word.charAt(0);
        char d = word.charAt(3);

        System.out.println(c);
        System.out.println(d);
    }
}

The program prints Z character to the terminal.

String word = "ZetCode";

Here we create a string variable and assign it "ZetCode" value.

char c = word.charAt(0);

The charAt() method returns the char value at the specified index. The first char value of the sequence is at index 0, the next at index 1, and so on.

$ java StringsChars.java
Z
C

The program prints the first and the fourth character of the "ZetCode" string to the console.

Arrays

Array is a complex data type which handles a collection of elements. Each of the elements can be accessed by an index. All the elements of an array must be of the same data type.

com/zetcode/ArraysEx.java
package com.zetcode;

public class ArraysEx {

    public static void main(String[] args) {

        int[] numbers = new int[5];

        numbers[0] = 3;
        numbers[1] = 2;
        numbers[2] = 1;
        numbers[3] = 5;
        numbers[4] = 6;

        int len = numbers.length;

        for (int i = 0; i < len; i++) {

            System.out.println(numbers[i]);
        }
    }
}

In this example, we declare an array, fill it with data and then print the contents of the array to the console.

int[] numbers = new int[5];

We create an integer array which can store up to 5 integers. So we have an array of five elements, with indexes 0..4.

numbers[0] = 3;
numbers[1] = 2;
numbers[2] = 1;
numbers[3] = 5;
numbers[4] = 6;

Here we assign values to the created array. We can access the elements of an array by the array access notation. It consists of the array name followed by square brackets. Inside the brackets we specify the index to the element that we want.

int len = numbers.length;

Each array has a length property which returns the number of elements in the array.

for (int i = 0; i < len; i++) {

    System.out.println(numbers[i]);
}

We traverse the array and print the data to the console.

$ java ArraysEx.java
3
2
1
5
6

This is the output of the program.

In this part of the Java tutorial, we covered data types in Java.


×
打赏作者
最新回复 (0)
只看楼主
全部楼主
返回