Get up to 80 % extra points for free! More info:

Lesson 3 - Variables, type system and parsing in Java

Lesson highlights

Are you looking for a quick reference on Java variables, type system and parsing instead of a thorough-full lesson? Here it is:

Creating an int variable (for whole numbers) and assigning a value 56 to it:

int a = 56;
System.out.println(a);

Reading text from the console using nextLine() on new Scanner() and concatenating strings with +:

Scanner scanner = new Scanner(System.in);
System.out.println("Write something: ");
String input = scanner.nextLine();
System.out.println("You wrote: " + input);

Reading numbers from the console using Integer.parseInt() to make a number from text:

Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number and I'll double it: ");
String s = scanner.nextLine();
int a = Integer.parseInt(s);
a = a * 2;
System.out.println(a);

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

In the previous lesson, NetBeans IDE and your first console application, we learned how to work with NetBeans, and created our first console application. In today's lesson, we're going to look at the so-called type system of Java. We'll introduce basic data types, and we'll work with variables. As a result, we'll create 4 simple programs, including a simple calculator.

Variables

Before we start with data types, let's make sure we understand what a variable is, if you're already familiar with programming, please excuse the short explanation. Surely, you remember variables from Math class (e.g. x), in which we could store some value, usually a number. A variable in IT is really the same thing. It's a place in computer memory where we can store some data, e.g. a username, the current time or a database of articles. This place has a certain reserved size, different variable types have different sizes, which the variable can't exceed, e.g. an integer number can't be greater than 2 147 483 647.

A variable is always of some sort of data type. It can be a number, a character, text, etc. It depends on what we want to use it for. Before working with a variable, we have to declare it first to specify how this variable will be called and of what data type it will be. The programming language will establish it in the memory, and be able to use it. Our computer knows, based on our declaration, how much memory the variable occupies and how to operate with that piece of memory.

Type system

There are two basic type systems: static and dynamic.

In the dynamic type system, we're fully relieved from the fact that the variable has some data type at all. Obviously, the variables have types internally, but the language doesn't show it. Dynamic typing often goes so far that we don't have to declare variables at all. If we store some data in a variable and the language finds out that this variable had never been declared, it'll just create it automatically. In the same variable, we are able to store text, user objects or decimal numbers. The language will automatically change the inner data type according to data we're assigning into the variable. Due to a smaller amount of code, the development is usually faster in those languages. The example languages with this kind of type system are e.g. PHP or Ruby.

On the other hand, we have the static type system. It requires us to declare the variable type, and this type is unchangeable from then on. Meaning that, if we try to store a user object into a String, we'll get yelled at by the compiler.

Java is a statically typed language. All variables must be declared as specific data types. The disadvantage to this is that due to the declarations a source code is a bit longer and it takes more time to write it. The great advantage is that before running, the compiler checks whether all data types match. The dynamic typing may look advantageous, but we can't automatically check the source code and if we expect a user object somewhere and we get a decimal number instead, the error will be revealed only during the run-time and the interpreter will stop the program. Java won't allow us to compile a program until it checks it for errors (this is yet another benefit to using compilers).

Let's make a sample program, so that you'll be able to apply this newly acquired knowledge. We'll continue with the theoretic part of it all next time. Here are three basic data types:

  • Numbers: int
  • Real numbers (10.12, ...): double
  • Texts: String

Variable printing program

We'll go ahead and declare an integer variable, name it a, store the number 56 in it, and print its value to the console. Create a new project and name it Output (we'll create a new project for each sample program). Don't forget to write the code inside the body of the main() method like we did last time, I won't copy the main() method here anymore.

int a;
a = 56;
System.out.println(a);

The first command declares a new variable, a, of the int data type. This variable will be used to store integers i.e. whole numbers. The second command assigns a value to the variable using the = operator we all know from math classes. The last command is already familiar to us. It prints the content of the variable a. The console is smart and knows how to print numeric values as well.

Console application
56

The same code for a real number variable would look like this:

double a;
a = 56.6;
System.out.println(a);

It's almost the same as the code for integer. The decimal separator will always be represented by a dot here. Even if your regional separator is a comma.

Parrot program

The previous program was a bit boring, let's try to respond to user input somehow. Let's write a program named Parrot. You can probably guess what it will do - it will repeat (twice) what the user has written. We haven't tried to read anything from the console yet. There is the nextLine() method that returns a String from the console. In order to be able to read texts from the console, we'll create a new project named Parrot, and modify the template to look as following:

package parrot;

import java.util.Scanner;

public class Parrot {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
    }
}

I've removed the gray comments to make changes more obvious, however, you can keep them. We've imported java.util.Scanner class which allows us to access methods for console input. Finally, there is a line at the very beginning of the main() method which creates a scanner object on which we can call the nextLine() method. It'd be way too complicated to explain objects at this moment, so for now, we'll just remember:

Whenever we want to read texts from the console, we add the import and create the scanner object at the beginning of the main() method first. Then we can use the scanner in the rest of our program, how many times we want.

We won't need any other objects in the basics course and we'll explain everything in details in the OOP course.

Now, let's move back into the source code and make the main() method contents look like this:

Scanner scanner = new Scanner(System.in);
System.out.println("Hi I'm Lora, the virtual parrot, and I love to repeat!");
System.out.println("Type something in: ");

String input;
input = scanner.nextLine();

String output;
output = input + ", " + input + "!";

System.out.println(output);

It's a little more fun, right? :) We've already explained the first line above. The other two lines are self-explanatory (they just print text). On the fourth line, we declare a String input. Input will contain the return value of the nextLine() method, i.e. whatever the user enters into the console. To make the code more understandable, we create another String variable for output. The interesting part of the code is when we assign the value to output, we do a string concatenation. We use the + operator to join several strings into one. As you can see, it doesn't matter whether it's a variable or it's an explicitly declared string in quotation marks in our source code. We assign the input to the variable, then a comma followed by a space, then input again and finally an exclamation mark. Then the program will display this variable and terminate.

Console application
Hi I'm Lora, the virtual parrot, and I love to repeat!
Say something:
Lora wants a cracker!
Lora wants a cracker!, Lora wants a cracker!!

We can assign values to variables right in their declaration, so we could replace:

String input;
input = scanner.nextLine();

with:

String input = scanner.nextLine();

We could shorten the program in many other ways, but generally, it's better to use more variables and focus on clarity and readability than altering the code until we forget what the program was even supposed to do.

Doubler program

The doubler program will retrieve an input number, double it and display the result. With the current knowledge we possess, we could write something like this:

Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number and I'll double it: ");
int a = scanner.nextLine();
a = a * 2;
System.out.println(a);

Java will report an error and highlight the line on which we tried to get the value from the console and store it into the int variable. We've just seen type checking in action, scanner.nextLine() returns a String, and we're trying to assign it to the int variable. We need to parse it first. Everything from the console is text, even if we enter a number.

Parsing

Parsing means converting from text to another specific type, e.g. numbers. Many data types in Java already have methods for parsing prepared. Since we want to parse an int from String, we'll write the following:

String s = "56";
int a = Integer.parseInt(s);

We call the parseInt() method on the Integer class, it takes a String parameter and returns a number. Let's apply this knowledge to our program:

Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number and I'll double it: ");
String s = scanner.nextLine();
int a = Integer.parseInt(s);
a = a * 2;
System.out.println(a);

The first thing we did was store the text from the console into the String s. Integer variable a will then, thanks to parsing, contain the numeric value of the String s. Then, we double the value of a and print it out to the console.

Console application
Enter a number and I'll double it:
1024
2048

Parsing can't be done if a word is used instead of a number in the text, but don't worry about these sort of scenarios for now.

There's also a nextInt() method on the scanner, which at first glance might seem to return an already parsed number and save us work. Unfortunately, this method leaves the Enter character in the input, when the user confirms their number with it. This character remains there until you read it from the console along with some other text, and might cause unexpected problems in your programs. Therefore, always use nextLine() to read from the console.

Simple calculator

Since we haven't worked with real numbers yet, let's program a simple calculator. It'll be very easy. The input will consist of two numbers, and the program will display the results of addition, subtraction, multiplication, and division.

Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to calculator!");
System.out.println("Enter first number:");
double a = Double.parseDouble(scanner.nextLine());
System.out.println("Enter second number:");
double b = Double.parseDouble(scanner.nextLine());
double sum = a + b;
double difference = a - b;
double product = a * b;
double quotient = a / b;
System.out.println("Addition: " + sum);
System.out.println("Subtraction: " + difference);
System.out.println("Multiplication: " + product);
System.out.println("Division: " + quotient);
System.out.println("Thank you for using calculator.");

Note: The decimal separator depends on your regional settings, for the English-speaking world it would be a dot.

Console application
Welcome to calculator!
Enter first number:
3.14
Enter second number:
2.72
Addition: 5.86
Subtraction: 0.42
Multiplication: 8.5408
Division: 1.15441176470588
Thank you for using calculator. Press any key to end the program.

First, we simplified parsing from the console, so we don't need a String variable (we wouldn't use it further anyway). Secondly, at the end of the program, we join a String with a number using the plus sign. Java will surprisingly not report an error, but it'll perform an implicit conversion from a number to a String (using the Integer.toString() method). If it wasn't this way or if we got into a situation where we needed to convert anything to String, we'd call the String.valueOf() method with the variable as a parameter. In this case, Java called it for us, it basically did this:

System.out.println("Addition:" + String.valueOf(sum));

Now we just did the opposite of parsing - conversion from anything to a String. In the next lesson, Solved tasks for Java lessons 1-3, we'll talk some more about type systems, and introduce you all to more data types.

All of the programs are available for download in the attachment below. You should definitely try to create some programs similar to these, seeing as how you already have the knowledge necessary to do so! :)

In the following exercise, Solved tasks for Java lessons 1-3, we're gonna practice our knowledge from previous lessons.


 

Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.

Download

By downloading the following file, you agree to the license terms

Downloaded 122x (65.92 kB)
Application includes source codes in language Java

 

Previous article
NetBeans IDE and your first console application
All articles in this section
Java Basic Constructs
Skip article
(not recommended)
Solved tasks for Java lessons 1-3
Article has been written for you by David Capka Hartinger
Avatar
User rating:
11 votes
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn university David learned IT at the Unicorn University - a prestigious college providing education on IT and economics.
Activities