|
JAVA PROGRAMMING |
DATA TYPES AND VARIABLESJava 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: 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:
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. 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: 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. 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'. 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: 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.
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:
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; 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. Java Coding Conventions: The following are coding conventions of the Java programming language:
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": 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; 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: 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]; 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. 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][ ] 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. 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:
|