Lesson 3 - Variables, type system and parsing in Java

Java Basic constructs Variables, type system and parsing in Java

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. integer number can't be bigger 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 it 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, our compiler checks whether all data types match. The dynamic typing may look advantageous, but we can't automatically check a 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 an 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 an example program, so that you'll be able to apply this newly acquired knowledge. We will 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, and name it: a, store the number 56 in it and print its content into 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 will print 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 is 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 use a process 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 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 is 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 it. 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, highlight the line in 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.

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 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, More on the Java type system: Data types, 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! :)


 

Download

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

 

  Activities (6)

Article has been written for you by David Capka
Avatar
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 College Author learned IT at the Unicorn College - prestigious college providing IT and economical education.

Do you like this article?
Nobody has rated this just yet, be the first one!


 



 

 

Comments

Avatar
Shaba Omokhagbo Samson:10. January 13:52

honestly speaking, I'm learning!!!!

 
Reply  +1 10. January 13:52
Avatar
Andrew Kakumba:6. February 16:23

Hi David, I've got a challenge running this script. I've named my project as "Output" and put exactly the same script as you stated it but still showing me an error. Refer to the attachment

package onlineapp;

import java.util.Scanner;

public class Program
{
public static void main(String[] args) {
int a;
a = 56;
System.out.prin­tln(a);
}
}

 
Reply 6. February 16:23
Avatar
Replies to Andrew Kakumba
Andrew Kakumba:6. February 17:27

Davie kindly ignore. I succeeded when I renamed "onlineapp" and "Program" with project name "output"

 
Reply  +1 6. February 17:27
Avatar
Andrew Kakumba:7. February 7:43

Hi David, still have a challenge with running this code below. I named the project as "Basic", I thought I'd replace "package" and "public class" with project name but all in vain. And also at the String output, where do I have to put space and where I shouldn't. Kindly help me on this mate

package onlineapp;

import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.prin­tln("Hi I am Rael, the virtual parrot, and I love to repeat!");
System.out.prin­tln("Let me fuck you:");

String input;
input = scanner.nextline();

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

System.out.prin­tln(output);

}
}

 
Reply 7. February 7:43
Avatar
David Capka
ICT.social team
Avatar
Replies to Andrew Kakumba
David Capka:7. February 13:06

Look at the red underlined parts, those are errors. You have to change the package name in the code to basic, the class name to Basic and there is an error in nextLine (L has to be uppercase).

 
Reply 7. February 13:06
To maintain quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it is free.

5 messages from 5 displayed.