|
|
|
home | tutorial | questions | test 1
Declaration and Access Control
- Array Fundamentals
- Arrays are used to represent fixed number of elements of the same
type. The following are legal syntax for declaring one-dimensional arrays.
int anArray[];
int[] anArray;
int []anArray;
It is important to note that the size of the array is not included
in the declaration. Memory is allocated for an array using the new
operator as shown below.
anArray = new int[10];
The declaration and memory allocation may be combined together as
shown below.
int anArray[] = new int[10];
The elements of the array are implicitly initialized to default values
based on array types (0 for integral types, null for objects etc.).
This is true for both local arrays as well as arrays which are data
members. In this respect arrays are different from normal variables.
Variable defined inside a method are not implicitly initialized, where
as array elements are implicitly initialized.
- Array Initializations
- Arrays are initialized using the syntax below
int intArray[] = {1,2,3,4};
The length operator can be used to access the number of elements
in an array (for example - intArray.length).
- Multidimensional Arrays
- The following are legal examples of declaration of a two dimensional
array.
int[] arr[];
int[][] arr;
int arr[][];
int []arr[];
When creating multi-dimensional arrays the initial index must be
created before a later index. The following examples are legal.
int arr[][] = new int[5][5];
int arr[][] = new int[5][];
The following example will not compile;
int arr[][] = new int[][5];
- Class Fundamentals
- A class defines a new type and contains methods and variables. The
example below illustrates a simple class.
class City {
String name; // member variable
String getName() // member method
{
return name;
}
public static void main(String arg[]) {
}
}
- Method overloading
- JavaTM technology allows two methods to have the same name
as long as they have different signatures. The signature of a method
consists of name of the method, and count and type of arguments of the
method. Thus as long as the argument types of two methods are different,
they may be over-loaded (have the same name).
- Class constructors
- Constructors are member methods that have same name as the class name.
The constructor is invoked using the new operator when a class is created.
If a class does not have any constructors then Java language compiler
provides an implicit default constructor. The implicit default constructor
does not have any arguments and is of the type -
class_name() { }
If a class defines one or more constructors, an implicit constructor
is not provided. The example below gives a compilation error.
class Test {
int temp;
Test(int x) {
temp = x;
}
public static void main() {
Test t = new Test(); /* This would generate a
compilation error, as there is no constructor
without any arguments. */
}
}
home | tutorial | questions | test 1
|