Welcome Guest   Login
This website is maintained for archive purpose. Website available for sale. Send your quote to reach at dkay.in
Jul 18, 2024
<?php include("../../config.inc.php"); $section="Tutorials - Java - Chapt 3"; include("../../title.inc.php"); ?>
Chapter 3
Data types Variables & Arrays

As with all modern programming languages, Java supports several types of data. You may use these types to declare variables and to create arrays.

It is important to state at the outset that Java is strongly typed language. Indeed, part of Java’s safety and robustness comes from this fact. Let’s see what this means. First, every variable has a type, every expression has a type, and every type is strictly defined. Second, all assignments, whether explicit or via parameter passing in method calls, are checked for type compatibility. there are no automatic coercion or conversion of conflicting types as in some languages. The Java compiler checks all expressions and parameters to ensure that the types are compatible. Any type mismatches are errors that must be corrected before the compiler will finish compiling the class.

The simple types

Java defines eight simple (or elemental ) types of data: byte, short, int, long, char, float, double, and boolean. These can be put in four groups.

  • Integers : This group includes byte, short, int, and long, which are for whole-valued signed numbers.
  • Floating-point numbers : This group includes float and double, which represents numbers with fractional precision.
  • Characters : This group includes char, which represents symbols in a character set, like letters and numbers.
  • Boolean : This group includes boolean, which is a special type for representing true/false values.
You can use these types as-is, or construct arrays or your own class types. Thus, they form the basis for all other types of data that you can create.

The language like C/C++ allow the size of an integer to vary based upon the operating system it is running on. However, Java is different. Because of Java’s portability requirement, all data types have a strickly defined range. For example, an int is always 32 bits, regardless of the particular platform. This allows programs to be written that are guaranteed to run without porting on any machine architecture.

Name Width Range
Byte 8 -128 to 127
Short 16 -32768 to 32,767
Int 32 -2,147,843,648 to 2,147,483,647
long 64 -9,223,375,036,854,775,808 to 9,223,372,036,854,775,807

Java defines four integer types byte, short, int, and long. All of these are signed, positive and negative values. Java does not support unsigned, positive-only integers.

Example 1
Class example1 {

public static void main(String args[]) 
byte b=10;
short s=200;
int i=-3000;
long l=53420;
System.out.println("byte b= "+b);
System.out.println("short s= "+s);
System.out.println("int i= "+i);
System.out.println("long l= "+l);

The above program creates all numeric type variables of Java by using byte, short, integer, long. It also assigns the values while declaration & all values are printed to screen.

Example 2
// compute distance light travels using long variables.

class Light {
public static void main(String args[]) {

int lightspeed;
long days;
long seconds;
long distance;

//approximate speed of light in miles per second

lightspeed = 86000;
days = 1000; // specify the number of days here
seconds = days * 24 * 60 * 60; // convert to seconds
distance = lightspeed * seconds; // compute distance

System.out.print("In "+days);
System.out.print(" days light will travel about ");
System.out.println(distance + " miles.");


The above program is creates the variables of given datatypes. This program performs some mathematical operations also like multiplying which is done using ‘ * ’operator. Another thing in this program is it is that instead of using println() method it makes use of print() method which means print to screen without advancing to new line.

This program generates the following output :

In 1000 days light will travel about 7430400000000 miles.

Floating-Point Types
Name Width in bits Range
double  64 1.7e-308 to 1.7e+308
float 32 3.4e-038 to 3.4e+038


Floating-point numbers, also known as real numbers, are used when evaluating expressions that require fractional precision. For example, calculations such as square root, or transcendentals such as sine and cosine, results in a value whose precision requires a floating-point type.

Example 3
// compute the area of a circle

class Area {

public static void main(String args[]) {
double pi, r, a;

r = 10.8; // radius of circle
pi = 3.1416; // pi, approximately
a = pi * r * r; // compute area of circle;

System.out.println("Area of circle is " + a);


This program calculates area of circle as per the formula P r 2 .


In Java, the data type used to store characters is char. In Java char is a 16-bit type. The range of a char is 0 to 65536. There are no negative chars. The standard set of characters known as ASCII still ranges from 0 to 127 as always.

Example 4
// Demonstrate char data type.

class CharDemo {
public static void main(String args[]) {

char ch1,ch2;
ch1 = 88; // ASCII code for 'X'
ch2 = 'Y';

System.out.print("ch1 and ch2 : ");
System.out.println(ch1 + " " + ch2);





Java has a simple type, called boolean, for logical values. It can have only one of two possible values, true or false. This is the type returned by all relational operators, such as a < b. boolean is also the type required by the conditional expressions that govern the control statements such as if and for.

Example 5
class BoolTest {
public static void main(String args[]) {
boolean b;
System.out.println("b is "+b);

System.out.println("b holds true value");
System.out.println("b holds false value");



This program creates a boolean variable and assigns false to it, which is printed to screen and checked through if statement and appropriate message is displayed depending upon the value assigned.

Example 6
class BoolMore {

public static void main(String args[]) {
boolean b;

b = ( 6 > 7 );
System.out.println("b = ( 6 > 7 ) : b is "+b);


This program creates boolean datatype variables and checks for expression ( 6 > 7) and false is returned is assigned to variable b.


A constant value in Java is created by using a literal representation of it. This value can either assigned to variable or compared with variable. Following is the table of literals for different datatypes.
Datatype Literal
Integer Literal whole numbers like 1,2,3
  Octals from 0 to 7
  Hexadecimal like 0x22 or 0xA2
Floating point Literal 2.0 0.66667
  Scientific 314159E-05
Boolean Literal true, false
Character Literals ‘a’, ‘V’, ‘z’, ‘\n’
String Literals "Hello World"
  "two \n Lines"


Character Literals
Escape Sequence Description
\’ Single quote
\" Double quote
\\ Backslash
\r Carriage return
\n New Line
\t Tab
\b Backspace



The variable is the basic unit of storage in a Java program. A variable is defined by the combination of an identifier, a type, and an optional initializer. In addition, All variables have a scope, which defines their visibility, and a lifetime.

Declaring a Variable

In Java, all variables must be declared before they can be used. The basic form of a variable declaration is shown here.

type identifier [ = value ] [, identifier [ = value ]..]

The type is one of Java’s atomic types, or the name of a class or interface. The identifier is the name of the variable. You can initialise the variable by specifying an equal sign and a value. To declare more than one variable of the specified type, use a comma-separated list.

Example of initialization:

int a, b, c;

int d = 3, e, f = 5;

byte z = 22;

double pi = 3.14159;

char x = ‘a’;

boolean ans = true;

Dynamic initialisation

Java allows variables to be initialised dynamically, using any expression valid at the same time the variable is declared.


double a = 3.0,b = 4.0;

double c = Math.sqrt(a * a + b * b);

The Scope and Lifetime of Variables

Java allows variables to be declared within any block. A block is begun with an opening curly brace and ended by a closing curly brace. A block defines scope. Thus, each time you start a new block, you are creating a new scope. A scope determines what objects are visible to other parts of your program. It also determines the lifetime of those objects.

In Java, the two major scopes are those defined by a class and those defined by a method. Even this distinction is somewhat artificial. However, since the class scope has several unique properties and attributes that do not apply to scope defined by method, this distinction makes some sense.

The scope defined by a method begins with its opening curly brace. However, if that method has parameters, they too are included within the method’s scope. Although discussion, they work the same as any other method variable.

Variables declared inside a scope are not visible ( that is, accessible ) to code that is defined outside that scope. Thus, when you declare a variable within a scope, you are localising that variable and protecting from unauthorised access and /or modification. Indeed, the scope rules provide the foundation for encapsulation.
class Scope {
public static void main(String args[] ) {
int x;
x = 10;

if(x==10) {
int y=20; // y declared in new block
System.out.println("x and y : " + x + " "+ y);
x = y * 2;

// y = 100; // Error! y not known here
System.out.println("x is "+x); // x is still known here


In this program, the variable x is declared at the start of main()’s scope and is accessible to all subsequent code withing main(). Within if block, y is declared so its visible within this block only not outside the block. Line y = 100 is commented if the comments are removed, a compile time error will occur.

Here is another important point to remember. Variables are created when their scope is entered, and destroyed when their scope is left. This means that a variable will not hold its value once it has gone out of scope. Therefore, variables declared within a method will not hold their values between calls to that method. Also, a variable declared within a block will lose its values when the block is left. Thus, the lifetime of a variable is confined to its scope.

Type Conversion and Casting

It happens so many times that you assign the value of one variable to another variable. If the two types are compatible, then Java will perform the conversion automatically. For example, it is always possible to assign an it value to a long variable. However, not all types are compatible, and thus, not all type conversion are implicitly allowed. For instance, there is no conversion defined from double to byte. Fortunately, it is still possible to performs an explicit conversion between incompatible types.

Java’s Automatic Conversion

When one type of data is assigned to another type of variable, an automatic type conversion will take place if the following two conditions are met:

  • The two types are compatible
  • The destination type is larger than the source types.

int ivar=30;

long lvar;

lvar = ivar;

Casting Incompatible Types

Although the automatic type conversions are helpful, they will not fulfill all needs. For example, what if you want to asign an int value to a byte variable ? This conversion will not be performed automatically, because a byte is smaller than an int.

To create a conversion between two incompatible types, you must use a cast. A cast is simply an explicit type conversion, It has this general form:


int ivar=30;

byte bvar = (byte) ivar;


An array is a group of like-typed variables that are referred to by a common name. Arrays of any type can be created and may have one or more dimensions. A specific Array element in an array is accessed by its index. Arrays offer a convenient means of grouping related information.

One-Dimension Arrays

A one-dimension array is, essentially, a list of like-typed variables. To create an array, you first must create an array variable of the desired type.The general form of a one-dimensional array declaration is

type var-name[ ];

Here, type declares the base type of the array. The base type determines the data type of each element that comprises the array. Thus, the base type for the array determines what type of data the array will hold. For example, the following declares an array named month_days "array of int":

int month_days[ ];

Although this declaration estabilishes the fact that month_days is an array variable, no array actually exists. In fact, the varlue of month_days is set to null, which represents an array with no value. To link month_days with an actual, physical array of integers, you must allocate one using new and assign it to month_days. new is a special operator that allocates memory.

aray-var = new type[size];

Here, type specifies the type of data being allocated, size specifies the numbers of elements in the array, and array-var is the array variable that is linked to the array. That is, to use new to allocate the array, you must specify the type and number of elements to allocate. The elements in the array allocated by new will automatically be initialised to zero. This example allocates a 12-element array of integers and links them to month_days.

month_days = new int[12];

The statement bellow assign the value 32 to the second element of month_days.


When you run this next program, it prints the number of days in April. As mentioned, Java array indexes start with zero, so the number of days in April is month_days[3] or 30.
Class Array {
public static void main(String args[]) {
int month_days[]= new int[12];

System.out.println("April has "+month_days[3] + " days");



Following code creates an initialised array of integers:
class AdvArray {
public static void main(String args[]) {

int month_days[] = { 31,28,31,30,31,31,30,31,30,31};
System.out.println("April has " + month_days[3] + " days.");



Multidimensional Array

In Java, multidimentional arrays are actually arrays of arrays. These, as you might expect, look and act like regular multidimensional arrays. However, as you will see, there are a couple of subtle differences. To declare a multidimenstional array variable, specify each additional index using another set of square brackets. For example the following declares a two-dimensional array variable called td.

int td[ ] [ ] = new int [4] [5];

This allocates a 4 by 5 array and assigns it to td. Internally this matrix is implemented as array of arrays of int. conceptually, this array will look like the one shown bellow.

Right index determines column


Left index



The following program number each element in the array from left to right, top to bottom and then display these values:
class TwoDArray {
public static void main(String args[]) {
int twoD[][] = new int[4][5];
int i,j,k = 0;
for(j=0;j<5;j++) {
twoD[i][j] = k;

for(i=0;i<4;i++) {
System.out.print(twoD[i][j] + " ");


This program generates the following output :

0 1 2 3 4

5 6 7 8 9

10 11 12 13 14

15 16 17 18 19

My New Blog

My Award winning Whitepaper

Contradicting Light
My Personal Blog

Trace Mobile Location

My Book Reviews

Tech Jokes Worth Reading
www.deepjava.com 1999-2024 (C) Developed and maintained by D-Kay Consultancy