CHAPTER-2(Classes and Objects)                                   BOTTOM

 

Arrays:-

An array is a data structure that defines an indexed collection of a fixed number of homogeneous data elements. This means that all elements in the array have the same data type. A position in the array is indicated by a non-negative integer value called the index. An element at a given position in the array is accessed using the index. The size of an array is fixed and cannot increase to accommodate more elements. In Java, arrays are objects.

Arrays can be of primitive data types or reference types. In the former case, all elements in the array are of a specific primitive data type. In the latter case, all elements are references of a specific reference type. References in the array can then denote objects of this reference type or its subtypes. Each array object has a final field called length, which specifies the array size, that is, the number of elements the array can accommodate. The first element is always at index 0 and the last element at index n-1, where n is the value of the length field in the array.
Simple arrays are one-dimensional arrays, that is, a simple sequence of values. Since arrays can store object references, the objects referenced can also be array objects. This allows implementation of array of arrays.


Declaring Array Variables


An array variable declaration has either the following syntax:

<element type>[] <array name>;
or
<element type> <array name>[];

where <element type> can be a primitive data type or a reference type. The array variable <array name> has the type <element type>[]. Note that the array size is not specified. This means that the array variable <array name> can be assigned an array of any length, as long as its elements have <element type>. It is important to understand that the declaration does not actually create an array. It only declares a reference that can denote an array object.

Example:-

int anIntArray[], oneInteger;
Pizza[] mediumPizzas, largePizzas;

These two declarations declare anIntArray and mediumPizzas to be reference variables that can denote arrays of int values and arrays of Pizza objects, respectively. The variable largePizzas can denote an array of pizzas, but the variable oneInteger cannot denote an array of int values.it is simply an int variable.

Constructing an Array


An array can be constructed for a specific number of elements of the element type, using the new operator. The resulting array reference can be assigned to an array variable of the corresponding type.


<array name> = new <element type> [<array size>];

The minimum value of <array size> is 0 (i.e., arrays with zero elements can be constructed in Java). If the array size is negative, a NegativeArraySizeException is thrown. Given the following array declarations:

int anIntArray[], oneInteger;
Pizza[] mediumPizzas, largePizzas;

the arrays can be constructed as follows:

anIntArray = new int[10]; // array for 10 integers
mediumPizzas = new Pizza[5]; // array of 5 pizzas
largePizzas = new Pizza[3]; // array of 3 pizzas

The array declaration and construction can be combined.


<element type1>[] <array name> = new <element type2>[<array size>];

However, here array type <element type2>[] must be assignable to array type <element type1>[] .. When the array is constructed, all its elements are initialized to the default value for <element type2>. This is true for both member and local arrays when they are constructed.
In all the examples below, the code constructs the array and the array elements are implicitly initialized to their default value. For example, the element at index 2 in array anIntArray gets the value 0, and the element at index 3 in array mediumPizzas gets the value null when the
arrays are constructed.

int[] anIntArray = new int[10]; // Default element value: 0.
Pizza[] mediumPizzas = new Pizza[5]; // Default element value: null.
// Pizza class extends Object class

The value of the field length in each array is set to the number of elements specified during the construction of the array; for example, medium Pizzas.length has the value 5. Once an array has been constructed, its elements can also be explicitly initialized individually.

Initializing an Array

Java provides the means of declaring, constructing, and explicitlyinitializing an array in one declaration statement:

<element type>[] <array name> = { <array initialize list> };

This form of initialization applies to member as well as local arrays. The <array initialize list> is a comma-separated list of zero or more expressions. Such an array initialization block results in the construction and initialization of the array.

int[] anIntArray = {1, 3, 49, 2, 6, 7, 15, 2, 1, 5};

The array anIntArray is declared as an array of ints. It is constructed to hold 10 elements (equal to the length of the list of expressions in the block), where the first element is initialized to the value of the first expression (1), the second element to the value of the second expression (3), and so on.

// Pizza class extends Object class
Object[] objArray = { new Pizza(), new Pizza(), null };

The array objArray is declared as an array of the Object class, constructed to hold three elements. The initialization code sets the first two elements of the array to refer to two Pizza objects, while the last element is initialized to the null reference. Note that the number of objects created in the above declaration statement is actually three: the array object with three references and the two Pizza objects. The expressions in the <array initialize list> are evaluated from left to right, and the array name obviously cannot occur in any of the expressions in the list. In the examples above, the <array initialize list> is terminated by the right curly bracket, }, of the block. The list can also be legally terminated by a comma. The following array has length two, not three:

Topping[] pizzaToppings = { new Topping("cheese"), new Topping("tomato"), };

The declaration statement at (1) in the following code defines an array of four String objects, while the declaration statement at (2) should make it clear that a String object is not the same as an array of char.

// Array with 4 String objects

String[] pets = {"crocodiles", "elephants", "crocophants", "elediles"}; // (1)

// Array of 3 characters

char[] charArray = {'a', 'h', 'a'}; // (2) Not the same as "aha".

Multidimensional Arrays(2-D Array)

In Java, multidimensional 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 multidimensional array variable, specify each additional index using another set of square brackets. For example, the following declares a two-dimensional array variable called twoD.

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 array of arrays of int. Conceptually, this array will look like the one shown in Figure below.

// 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();
}
}
}


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

 

 

WRAPPER CLASSES

Simple data types, such as int and char, are not part of the object hierarchy. They are
passed by value to methods and cannot be directly passed by reference. Also, there is no way for two methods to refer to the same instance of an int. At times,we will need to create an object representation for one of these simple types. For example there are collection classes that deal only with objects; to store a simple type in one of these classes, we need to wrap the simple type in a class. To address this need, Java provides classes that correspond to each of the simple types. In essence, these classes encapsulate, or wrap, the simple types within a class. Thus, they are ommonly referred to as type wrappers.

Double and Float

Double and Float are wrappers for floating-point values of type double and float,
respectively. The constructors for Float are shown here:

Float(double num)
Float(float num)
Float(String str) throws NumberFormatException

As you can see, Float objects can be constructed with values of type float or double. They can also be constructed from the string representation of a floating-point numbers

Double:-

The constructors for Double are shown here:
Double(double num)
Double(String str) throws NumberFormatException

Double objects can be constructed with a double value or a string containing a floating-point value.

Example:-

class DoubleDemo {
public static void main(String args[]) {
Double d1 = new Double(3.14159);
Double d2 = new Double("314159E-5");
System.out.println(d1 + " = " + d2 + " -> " + d1.equals(d2));
}
}

Ans.3.14159 = 3.14159 –> true

// Demonstrate isInfinite() and isNaN()
class InfNaN {
public static void main(String args[]) {
Double d1 = new Double(1/0.);
Double d2 = new Double(0/0.);

System.out.println(d1 + ": " + d1.isInfinite() + ", " + d1.isNaN());
System.out.println(d2 + ": " + d2.isInfinite() + ", " + d2.isNaN());
}
}

This program generates the following output:
Infinity: true, false
NaN: false, true


Byte, Short, Integer, and Long

The Byte, Short, Integer, and Long classes are wrappers for byte, short, int, and long integer types, respectively. Their constructors are shown here:

Byte(byte num)
Byte(String str) throws NumberFormatException

Short(short num)
Short(String str) throws NumberFormatException

Integer(int num)
Integer(String str) throws NumberFormatException

Long(long num)
Long(String str) throws NumberFormatException

As you can see, these objects can be constructed from numeric values or from strings that contain valid whole number values.


The Byte, Short, Integer, and Long classes provide the parseByte( ), parseShort( ), parseInt( ), and parseLong( ) methods, respectively. These methods return the byte, short, int, or long equivalent of the numeric string with which they are called. (Similar methods also exist for the Float and Double classes.)
The following program demonstrates parseInt( ). It sums a list of integers entered by the user. It reads the integers using readLine( ) and uses parseInt( ) to convert these strings into their int equivalents

/* This program sums a list of numbers

/* This program sums a list of numbers entered
by the user. It converts the string representation
of each number into an int using parseInt().
*/

import java.io.*;
class ParseDemo {
public static void main(String args[])
throws IOException
{
// create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str; int i;
int sum=0;
System.out.println("Enter numbers, 0 to quit.");
do {
str = br.readLine();
try {
i = Integer.parseInt(str);
} catch(NumberFormatException e) {
System.out.println("Invalid format");
i = 0; }
sum += i;
System.out.println("Current sum is: " + sum);
} while(i != 0); } }

/* Convert an integer into binary, hexadecimal,
and octal.
*/
class StringConversions {
public static void main(String args[]) {
int num = 19648;
System.out.println(num + " in binary: " +
Integer.toBinaryString(num));
System.out.println(num + " in octal: " +
Integer.toOctalString(num));
System.out.println(num + " in hexadecimal: " +
Integer.toHexString(num)); } }

The output of this program is shown here:

19648 in binary: 100110011000000
19648 in octal: 46300
19648 in hexadecimal: 4cc0

Character:-


Character is a simple wrapper around a char. The constructor for Character is Character(char ch)
Here, ch specifies the character that will be wrapped by the Character object being created To obtain the char value contained in a Character object, call charValue( ), shown here:
char charValue( ) It returns the character.

Example:-

class IsDemo {
public static void main(String args[]) {
char a[] = {'a', 'b', '5', '?', 'A', ' '};
for(int i=0; i<a.length; i++) {
if(Character.isDigit(a[i]))
System.out.println(a[i] + " is a digit.");
if(Character.isLetter(a[i]))
System.out.println(a[i] + " is a letter.");
if(Character.isWhitespace(a[i]))
System.out.println(a[i] + " is whitespace.");
if(Character.isUpperCase(a[i]))
System.out.println(a[i] + " is uppercase.");
if(Character.isLowerCase(a[i]))
System.out.println(a[i] + " is lowercase."); } } }

The output from this program is shown here:

a is a letter.
a is lowercase.
b is a letter.
b is lowercase.
5 is a digit.
A is a letter.
A is uppercase.
A is whitespace.

Boolean

Boolean is a very thin wrapper around boolean values, which is useful mostly when you want to pass a boolean variable by reference. It contains the constants TRUE and FALSE, which define true and false Boolean objects.Boolean defines these constructors:

Boolean(boolean boolValue)
Boolean(String boolString)

In the first version, boolValue must be either true or false. In the second version, if boolString contains the string “true” (in uppercase or lowercase), then the new Boolean object will be true. Otherwise, it will be false. Boolean defines the methods shown below.


 

Note : After Successful completion of Training Candidate will be provided with Project Report and Training Certificate.

Home  |   FeedBack  |   Terms of Use  |   Contact Us  |   Report Error
                                                                            Copyright © 2009 R.M Infotech (P) Ltd.                                             Designed by: Raman