# Lesson 4 - More on the Java type system: Data types

In the previous exercise, Solved tasks for Java lessons 1-3, we've practiced our knowledge from previous lessons.

Lesson highlights

Are you looking for a quick reference on Java data types instead of a thorough-full lesson? Here it is:

Creating variables of basic whole-number data types:

``````{JAVA_CONSOLE}
byte a = 15; // can store numbers from -128 to 127
short b = 10000; // -32 768 to 32 767
int c = 500000; // -2 147 483 648 to 2 147 483 647
long d = 1000000000; // -9 223 372 036 854 775 808 to 9 223 372 036 854 775 807

System.out.println(a + b); // We can use basic arithmetics
{/JAVA_CONSOLE}``````

Creating decimal variables:

``````{JAVA_CONSOLE}
float f = 3.141592f; // single precision
double d = 3.14159265358979; // double precision

System.out.println(f);
System.out.println(d);
{/JAVA_CONSOLE}``````

Declaring other built-in data types:

``````{JAVA_CONSOLE}
String s = "This text can be as long as we want";
char a = 'A'; // One character
boolean loveJava = true; // booleans are true or false

System.out.println(s);
System.out.println(a);
System.out.println(loveJava);
{/JAVA_CONSOLE}``````

Calling `String` methods (startsWith/en­dsWith/contain­s/toUpperCase/to­LowerCase/repla­ce):

``````{JAVA_CONSOLE}
String s = "Think twice, code once ";
System.out.println(s.startsWith("Think"));
System.out.println(s.endsWith("once"));
System.out.println(s.trim().endsWith("once"));
System.out.println(s.contains("TWICE"));
System.out.println(s.toUpperCase());
System.out.println(s.toLowerCase());
System.out.println(s.replace("Think", "Learn"));
System.out.printf("My favorite quote is: %s with %d characters", s, s.length());
{/JAVA_CONSOLE}``````

Would you like to learn more? A complete lesson on this topic follows.

In the previous lesson, Solved tasks for Java lessons 1-3, we learned basic data types of Java (`int`, `double` and `String`). In today's tutorial, we're going to look at them in more detail and explain how to use them correctly. Today is going to be more theoretical, and the next lesson will be very practical. At the end, we'll make a few simple examples.

Java recognizes two kinds of datatypes, primitive and reference.

### Primitive datatypes

We can easily imagine a variable of the primitive data type. It can be, for example, a number or a character. The value is stored directly in memory and can be accessed directly from the program. Note how I've used the word "directly" so many times. In the lessons throughout this course, we'll mainly be working with these variables.

#### Whole-number data types

Let's look at the table of all of the built-in whole-number data types in Java, notice the type `int`, which we already now.

Data type Range Size
byte -128 to 127 8 bits
short -32 768 to 32 767 16 bits
int -2 147 483 648 to 2 147 483 647 32 bits
long -9 223 372 036 854 775 808 to 9 223 372 036 854 775 807 64 bits

By now, you might be thinking - why do we have so many data types for storing numbers? The answer is simple, it depends on their size. If the number is large, it consumes more memory. For user's age, we should select `byte` since nobody can live more than 127 years. Imagine a database with millions of users of some informational system. If we choose `int` instead of `byte`, it'll occupy 4 times more space. Conversely, if we have a function that calculates a factorial, the range of `int` will not be enough for us and we'll have to use `long`.

We don't have to think hard about choosing data types, we'll use `int` almost every time. You should think about it only in case the variables are in some array or collection in general, and there are a lot of them. In that case, it's worth it to consider memory requirements. The tables I gave here are mainly for the sake of completeness. The already-mentioned implicit conversion also works between the types, so we can assign some `int` to a `long` variable directly, without having to convert it.

#### Decimal numbers

For decimal numbers, the choice is simpler, we can only choose between two data types. They differ in the range of values, and also in precision, i.e. in the number of decimal places. The datatype `double` is twice as precise as `float`, which you probably deduced from its name.

Data type Range Precision
float +-1.5 * 10−45 to +-3.4 * 1038 7 numbers
double +-5.0 * 10−324 to +-1.7 * 10308 15-16 number

Beware, due to the fact that decimal numbers are stored in your computer in a binary system, there is some precision loss. Although the deviation is almost negligible, if you're programming, e.g. a financial system, don't use these data types for storing money since it could lead to slight deviations.

When we want to assign a value to a `float` variable in source code, we have to use the `F` suffix. With double, we may use the `D` suffix, but it can be omitted since double is the default decimal type:

```float f = 3.14F;
double d = 2.72;```

As the decimal separator in source code, we use dots, regardless of our OS regional settings.

#### Other built-in data types

Let's look at the other data types that Java offers:

Data type Range Size/Precision
char U+0000 to U+ffff 16 bits
boolean true or false 8 bits
##### `Char`

`Char` represents one character, unlike `String`, which represents the entire string of chars. We declare characters with apostrophes in Java:

`char c = 'A';`

A single, non-array, `char` actually belongs in the list of whole-number variables. It contains a numeric character code, but it seemed more logical for me to introduce it here.

##### `BigDecimal`

The `BigDecimal` data type solves the problem of storing decimal numbers in binary form, the number is stored internally similarly as text. It is used for storing monetary values. For all other mathematical operations with decimal numbers, we use double or float. We won't show how to use BigDecimal now since it's an object. However, if you will ever need to perform some monetary calculations, you'll know what to look up.

Note.: In Java, all the number classes are inherited from the `Number` class. This is rather an information for the future. Since we don't know what inheritance is right now, it's not important. The `Number` class has another 4 subclasses which we'll not discuss in details now either. However, let's just mention `BigDecimal` and `BigInteger` are for high accuracy calculations. The `AtomicInteger` and `AtomicLong` classes are used in applications with multiple processes. Again, it's important for you to just know that some classes like this exist so you'd be able to look them up if you happen to need them in future.

##### `Boolean`

Variables of the `boolean` type can contain only two values: `true` or `false`. We'll use them when we get to conditions. In a variable of the `boolean` type, we can store either `true`/`false` or a logical expression. Let's try a simple example:

``````{JAVA_CONSOLE}
boolean b = false;
boolean expression = (15 > 5);
System.out.println(b);
System.out.println(expression);
{/JAVA_CONSOLE}``````

The program output:

```Console application
false
true```

We write expressions in parentheses. Notice that the expression applies, is equal to `true` since `15` really is more than `5`. Going from expressions to conditions isn't a far stretch, but we'll go into them in the next lesson.

## Reference data types

We'll get to reference data types, but not until we get to object-oriented programming, where we'll also explain basic differences. For now, we'll work with simple types, with differences that we won't be able to see. Let's just say that reference types are more complex than primitive types. One such type is already known to us, it's a `String`. You might think how come that `String` doesn't have a length limit. It is due to differences in work with reference data types in memory. Reference types starts with an uppercase letter unlike the primitive ones.

`String` provides a wide range of truly useful methods. We'll show some of them and try them out:

#### `String`

##### `StartsWith()`, `endsWith()` and `contains()`

We can ask if a string starts with, ends with or contains a substring. A substring is a part of a string. All of these methods will take a substring as a parameter and return `boolean` (`true`/`false`). We can't react to the output yet; however, let's write the return values nonetheless:

``````{JAVA_CONSOLE}
String s = "Rhinopotamus";
System.out.println(s.startsWith("rhin"));
System.out.println(s.endsWith("tamus"));
System.out.println(s.contains("pot"));
System.out.println(s.contains("lol"));
{/JAVA_CONSOLE}``````

The program output:

```Console application
false
true
true
false```

We can see that everything works as expected. The first phrase failed, as expected, because the string actually starts with a capital letter.

##### `ToUpperCase()` and `toLowerCase()`

Distinguishing between capital and lowercase letters is not always what we want. We'll often need to ask about the presence of a substring in a case-insensitive way. The situation can be solved using the `toUpperCase()` and `toLowerCase()` methods which return the string in uppercase, resp. lowercase. Let's make a more realistic example than Rhinopotamus. The variable will contain a line from some configuration file, which was written by the user. Since we can't rely on the user's input we'll try to eliminate possible errors, here by ignoring letter cases.

``````{JAVA_CONSOLE}
String config = "Fullscreen shaDows autosave";
config = config.toLowerCase();
System.out.println("Will the game run in fullscreen?");
System.out.println(config.contains("fullscreen"));
System.out.println("Will sound be turned off?");
System.out.println(config.contains("nosound"));
System.out.println("Would the player like to use autosave?");
System.out.println(config.contains("autosave"));
{/JAVA_CONSOLE}``````

The program output:

```Console application
Will the game run in fullscreen?
true
true
Will sound be turned off?
false
Would the player like to use autosave?
true```

We can see that we're able to detect the presence of particular words in a string. First, we convert the entire string to lowercase or uppercase, and then check the presence of the word in lowercase or uppercase, respectively. By the way, simple processing of configuration script may actually look like this.

##### `Trim()`

Another pitfall can be whitespace characters, which are not visible for users, but can cause program errors. Generally, it's a good idea to trim any input from the user. Try to enter some spaces before the number and after the number in the following application, `trim()` will remove them. It removes white characters only around the string, not inside:

``````{JAVA_CONSOLE}
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number:");
String s = scanner.nextLine();
System.out.println("Here's what you originally wrote: " + s);
System.out.println("Your text after the trim function: " + s.trim());
int a = Integer.parseInt(s.trim());
System.out.println("I converted the text you entered to a number. Here it is: " + a);
{/JAVA_CONSOLE}``````
##### `Replace()`

Probably the most important method on `String` is a replacement of its parts with another text. We enter two substrings as parameters, the first one is the one want to be replaced and the second one will replace it. The method returns a new `String` in which the replacing occurred. When the method doesn't find the substring, it returns the original string. Let's try:

``````{JAVA_CONSOLE}
String s = "C# is the best!";
s = s.replace("C#", "Java");
System.out.println(s);
{/JAVA_CONSOLE}``````

We'll get:

```Console application
Java is the best!```
##### `Format()`

`Format()` is a very useful method that allows us to insert placeholders into a string. The placeholders are represented by a percent sign (`%`) and the data-type abbrev. The first parameter is the `string` containing those placeholders. Next method parameters will be the variables which are going to be placed in the text instead of these placeholders. Notice that the method is not called on the specific variable but right on a `String` type (to be completely accurate it's not called on the instance, see other courses).

``````{JAVA_CONSOLE}
int a = 10;
int b = 20;
int c = a + b;
String s = String.format("When we add up %d and %d, we get %d", a, b, c);
System.out.println(s);
{/JAVA_CONSOLE}``````

The program output:

```Console application
When we add up 10 and 20, we get 30```

We use:

• `%d` for integers
• `%s` for Strings
• `%f` for `doubles`/`floats`. We can also define the number of decimal places, e.g. like `%.2f` which rounds to `2` decimal places.

The console can receive a text in this format by itself, we just need to call `printf()` instead of `println()`:

``````{JAVA_CONSOLE}
int a = 10;
int b = 20;
int c = a + b;
System.out.printf("When we add up %d and %d, we get %d", a, b, c);
{/JAVA_CONSOLE}``````

This is a very useful and clear way to build a string, however, in Java, it's more common to use just the `+` operator.

##### `Length()`

Lastly, but most importantly we have `length()`. It returns an integer that represents the number of characters in the string.

``````{JAVA_CONSOLE}
Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();
System.out.println("Your name is " + name.length() + " characters long.");
{/JAVA_CONSOLE}``````

There's still a lot to go over and lots of other data types that we haven't covered. Regardless, there is a time for everything. In the next lesson, Solved tasks for Java lesson 4, we'll introduce conditions and then loops, then we'll have enough knowledge to create interesting programs In the following exercise, Solved tasks for Java lesson 4, we're gonna practice our knowledge from previous lessons.

Article has been written for you by David Capka
User rating: David learned IT at the Unicorn University - a prestigious college providing education on IT and economics.