Computing

Arrays and Overloading in Java

In the last article, we dealt with strings, variable initializations and castings. This week lets have a look at the array feature of java and also on a special feature called Operator Overloading. 

Arrays in Java

Java has a built in array class which you can use to hold multiple values provided those values are of the same data type.
In Java, arrays are much more restrictive. For example, you may not change the size of an array once you have created it. To add elements to an array dynamically you actually have to create a new, larger array and copy the old array into the new one using array Copy() in the java.lang.System class.
For a dynamically resizable data structure, look to the Vector class in the java.utilpackage.
However, for cases in which you do not need to dynamically resize your data structure, arrays work great. Java provides a zero-based array, which is defined much as variables are. You first declare what type of data will be stored in an array, give the array a name, and then define how large it is. Consider the following example: 

int[] intArray = new int[40];

This array would hold 40 ints numbered from 0-39.
 
Filling and extracting values from an array is the same process as it was for Perl.
Consider the following example:
 
int[] intArray = new int[40];
for (int i = 0; i < 40; i++)
{
intArray[i] = i;
}
for (int i = 0; i < 40; i++)
{
System.out.println("Value: " + intArray[i]);
}
 
Java also allows you to define an array at time of initialization such as in the following example:
 
int[] intArray = {0,1,2,3,4};
Operator Overloading

Another cool feature of Java is that methods in Java can easily be overloaded such that the same method name can be used for several different implementations of the same action. For example printNumber(), printLetter(), printImage() are the various methods that can be used for several different implementations of the same action.
The only requirement for overloading is that each version of the method takes a different set of parameters as arguments (sometimes, we say that it has a "different signature") such as in the following example: 

int add(int a, int b)
{
return (a+b);
}

float add(float a, float b)
{
return (a+b);
}
 
Finally, it is worth noting that since methods belong to specific classes, it is fine for you to have the same method name with the same arguments in different classes. Thus, the Button class might have a setLabel(String s) method and a Label might have a setLabel(String s) method and neither will conflict since each method is specific to a specific class.   

07-Feb-2002

More by :  Deepak Chandrasekaran


Top | Computing

Views: 3490      Comments: 1



Comment very nice

Reena Baliyan
20-Jun-2011 00:36 AM




Name *

Email ID

Comment *
 
 Characters
Verification Code*

Can't read? Reload

Please fill the above code for verification.