Primitive Types and Expressions

This is the seventh lesson in a series introducing 10-year-olds to programming through Minecraft. Learn more here.

Primitive Types

There are several types of variables that are part of the Java language; these are called primitive types. The most important ones for Minecraft are:

char: A single character (e.g. 'a', 'x')

integer: A whole number (e.g. -10, 0, 1, 145). It has a minimum value of -2,147,483,648 and maximum value of 2,147,483,647.

float: A decimal number (e.g. 3.62341, 1.5). Floats in Java are written with an 'f' or 'F' after them. For example:

float dirtHardness = 0.5f;

boolean: Either true or false.

Arithmetic Expressions

Most of the expressions we'll use for Minecraft are addition and subtraction:

int x = 5;
int y = x - 3;
int z = y + 2;

In this case, y would have a value of 2 and z would have a value of 4. We can also perform multiplication and division.

Boolean expressions

There are two ways to write boolean expressions: comparisons and boolean operators.

Comparisons

  • >: greater than
  • <: less than
  • >=: greater than or equal to
  • <=: less than or equal to
  • ==: equal to
  • !=: not equal to

Note: = assigns a value to a variable, but == compares two variables.

int x = 5;
int y = 2;

boolean isXGreaterThanY = x > y; // true
boolean isYLessThanOrEqualToX = y <= x; // true

Boolean

  • ! : Boolean NOT
  • && : Boolean AND
  • || : Boolean inclusive OR
  • ^ : Boolean exclusive OR

We probably won't use ^ very often.

int myAge = 34;
int yourAge = 18;
int dadsAge = 60;

// These all evaluate to true
boolean isYoungerThan50 = !myAge > 50;

boolean bothOfUsAreYoungerThan50 = 
            myAge < 50 && yourAge < 50;

boolean eitherOfUsIsYoungerThan50 = 
            myAge < 50 || dadsAge < 50;

Notice that a single statement can span multiple lines :) As long as you have the semicolon at the end, all is well.

comments powered by Disqus