DATA TYPES AND VARIABLES
Java A Typed Language:
It is important to state at the outset that Java is
a 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 i method calls, are
checked for type compatibility. There are no automatic coercions or conversions
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.
asic Data Type:
Primitive Types:
The Java programming language defines literal
values for eight primitive data types and one special type. The primitive types
can be considered in four categories:
- Logical boolean
- Textual char, String
- Integral byte, short, int and
long
- Floating point double and
float
Integer: Java defines four integer types:
byte, short, int and long. All these are signed positive and negative values.
Java does not support unsigned, positive - only integer. The width of an integer
type should not be thought of as the amount of storage it consumes but rather as
the behavior it defines for variables and expressions of that type. The Java
run-time environment is free to use whatever size it wants, as long as the types
behave as you declared them. In fact at least one implementation stores bytes
and shorts as 32-bit (rather than 8 - bit and 16 - bit) values to improve
performance because that is the word size of most computers currently in use.
The width and ranges of these integer types vary widely, as shown in this table:
Name Width Range
long 64 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
int 32 -2,147,483,648 to 2,147,483,647
short 16 -32,768 to 32,767
byte 8 -127 to 127
Byte: The smallest integer type is byte.
This is a signed 8 - bit type has a range from -128 to 127. Variables of type
byte are especially useful when you're working with a stream of data from a
network or file. They are also useful when you're working with raw binary data
that may not be directly compatible with Java's other built - in types. Byte
variables are declared by use of the byte keyword. For example,the following
declares two byte variables called b and c.
byte c, b;
Short: is a signed 16 - bit type. It has a
range from -32,768 to 32,767. It is probably the least - used Java type, since
it is defined as having high byte first (called big - endian format). For
example:
short c;
Int: The most commonly used integer type is int. It is a signed 32 -
bit type that has a range from -2,147,483,648 to 2,147,483,647. The int type is
the most versatile and efficient type, and it should be used most of the time
when you want to create a number for counting or indexing arrays or doing
integer math. It may seem that using short or byte will save space, but there is
no guarantee that Java won't promote those types to int internally anyway.
Remember type determine behavior not size.
Long: is a signed 64-bit type and is useful for those occasions where
an int type is not large enough to hold the desired value. The range of a long
is quite large. This makes it useful when big, whole numbers are needed. For
example:
// Program to compute distance travelled by light
class Light {
public static void main(String args[]){
int lightspeed;
long days;
long seconds;
long distance;
lightspeed = 186000;
days = 1000;
seconds = days * 24 * 60 * 60;
distance = lightspeed * seconds;
System.out.println (" In "+days);
System.out.println(" days light will travel about");
System.out.println (distance +" miles");
}
}
Float: The type
float specifies a single - precision value that uses 32 bits of storage. Single
precision is faster on some processors and takes half as much space as double
precision, but will become imprecise when the values are either very large or
very small. Variables of type float are useful when you need a fractional
component but don't require a large degree of precision. For example float can
be useful when representing Rupees and paise's.
float hightemp, lowtemp;
Double: Double precision as denoted by the
double keyword uses 64 bits to store a value. Double precision is actually
faster than single precision on some modern processors that have been optimized
for high - speed mathematical calculations. All transcendental math functions,
such as sin( ), cos( ), sqrt( ), etc., return double values. When you need to
maintain accuracy over many iterative calculations or are manipulating large -
valued numbers, double is the best choice.
// Compute the area of a circle
class Area {
public static void main(String args[]){
double pi, r, a;
r = 10.8;
pi = 3.1416;
a = pi * r * r;
System.out.println(" Area of cirlce is " +a);
}
}
Characters: In Java the data type used to store characters is char.
Java uses Unicode to represent characters. Unicode defines a fully international
character set that can represent all of the characters found in all human
languages. Thus in Java char is a 16 bit type. The range of a char is 0 to
65,536. There are no negative chars. The standard set of characters known as
ASCII still ranges from 0 to 127 as always and the extended 8 - bit character
set ISO - latin-1, ranges from 0 to 255. Since Java is designed to allow applets
to be written for worldwide use it makes sense that it would use Unicode to
represent characters.
// Program to demonstrate Char variables
class DemoChar{
public static void main(String args[]){
char ch1, ch2;
ch1 = 88;
ch2 = 'Y';
System.out.println(" ch1 and ch2 : ");
System.out.println(ch1 + " "+ch2);
}
}
Even though chars are not integers in many cases you can operate on them as
if they were integers. This allows you to add two characters together or to
increment the value of a character variable.
For example // char variable integer behavior
class CharDemo{
public static void main(String args[]){
char ch1;
ch1 = 'X';
System.out.println(" ch1 contains" +ch1);
ch1++;
System.out.println(" ch1 is now "+ch1);
}
}
String: The String type, which is not a primitive but a class, is used
to represent sequences of characters. The characters themselves are Unicode and
the backslash notation shown previously for the char type also works in a
String. Unlike C and C++, strings do not end with '\0'.
A string literal is enclosed in double quote marks: "The early birds wins the
race"
For example:
String greeting = "Good day to you";
String message = "Record not found !!";
Stirng str1, str2;
Boolean: Java has a simple type, called boolean for logical values. It
can have only one of the 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.
// Program to demonstrate boolean type
class BoolTest{
public static void main(String args[]){
boolean b;
b = false;
System.out.println(" b is "+b);
b = true;
System.out.println(" b is "+b);
if(b)
System.out.println("This is executed");
b = false;
if(b)
System.out.println(" This is not executed");
System.out.println(" 10 > 9 is "+ (10 > 9));
}
}
Character literals: Characters in Java are indices into the Unicode
character set. They are 16 - bit values that can be converted into integers and
manipulated with the integer operators, such as the addition and subtraction
operators. A literal character is represented inside a pair of single quotes.
Table below shows the character escape sequences
Escape Sequence Description
\ddd Octal character(ddd)
\uxxxx Hexadecimal UNICODE character (xxxx)
\' Single quote
\" Double quote
\\ Backslash
\r Carriage return
\f Form feed
\t Tab
\b Backspace
Variables:
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 variable have a scope, which defines their visibility and a
lifetime.
Declaring a Variable:
In Java all variable 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 initialize the variable by
specifying an equal sign and a value. Keep in mind that the initialization
expression must result in a value of the same type as that specified type, use
comma - separated list.
For example:
int a, b, c; int d = 3, e; byte z = 22;
double pi = 3.141567; char x = 'x';
Dynamic Initialization:
Although the preceding examples have used only constants as initializers,
Java allows variables to be initialized dynamically, using any expression valid
at the time the variable is declared.
For example:
// Program to demonstrate dynamic initialization
class DynInit {
public static void main(String args[]){
double a = 3.0, b= 4.0;
// c is dynamicall initialized and Math.sqrt ( )
is a built in method
double c = Math.sqrt(a * a +b * b);
System.out.println(" Hypotenuse is "+c);
}
}
The Scope And Lifetime Of Variables:
All of the variables used have been declared at the
start of the main( ) method. However 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 a 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.
Most other computer language defines two general
categories of scopes: global and local. However these traditional scopes do not
fit well with Java's strict, Object - oriented model. While it is possible to
create what amounts to being a global scope, it is far the exception, not the
rule. In Java the two major scopes are those defined by a class and those
defined by a method.
As a general rule, 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 localizing that
variable and protecting it from unauthorized access and / or modification.
Indeed the scope rules provide the foundation for encapsulation.
Scopes can be nested. For example each time you
create a block of code, you are creating a new nested scope. When this occurs
the outer scope encloses the inner scope. This means that an object declared in
the outer scope encloses the inner scope. This means that objects declared in
the outer scope will be visible to code within the inner scope. However the
reverse is not true. Objects declared within the inner scope will not be visible
outside it.
// Program to demonstrate block scope
class scope{
public static void main(String args[]){
int x;
x = 10; // only to this block
if( x == 10) {
int y = 20;
// x and y both known here
System.out.println
(" x and y"+x+" "+y);
x = y * 2;
}
// y = 100; // error y not known
System.out.println(" x is "+x);
}
}
With in a block variable can be declared at any point but are valid only
after they are declared. Thus if you define a variable at start of a method, it
is available to all of the code within that method. Conversely, if you declare a
variable at the end of a block, it is effectively useless, because no code will
have access to it. For example, this fragment is invalid because count cannot be
used prior to its declaration.
// Fragment below demonstrates this
count = 100; // Cannot use before it is declared
int count;
Another important point to remember: variables are created when their scope
is entered and destroyed when scope is left. This means that a variable will not
hold its value once it has gone out of scope. Therefore variable declared within
a method will not hold their values when the block is left. Thus the lifetime of
a variable is confined to its scope.
Type Conversion And Casting:
It is fairly common to assign a value of one type to another type. If the two
types are compatible, then Java will perform the conversion automatically. For
example, its always possible to assign an int value to a long variable. However,
not all types are compatible and thus not all type conversions are implicitly
allowed. For instance there is no conversion between incompatible types. To do
so you must use cast which performs an explicit conversion between incompatible
types.
Java's Automatic Conversions:
When one type of data is assigned 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 large than the source type.
When these two conditions are met, a widening
conversion takes place. For example the int type is always large enough to hold
all valid byte values, so on explicit cast statement is required. For widening
conversions the numeric types, including integer and floating - point types, are
compatible with each other. However the numeric types are not compatible with
char and boolean are not compatible with each other. Java also performs an
automatic type conversion when storing a literal integer constant into variables
of type byte, short or long.
Casting Incompatible Types:
Although the automatic type conversions are helpful
they will not fulfill all the needs. For example what if you want to assign an
int value to a byte variable? This conversion will not be performed
automatically because a byte is smaller than an int. This kind of conversion is
sometimes called a narrowing conversion, since you are explicitly making the
value narrower so that it will fit into the target type. 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.
(target-type) value
Here, target-type specifies the desired type to
convert the specified value. For example, the following fragment casts an int to
a byte. If integer's value is larger than the range of a byte, it will be
reduced modulo (the remainder of an integer division by the) byte's range.
int
a;
byte b;
b = (byte) a;
A different type of conversion will occur when a
floating - point value is assigned to an integer type: truncation. As you know
integers do not have fractional components. Thus when a floating - point value
is assigned to an integer, the resulting value will simply be 1. The 0.23 will
have been truncated. Of course, if the size of the whole number component is too
large to fit into the target integer type, then that value will be reduced
modulo the target type's range.
//
program to demonstrate casts.
class Conversion {
public static void main(String args[]){
byte b;
int i = 257;
double d = 323.142;
System.out.println(" Conversion of int to byte");
b =(byte) i;
System.out.println("i and b "+i +" "+b );
System.out.println(" Conversion of double to int ");
i = (int) d;
System.out.println(" d and i "+ d+ " "+i );
System.out.println(" Conversion of double to byte ");
i = (byte) d;
System.out.println(" d and b "+ d+ " "+b );
}
}
Java Coding Conventions: The following are
coding conventions of the Java programming language:
- Classes - class name should
be nouns, in mixed case, with the first letter of each word capitalized.
class AccountBook
class ComplexVariable
- Interface - interface names
should be capitalized like class names.
interface Account
- Methods - methods names
should be verbs, in mixed case with the first letter in lowercase. Within each
method name, capital letters, separate words. Limit the use of underscores.
balanceAccount( )
addComplex( )
- Variables - all variables
should be in mixed case with a lowercase first letter. Words are separated by
capital letters. Limit the use of underscores, and avoid using the dollar sign
($) because this character has special meaning to inner classes.
currentCustomer
Variables should be meaningful and indicate to the casual reader the intent of
their use. You should avoid single character names except for temporary
"throwaway" variable (for example i, j, and k used as loop control variables)
- Constants - primitive
constants should be all uppercase with the words separated by underscores.
Object constants can use mixedcase letters.
HEAD_COUNT
MAXIMUM_SIZE
- Control Structures - use
braces ({ }) for block of statements.
- Spacing - place only a
single statement on any line and use two or four - space indentations to make
your code readable. The number of spaces can vary depending on whose code
standards are used.
- Comments - use comments to
explain code segments that are not obvious.
Arrays:
An array is a group of like - typed variable that
are referred to by a common name. Arrays of any type can be created and may have
one or more dimensions. A specific element in an array is accessed by its index.
Arrays offer a convenient means of grouping related information.
One Dimensional Array:
A one - dimensional array is, essentially a list of
like - typed variables. To create an array, you must first 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 with the
type "array of int":
int month_days[];
Although this declaration establishes the fact that
month_days is an array variable, no array actually exists. In fact, the value 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. The general form of new as it applies to one dimension array
appears as follows:
array-var =new type[size];
Here type specifies the type of data being
allocated, size specifies the number of elements in the array and array-var is
the array variable i.e. linked to the array that is to use new to allocate any
array you must specify the type and number of elements to allocate. The elements
in the array allocated by new will automatically be initialized to zero. This
example allocates 12 - element array of integer and links them to month_days.
E.g. month-days = new int[12];
After this statement executes, month_days will
refer to an array of 12 integers. Further all elements in the array will be
initialized to zero.
Once you have allocated an array, you can access a
specific element in the array by specifying its index within square brackets.
All array indexes start at zero. For example this statement assigns the value 28
to the second elements of month_days.
month_days[1]=28;
String name[ ] = { "Hari","Gopi","Kishore","Monica"};
// Demonstrate a one - dimensional array class Array{
public static void main(String args[]) {
int month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println(" April has "+month_days[3] +" days");
}
}
Arrays can be initialized when they are declared. The process is much the
same as that used to initialize the simple types. An array initializer is a list
of comma - separated expressions surrounded by curly braces. The commas separate
the values of the array elements. The array will automatically be created large
enough to hold the number of elements you specify in the array initializer.
There is no need to use new.
//
Program to create and initialize array of integers:
class Average{
public static void main(String args[]) {
double nums[ ] = { 10.1, 11.2, 12.3, 23.4, 22.4};
double result = 0;
int i;
for(i = 0; i < 5; i++)
result = result+nums[1];
System.out.println(" Average is "+result/5);
}
}
Multidimensional Arrays:
In Java multidimensional arrays are actually arrays of array. 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
multidimensional array variable specifies each additional index using another
set of square brackets. For example, the following declares a two dimensional
array variable.
int
twoD[ ][ ]= new int [4] [5];
int mk[ ][ ]={ {75,85,95,65,45},
{65,75,45,85,75},
{65,85,87,81,45},
{85,75,75,45,88} };
This allocates a 4 by 5 array and assigns it to twoD. Internally this matrix
is implemented as an arrays of array of int
The following program numbers each element in the array from left to right,
top to bottom, and then displays these values:
//
Demonstrate a two_dimensional array.
class TwoDArray {
public static void main{String args[]) {
int twoD [ ] [ ] = new int [ 4] [ 5] ;
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i] [j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print{twoD[i][j] + " ") ;
System.out.println( );
}
}
}
When you allocate memory for a multidimensional array, you need only specify
the memory for the first (leftmost) dimension. You can allocate the remaining
dimensions separately. For example, this following code allocates memory for the
first dimension of twoD when it is declared. It allocates the second dimension
manually.
int
twoD [ ] [ ] = new int [4][ ]
twoD [0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
twoD[3] = new int[5];
While there is no advantage to individually
allocating the second dimension arrays in this situation, there may be in
others. For example, when you allocate dimensions manually, you do not need to
allocate the same, number of elements for each dimension. As stated earlier,
since multidimensional arrays are actually arrays of arrays, the length of each
array is under your control. For example, the following program creates a
two-dimensional array in which the sizes of the second dimension are unequal.
//
Manually allocate differing size second dimensions.
class TwoDAgain {
public static void main(String args[]) {
int twoD[] [] = new int[4] [] ;
twoD[0] = new int[l];
twoD[l] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j< i + l; j++) {
twoD[i] [j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j< i + l; j++)
System.out.print(twoD[i][j] +" ");
System.out.println( );
}
}
Let's look at one more example that uses a
multidimensional array. The following program creates a 3 by 4 by 5, three -
dimensional array. It then loads each element with the
products of its indexes. For
example:
// Demonstrate a three - dimensional array
class three_Dmatrix{
public static void main(String args[]){
int threeD[ ][ ][ ] = new int [3][4][5];
int i, j, k;
for(i = 0; i < 3; i++ )
for(j = 0; j < 3; j++ )
for(k = 0; k < 3; k++ )
threeD[ i ] [ j ] [ k ] = i * j * k;
for(i = 0; i < 3; i++ ) {
for(j = 0; j < 3; j++ ) {
for(k = 0; k < 3; k++ )
System.out.println(threeD[ i ] [ j ] [ k ] + " ");
System.out.println( );
}
System.out.println( );
}
}
}
Alternative Array Syntax :
There is a second form that may be used to declare an array:
type [ ] var_name;
Here, the square brackets follow the type specifier, and not the name of the
array variable. For example the following two declarations are equivalent:
int a1[ ] = new int [3];
int [ ] a2 =new int [3];
The following declarations are also equivalent:
char twod [ ] [ ] = new char [3][4];
char [ ] [ ] twod2 = new char [3][4];
This alternative declaration form is included mostly as a convenience.
HOME
<<PREVIOUS
NEXT>> |