Java Data Type
Four important aspects of any language are the way it stores data, the way it operates upon this data, how it accomplishes input and output, and how it lets you control the sequence of execution of instructions in a program. We would discuss the first three of these building blocks in this chapter
Java Data Types
Before we even write our first Java program, it is important to understand how data is represented in Java. This is done using a data type. A data type specifies two things:
(a) What value can the data type take?
(b) What operations can be performed on the data type?
For example, an integer data type can take values in the range -2147483648 to +2147483647, and operations like addition, subtraction, multiplication, division, etc., can be performed on it. Similarly, a boolean data type can take a value true or false, and permits comparison operations on it.
Based on where a data type can be created in memory, it is called a primitive type (often also known as a value type) or a reference type.
Java forces primitive data types to get created only in stack and reference types only on heap. For example, an integer (like say, 2341) always gets created in stack, whereas a string (like say “Quest”) always gets created in heap. The guiding principle on which Java does this decision making is—all data types that are small in size are created in stack, and all those that occupy bigger memory chunks are created in heap.
A primitive type as well as a reference type can be further categorized into predefined and user-defined categories. Here pre-defined means the data types that Java provides are ready-made, whereas, user-defined means the one that a common user like us can create. For example, integer is a pre-defined primitive data type, whereas an Enumeration is a user-defined value type. Below figure shows the different categories of data types available in Java. Note that the pre-defined value types are often also called Primitives.
Amongst all the data types shown in Figure, to begin with, we would concentrate on the pre-defined value data types. To use the data types in a Java program we have to create constants and variables. A constant is nothing but a specific value from the range of values offered by a data type, whereas a variable is a container which can hold a constant value. The container is typically a memory location and the variable is the name given to the location in memory. For example, if we use an expression x = 5, then the constant value 5 would be stored in a memory location and a name x would be given to that location. Whenever we wish to retrieve and use 5, we just have to use the variable name x.
As the name suggests, a constant’s value cannot change (fixed), whereas a variable’s value can change (vary). A constant is often called a literal, whereas a variable is also known as an identifier.
There are certain rules that one needs to observe while creating constants and variables. These are discussed below.
Rules for Constructing Constants
(a) If no sign precedes a numeric constant, it is assumed to be positive.
(b) No commas or blanks are allowed within a constant.
(c) The bytes occupied by each constant are fixed and do not change from one compiler to another.
(d) Only a float constant can contain a decimal point.
(e) A float constant must be followed by a suffix f.
(f) A float constant can be expressed in fractional from (example 314.56f) or exponential form (example 3.1456e2).
(g) A character constant is a single alphabet, a single digit or a single special symbol enclosed within single inverted commas. Both the inverted commas should point to the left. For example, ’A’ is a valid character constant, whereas ‘A’ is not.
Rules for Constructing Variable Names
(a) A variable name is any combination of alphabets, digits, underscored ( _ ) and dollars ( $ ).
(b) The first character in the variable name must be an alphabet, underscore or dollar.
(c) No commas or blanks are allowed within a variable name.
(d) Variable names are case-sensitive. So, abc, ABC, Abc, aBc, AbC are treated as different variables.
While creating variable names conventions given below are commonly followed.
(a) A variable name usually begins with an alphabet. Ex. speed, average
(b) A variable representing money usually begins with $. Ex. $interest, $salary.
(c) If a variable name containing multiple words the words are either connected using underscore or follow a camel-case notation. Ex. current_speed, currentSpeed, avg_salary, avgSalary.
While following these rules and conventions one must avoid the temptation of creating long variable names, as it unnecessarily adds to the typing effort.
The rules remain the same for constructing variables of any type. Naturally, the question follows—how is Java able to differentiate between these variables? This is a rather simple matter. Java compiler makes it compulsory for us to declare the type of any variable name that we wish to use in a program. Here are a few examples showing how this is done.
Ex.: int si, m_hra ;
float bassal ;
char code ;
Since, there is no limit on maximum allowable length of a variable name, an enormous number of variable names can be constructed using the above-mentioned rules. It is a good practice to exploit this enormous choice in naming variables by using meaningful variable names.
Thus, if we want to calculate simple interest, it is always advisable to construct meaningful variable names like prin, roi, noy to represent Principal, Rate of interest and Number of years rather than using the variables a, b, c.
Java Keywords
Keywords are the words whose meaning has already been explained to the Java compiler. When we make the declaration
int age ;
age is a variable, whereas int is a keyword. When this declaration is made, we are telling the compiler that the variable age be treated as a variable of type integer. But we don’t have to be so elaborate, just int age conveys the same meaning. This is because the meaning of the keyword int has already been explained to the Java compiler.
The keywords cannot be used as variable names because if we do so, we are trying to assign a new meaning to the keyword, which is not allowed. There are only 48 keywords available in Java. Figure 2.4 gives a list of these keywords for your ready reference. A detailed discussion of each of these keywords would be taken up in later chapters wherever their use is relevant.
The First Java Program
Armed with the knowledge of variables, constants and keywords, the next logical step is to combine them to form instructions. However, instead of this, we would write our first Java program now. Once we have done that we would see in detail the instructions that it made use of.
Before we begin with our first Java program, remember the following rules that are applicable to all Java programs:
(a) Each instruction in a Java program is written as a separate statement. Therefore, a complete Java program would comprise a series of statements.
(b) Blank spaces may be inserted between two words to improve the readability of the statement. However, no blank spaces are allowed within a variable, constant or keyword.
(c) All statements are in small case letters.
(d) Every Java statement must end with a semicolon ( ; ).
Let us now write our first Java program. It would simply calculate simple interest for a set of values representing principal, number of years and rate of interest.
// Calculation of simple interest
package calofsi ;
public class CalOfSi
{
public static void main ( String[ ] args )
{
float p, r, si ;
int n ;
p = 1000.50f ;
n = 3 ;
r = 15.5f ;
si = p * n * r / 100 ;
System.out.println ( si ) ;
}
}
Now a few useful tips about the program…
- Comments about the program should either be enclosed within /* */ or be preceded by //. For example, the first statement in our program is a comment.
- Though comments are not necessary, it is a good practice to begin a program with a comment indicating the purpose of the program, its author and the date on which the program was written.
- Sometimes it is not very obvious as to what a particular statement in a program accomplishes. At such times it is worthwhile mentioning the purpose of the statement (or a set of statements) using a comment. For example
/* formula for simple interest */
si = p * n * r / 100 ;
- A comment can be split over more than one line, as in,
/* This is
a multi-line
comment */
Such a comment is often called a multi-line comment.
- A Java program is a collection of one or more packages. Each package can contain multiple classes. Each class may contain multiple functions. Each function can contain multiple instructions. This typical organization of a Java program is shown in Figure
- Every instruction used in a Java program should belong to a function. Every function must belong to a class and every class must belong to a package. In our program there is a package called calofsi, a class called CalOfSi and a function called main( ). package and class both are keywords.
Right now we do not want to go into the details of the package and the class. We would learn about packages and classes in later chapters. But it would be a good time to get introduced to the concept of a function.
- main( ) is a function. A function contains a set of statements. Though a Java program can contain multiple functions, to begin with, we would concentrate on only those programs which have only one function. All statements that belong to main( ) are enclosed within a pair of braces { } as shown below.
public static void main ( String[ ] args )
{
statement 1 ;
statement 2 ;
statement 3 ;
}
- The way functions in a calculator return a value, similarly, functions in Java also return a value. Since we do not wish to return any value from main( ) function we have to specify this using the keyword void before main( ). main( ) is always preceded by the keyword static. The purpose of this keyword and detailed working of functions would be discussed in Chapters 9 and 7 respectively.
- Any variable used in the program must be declared before using it.
For example,
int p, n ; /* declaration */
float r, si ; /* declaration */
si = p * n * r / 100 ; /* usage */
- Any Java statement always ends with a semicolon ( ; ).
For example,
float r, si ;
r = 15.5f ;
- In the statement, si = p * n * r / 100 ;
* and / are the arithmetic operators. The arithmetic operators available in Java are +, -, * and /. Java is very rich in operators. There are totally 41 operators available in Java.
- Once the value of si is calculated it needs to be displayed on the screen. Unlike other languages, Java does not contain any instruction to display output on the screen. All output to screen is achieved using ready-made library functions. One such function is println( ). We have used it to display the value contained in si on the screen.
- Actually speaking println( ) is a function of PrintStream class, and out is a static object defined in a System class. We would learn classes, objects and static members in Chapter 8. As of now, let us just use the syntax System.out.println( ) whenever we wish to display output on the screen.
- If we wish, we can print multiple values using println( ) function.
This is shown below.
System.out.println ( si + ” ” + p + ” ” + n + ” ” + r ) ;
System.out.println ( “Simple interest = Rs. ” + si ) ;
System.out.println ( “Principal = ” + p + ” Rate = ” + r ) ;
The output of these statements would look like this…
465.2325 1000.5 3 15.5
Simple interest = Rs. 465.2325
Principal = 1000.5 Rate = 15.5
Compilation and Execution
We need to carry out the following steps to create, compile and execute our first Java program. It is assumed that you have installed JDK and NetBeans as per the instructions in Chapter 1.
(a) Start NetBeans from Start | All Programs.
(b) Select File | New Project from the File menu. Select ‘Java’ from the ‘Categories’ list box and ‘Java Application’ from ‘Projects’ box. Click on the ‘Next’ button.
(c) Give a proper name for the project in the ‘Project Name’ text box (say CalOfSi). Choose a suitable location for the project folder, then click on Finish.
(d) NetBeans would provide a skeleton program that would contain a package statement, a public class CalOfSi and a function main( ), all defined in a file called CalOfSi.java. Note that the name of the file and the name of the public class are the same in all Java programs.
(e) Type the statements of our simple interest program in main( ).
(f) Save the program using Ctrl+S. (g) Compile and execute the program using F6.
One More Program
We now know how to write an elementary Java program, type it, compile it and execute it. These are the steps that you will have to carry out for every program. So to help you fix your ideas, here is one more program. It calculates and prints the average value of 3 numbers.
/* Calculation of average */
package calofavg ;
public class CalOfAvg
{
public static void main ( String[ ] args )
{
int x, y, z, avg ;
x = 73 ;
y = 70 ;
z = 65 ;
avg = ( x + y + z ) / 3 ;
System.out.println ( avg ) ;
}
}