Java Beginner: Lesson 2

Introductions to data types

In this lesson we will cover data types. Data types are devided into primitive and complex ones.
Primitive data types are:
  • boolean
  • byte
  • short
  • char
  • int
  • long
  • float
  • double


Complex data types are those data types for which you need to create a class in order to create instances of them, or you can use predefined classes, in the libraries for example, in order to create instances of this data types.
String for example is a comples data type. Returning to the project created in the previous lesson, the main method within HelloWorld class inside the HelloWorld.java file has a String paramenter in it as seen in the figure 1 bellow:

Figure 1: String parameter in the main method

If we keep pressed the CTRL button and we click on the "String" word the IDE will open for us the String.java file which contains the implementatin of String class as seen in the figure 2 bellow:

Figure 2: String.jav file containing the String class

If we put the mouse on the String.java tab in our IDE we will see the path of the class and the location of the zip file wich stores this class as seen in the figure 3.

Figure 3: Location of the String class

Without going any deeper on the complex types we are giving a practical exaple how to use int primitive data type. In the line 19 in the figure 4 bellow is declared the first variable which is of type int, as explained above, a primitive data type. In order to declare a variable of primitive data type, we need to put initialy the type of the variable we are declaring, in this case int, than comes the name of the variable, which in this case is nr1. This two keyword are enough to declare a variable of primitve data type, but as you may see from the figure 4 bellow, we have not ended the statment only with this two data types but we have added = 2; as well. The = 2 part makes the initialization of nr1 variable with the value 2, so we don't just declare the variable but we give a value to it as well. The ; character, as in many programming languages, indicates the end of a statment. In the same way we declare the nr2 variable, and we asign to it the value 3. In the line 21 in the figure 4 is declared the sum variable, this variable will contain the value of the sum of the variable nr1 and variable nr2. The execution of the statement starts from the right to the left, so initialy is calculated the sum of variable nr1 and nr2 and than this value is asigned to the sum variable.
The line 23 simply appends a string to the sum variable and prints it into the console.

Figure 4: Usage of primitive data types

This lesson gives a brief description of data types and variables in java. In the upcomming lessons we will go deeper in this topic.


(please report broken link in the comment)

Comments

Popular posts from this blog

Free host and domain

C++ Beginner: Lesson 3 - Simple calculator

C++ Beginner: Lesson 4 - Tic Tac Toe game