Anonymous Array
Anonymous Array
In Java 1.1 the concept of anonymous array was introduced. While it is easy to initialize
an array when it is declared , you couldnt reinitialize the array later with a comma-
delimited list unless you declared another variable to store the new array in .
In this place anonymous array is used
Can reinitialize an array to a new set of values or pass unnamed arrays into methods when
you dont want to define a local variable to store said array.
Syntax
new type[] { comma-delimited-list};
int[] a= {1,2,3,4};
a=new int[]{5,6,7,8};
or
int[] a2={5,6,7,8};
a1=a2;
eg.,
int[] a1={5,6,7,8};
for(int e:a1)
System.out.println(e);
int[] a2={1,2,3,4,5};
a1=a2;
// or a1=new int[]{1,2,3,4};
for(int e:a1)
System.out.println(e);
class AnonymousArray
{
static void print(int a[])
{
for(int i=0;i<a.length;++i)
System.out.print(a[i]+" ");
{
for(int i=0;i<a.length;++i)
for(int j=0;j<a[i].length;++j)
System.out.print(a[i][j]+" ");
System.out.println("");
print(new int[]{10,20,30,40});
System.out.println("\n");
}
}
Ragged array
class raggedarray
{
public static void main(String ...s)
{
/* int[][] p=new int[5][];
for(int i=1;i<=5;i++)
p[i-1]=new int[i];
for(int j=0;j<p.length;j++)
System.out.println(p[j].length);
int number = 0;
int[][] pyramid = new int[4][];
for (int i = 0; i < pyramid.length; i++)
{
pyramid[i] = new int[i+1];
for (int j = 0; j < pyramid[i].length; j++)
pyramid[i][j] = number++;
}
/*
output
0
12
345
6 7 8 9*/
}
}
CLASS
A Class is a template for an object.
It helps to encapsulate entire set of data and code that operate on data into a single user
defined data type
When a class is created, we create a new data type.
General form of a class is
class classname {
// instance field declarationa
type instance-variable-1;
type instance-variable-2;
type instance-variable-N;
// method definition
type methodname-1(parameter-list) { //body of method }
type methodname-2(parameter-list) { //body of method }
type methodname-N(parameter-list) { //body of method }
//constructor definition
classname(parameter-list) { //body of constructor }
.
}
The class body (the area between the braces) contains following item :
- constructors for initializing new objects
- field declarations
that provide the state of the class and its objects
called as instance field
Syntax
datatype variablename[=value];
- methods
the procedure /code that operates on the data .
Syntax
accessspecifier returntype methodname(parameter list){}.
Example
class Box {
// instance field
double width, height, depth;
// constructor of 3 parameters
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// method to compute and return volume
double volume() {
return width * height * depth;
}
}
OBJECTS
Defn:
Called as instance of a class
or
An object in Java is a block of memory that contains space to store all the instance
variables.
METHODS