Java With Us
Home   |   Tutorial   |   Programs  

Java Tutorial

Introduction to Java
Hello World Program
Variables and Data types
More about data types
Displaying text using print and println
Displaying text using printf
Java Comments
Naming conventions for Identifiers
Mathematical operations in Java
Taking input from the user

Classes and Objects
Introduction to object oriented programming
The constituents of a Class
Creating objects and calling methods
Get and Set Methods
Default constructor provided by the compiler
Access Specfiers
Scope and lifetime of Variables
Call by value and Call by Reference

A few more topics
Class as a reference data type
Constants or literals
Final variables
Increment and decrement operators
Manipulating Strings
Overloading constructors and methods
Static methods and variables
The Java API
The Math class
this keyword
Wrapper classes

Control Structures
Control Statements
Repetition statements
Nested loops
Formulating algorithms
Branching Statements

Arrays introduction
Processing arrays using 1oops
Searching and sorting arrays
Array of objects
Multi dimensional arrays
Taking input as command line arguments
Using ellipsis to accept variable number of arguments

Inheritance introduction
Relation between a super class and sub class
Final classes and methods
The protected access specifier
Class Object

Abstract classes and methods

Exception handling
Exception handling introduction
Exception hierarchy
Nested try catch blocks
Throwing exceptions

Variables and Data Types

Programs are often required to store information. For example, to write a program that adds two numbers, we need to store the first number, the second number and the result. This is accomplished by the use of variables. Variables represent memory area where the information is stored. Following is the physical representation of a variable:

A variable has a name, a value and a data type. A variable name is a symbolic representation of the memory area in which the information would be stored. The value is the actual data that is going to be stored. And a particular variable can only store one type of information. It could either be an integer, a real number, a single character or a String. This is specified by the data type.

In our example, we have a variable named firstNumber of type int and having a value 3. The data type int is used to store integer values i.e. positive numbers, zero or negative numbers.

In java we have primitive and reference data types. Primitive data types are the basic data types which are not composed of any other data types while reference data types are those which are composed of other data types. Reference data types may be classes or arrays. We have already seen what a class is. We shall see later on how to create object from these classes and assign their reference to a variable. Arrays are used to store groups of data all of which have the same data type. We shall see more about arrays in a dedicated chapter later on. The term reference also has the implication of being passed by reference, which too which be looked at in a later chapter.

For now, we will learn about the primitive data types. Java has eight primitive data types, each of which is capable of storing a particular kind of information. In addition, each of them also has a range of values which can be stored. Values outside this range cannot be stored in a variable of that particular data type. The different data types, the amount of memory required by them and the range of values which can be stored are specified in the table below.

Data type Size in bits Range (inclusive of both values) Range ( in exponential notation)
byte 8 - 128 to 127 - 27 to 27-1
short 16 - 32 768 to 32 767 - 215 to 215 -1
int 32 - 2 147 483 648 to 2 147 483 647 - 231 to 231 -1
long 64 - 9 223 372 036 854 775 808 to 9 223 372 036 854 775 807 - 263 to 263 -1
float 32   -3.4*10-38 to 3.4*1038
double 64   -1.7*10-308 to 1.7*10308
char 16 0 to 65536  
boolean Not properly defined true and false  

We generally use the int data type for storing integers, the double data type for storing real numbers which have a decimal or a fractional part, the boolean data type is used if the stored values can be either true or false, yes or no, 0 or 1 and other similar pairs and finally the char data type is used to store a single character.

Declaring, initialization and assignment

Before we use a variable in a program, it needs to be declared by specifying the data type and name. Then, we may give a value to its which is known as initialisation. When we give a value to it the subsequent time after the first time, it is known as assignment. Initialisation and assignment are similar except that initialisation is done the first time and assignment the subsequent time. Both of them have the same syntax.

Following is the syntax for declaring a variable:

< Data type > < variable name >;

And a variable is either initialized or assigned in the following way:

< Variable name > = < value >;

We may combine the declaration and initialisation of a variable in the following way:

< Data type > < variable name > = < value >;

Now, going back to our example of adding two numbers, we need three variables- the first two to store the two numbers that are to be added and the third to store the result. Let us name these variables as firstNumber, secondNumber and result. Variable names should follow the rules of identifiers. The following statements declare these three variables.

int firstNumber;
int secondNumber;
int result;

When we declare more than one variable of the same type, the declarations can be combined into a single statement separating the variable names using a comma as shown below.

int firstNumber, secondNumber, result;

And the next thing to be done is to initialise these variables. Let us initialise the numbers to 3 and 4. The following statement initialises firstNumber with 3.

firstNumber = 3;

The equal to sign ( = ) is known as the assignment operator. It assigns the value on the right to a variable on the left. In this case, the value on the right, 3 is assigned to the variable firstNumber which is stated on the left. The right hand side can also be an expression. We will look at expressions shortly when dealing with the variable result. Now, the variable secondNumber is initialised in the following way.

secondNumber = 4;

As already said, declaration and initialisation may be combined in the following way.

int firstNumber = 3; int secondNumber = 4;

Further, we may combine the declaration and initialisation of these three variables into a single statement as all the three variables have the same data type.

int firstNumber = 3 , secondNumber = 4 , result;

It is to be noted that a variable cannot be declared more than once. If done so, a compilation error would occur. Also, a variable can't be initialised without first declaring it.

Next, we need to assign the sum of the two numbers to the variable result. Here again, we assign the result in the same way as we have done for the two numbers. But here, we do not assign a number such as 3 or 4 but instead we add the two numbers. This results in an expression. An expression is a combination of operators and operands. Operators are of different types but for now, we shall be concerned about the mathematical operators +, -, * , / and %. These have the same meaning as in mathematics. The last operator % is known as the modulus operator which is used to find the remainder when dividing two numbers. So, the statement for assigning a value to result would like

result = firstNumber + secondNumber ;

This initialisation could be combined with variable declaration in the following way.

int result = firstNumber + secondNumber ;

We could have done this assignment along with the assignment for firstNumber and secondNumber in the following way but this isn't recommended.

int firstNumber = 3 , secondNumber = 4 , result= firstNumber + secondNumber;

It is always suggested that direct initialisation of variables be separated from the ones where computation is required. And further, list all variables be listed on separate lines and not grouped as shown above. Though either of the two ways is correct, we should try to make the code more readable.

Lastly we need to print the result. For this, we use the println() statement in the following way.

System.out.println ( "The result of adding "+ firstNumber + " and "+ secondNumber + " is "+ result );

Here, the plus sign acts as a concatenation operator. Concatenation refers to joining two things. Here, we have joined different Strings and the variables. Wherever, the variable name appears, it is substituted by its value. So firstNumber would be replaced with 3, secondNumber by 4 and result by 7. Therefore, the following statement would be printed on the screen.

The result of adding 3 and 4 is 7

Now, here is the final program for addition.

public class Addition {

   public static void main (String args[] ) {
      int firstNumber = 3;
      int secondNumber = 4;
      int result = firstNumber + secondNumber ;
      System.out.println ( "The result of adding "+ firstNumber + " and "+ secondNumber + " is "+ result );

Privacy Policy