← Java tutorials

LESSON 03 / 40 · FREE TUTORIAL

Blocks Have Data Types, Too

First ask what the data is, and then decide how to save it

90–110 minutesJava 11+Beginner

WHAT YOU WILL MAKE

Make four Minecraft block data cards

The warehouse manager will not pour the potion into the grid containing the torch. Java's types do similar checks: integers, decimals, true and false, and literals have their own rules. In this lesson, we'll meet six common types, see why dividing 5 by 2 might result in 2, and create a set of information cards with clear fields for the four types of blocks.

Before you start: It is recommended to complete Lessons 1–2 first

01 / 12

Type is an agreement

Before choosing a container, first figure out whether you need to save the quantity, status or name.
Before choosing a container, first figure out whether you need to save the quantity, status or name.

"Health value 20" and "player name Alex" both appear to be displayed on the screen, but they are not the same data. Numbers can be involved in calculations, and text can be searched and intercepted. Types let the compiler know what you are going to save and how you are going to use it.

  • Full quantity: usually starts with int.
  • Decimals possible: double is used in this lesson.
  • True or false status: use boolean.
  • Name or message: Use String.

02 / 12

Six commonly used types, one data card

Find a suitable location for data
TypePurpose of this lessonExample
intOrdinary integer64
longA larger range of integers9_000_000_000L
doubleNumerical values with decimals1.5
booleanTrue and false statusfalse
charA UTF-16 unit'A'
StringA paragraph of text"Stone"

Complete program · BlockData.java

public class BlockData {
    public static void main(String[] args) {
        int maxStack = 64;
        long worldBlocks = 9_000_000_000L;
        double hardness = 1.5;
        boolean falls = false;
        char grade = 'A';
        String blockName = "Stone";
        System.out.println(blockName + ": " + hardness);
        System.out.println(maxStack + " / " + worldBlocks);
        System.out.println(falls + " / " + grade);
    }
}

Output

Stone: 1.5
64 / 9000000000
false / A

03 / 12

int and long: integers also have boundaries

Larger capacity, still scope
TypeRepresentable integer range
int-2,147,483,648 to 2,147,483,647
long-9,223,372,036,854,775,808
To 9,223,372,036,854,775,807

Snippet: place inside main and run separately

int stack = 64, height = 320, score = -15;
System.out.println(stack + height + score);
long exploredBlocks = 9_000_000_000L;
System.out.println(exploredBlocks);
int oneMillion = 1_000_000;
System.out.println(oneMillion);

Output

369
9000000000
1000000

Underlines in numbers only aid human reading and do not enter the output. A capital L at the end of a large integer indicates a long literal. 9_000_000_000 exceeds the range of int literals. You cannot understand it as int first and then expect the long on the left to automatically save the situation.

04 / 12

double: decimals are useful and approximate

Complete quantity and quantity with decimals
  1. intNumber of items
    For example 4
  2. doubleExercise coordinates or hardness
    For example 1.5
  3. floatAnother floating point type
    The literal can be written as 0.8F

Snippet: place inside main and run separately

double hardness = 1.5;
double spawnX = -23.75;
float lightRatio = 0.8F;
System.out.println(hardness);
System.out.println(spawnX);
System.out.println(lightRatio);
System.out.println(0.1 + 0.2);

Output

1.5
-23.75
0.8
0.30000000000000004

The last line is not a computer casually typing a few more words. Many decimal fractions cannot be represented exactly in binary floating point numbers, and operations will leave approximation errors. Coordinate experiments can usually accept this small error, but accurate pricing requires the selection of another tool.

05 / 12

boolean: only true and false

The judgment result is not the third type of number
ExpressionResultAnnotations
12 >= 8trueThere are at least 8
12 == 0falseNot 0
!falsetrueFlip the true from the false
!truefalseFlip again

Snippet: place inside main and run separately

int torches = 12;
boolean enoughLight = torches >= 8;
boolean empty = torches == 0;
boolean gateOpen = false;
gateOpen = !gateOpen;
System.out.println(enoughLight);
System.out.println(empty);
System.out.println(gateOpen);

Output

true
false
true

boolean expresses the answer to a question. It does not accept yes, True, or the number 1 as true or false literals. The comparison operation returns a boolean; it does not itself choose the next action for the program.

06 / 12

char and String: Are the quotation marks correct?

A piece of rune and a string of messages have different representations.
A piece of rune and a string of messages have different representations.
Single quotes and double quotes
Writing methodTypeMeaning
'A'charA UTF-16 unit
'钻'charThe Chinese character used in this example
"Alex"StringA string of text
"A"StringA string of length 1

Snippet: place inside main and run separately

char grade = 'A';
char symbol = '钻';
String playerName = "Alex";
System.out.println(grade + " / " + symbol);
System.out.println(playerName);

Output

A / 钻
Alex

07 / 12

Integer division: Where does the decimal part go?

First look at the types of calculations involved
ExpressionResultCalculate what happened
5 / 22Division of two integers
5.0 / 22.5One side is already double
(double) (5 / 2)2.0Calculate 2 first, then convert
(double) 5 / 22.5Convert first, then divide

Snippet: place inside main and run separately

System.out.println(5 / 2);
System.out.println(5.0 / 2);
System.out.println((double) (5 / 2));
System.out.println((double) 5 / 2);
System.out.println(-5 / 2);

Output

2
2.5
2.0
2.5
-2

Integer division truncates the decimal part toward zero: 5 / 2 is 2, -5 / 2 is -2. Don't write it off simply as "always round down." When decimals are required, let at least one side be a float before division occurs.

08 / 12

Type conversion: first ask whether information will be lost

The portal can change the representation, but it cannot retrieve the lost decimals out of thin air.
The portal can change the representation, but it cannot retrieve the lost decimals out of thin air.
Two different conversion routes
StartConversionEnd point
int 12assigned to double12.0
double 12.8(int) forced conversion12
double -12.8(int) forced conversion-12

Snippet: place inside main and run separately

int level = 12;
double displayLevel = level;
double exactXp = 12.8;
int shownXp = (int) exactXp;
System.out.println(displayLevel);
System.out.println(shownXp);
System.out.println((int) -12.8);

Output

12.0
12
-12

09 / 12

Type debugging: the left and right sides must be compatible

Checking whether tags and content match is the first step in locating type problems.
Checking whether tags and content match is the first step in locating type problems.

Intentional typo: check four lines separately

int hardness = 1.5;
char grade = "A";
String name = 'Steve';
long blocks = 9_000_000_000;
  • Decimal 1.5 should be caught by double.
  • This example value of char is written as 'A', using single quotes.
  • The name is a string of text, and it should be written "Steve".
  • Add a capital L at the end of the large integer literal.

Snippet: place inside main and run separately

String countText = "64";
int count = 64;
System.out.println(countText + 1);
System.out.println(count + 1);

Output

641
65

10 / 12

Design four block data cards

The book-style data card allows different fields to be in place, and also facilitates horizontal comparison.
The book-style data card allows different fields to be in place, and also facilitates horizontal comparison.
Practice data of this work
BlockUpper limit of each groupPractice HardnessGravity dropRating
Grass Block640.6falseC
sand640.5trueB
Obsidian6450.0falseS
Diamond Ore643.0falseA

Each card contains five items: name, maximum number of each group, hardness, whether it fell due to gravity and rating. The reference program below arranges them in a row, with four rows corresponding to four cards. The numerical values ​​are used in the exercise sheet on this page; the rating is our custom label for the work.

11 / 12

complete work: four cards are output one by one

Complete program · FourCards.java

public class FourCards {
    public static void main(String[] args) {
        String name = "Grass Block";
        int maxStack = 64;
        double hardness = 0.6;
        boolean falls = false;
        char grade = 'C';
        System.out.println(name + " | " + maxStack + " | "
            + hardness + " | " + falls + " | " + grade);
        name = "sand";
        hardness = 0.5;
        falls = true;
        grade = 'B';
        System.out.println(name + " | " + maxStack + " | "
            + hardness + " | " + falls + " | " + grade);
        name = "Obsidian";
        hardness = 50.0;
        falls = false;
        grade = 'S';
        System.out.println(name + " | " + maxStack + " | "
            + hardness + " | " + falls + " | " + grade);
        name = "Diamond Ore";
        hardness = 3.0;
        falls = false;
        grade = 'A';
        System.out.println(name + " | " + maxStack + " | "
            + hardness + " | " + falls + " | " + grade);
    }
}

Output

Grass Block | 64 | 0.6 | false | C
sand | 64 | 0.5 | true | B
Obsidian | 64 | 50.0 | false | S
Diamond Ore | 64 | 3.0 | false | A

12 / 12

Find reasons for your type selection

The clearer the data description, the more reliable subsequent calculations and judgments will be.
The clearer the data description, the more reliable subsequent calculations and judgments will be.
The ability map of the third lesson
  1. DistinguishNumeric value or text
  2. OptionsInteger or decimal
  3. CheckQuotes and suffixes
  4. ConversionCheck information loss
  5. ExplanationPrediction and re-verification
  • Basics: Save a pet's name, life, number of items, adult status and rating.
  • Advanced: Compare 9 / 4, 9.0 / 4, (double) 9 / 4; the result is 2, 2.25, 2.25.
  • Creation: Design a data card for the mysterious square, and add a boolean field for whether it emits light.

Technical reference: Java SE 11 Language Specification, Chapter 4 Data Types, Chapter 5 Type Conversion. Official documentation: docs.oracle.com/javase/specs/jls/se11/html/.

TAKE IT WITH YOU

Take the lesson offline

The complete lesson, code, diagrams and exercises, in your preferred language.