Array and Var-Arg
Array and Var-Arg
Definition of an Array
An array is a referenced data type used to create fixed number of multiple variables of same type as a
group to store multiple values of similar type in continuous memory locations with single variable
name.
Need of array
In projects array is used for storing similar type of multiple values or objects and to send all those
multiple values or objects at time as single value from one method to another method either as an
argument or as a return value.
1) Using primitive or class type variables we cannot pass multiple values or objects as one value to
a method as argument and also
2) We cannot return multiple values or objects from a method at a time.
For passing multiple values or objects to a method we must define we must define overloaded
methods with required number of parameters as shown below.
Solution
To solve above two problems, we must group all values or objects to send them as a single unit from
one application to another application as method argument or return type. To group them as a single
unit we must store them in continuous Memory Locations. This can be possible by using referenced
data type array.
In Java, Array is a reference data type. It is used to store fixed number of multiple values and objects of
same type in continuous memory locations.
Note: Like other data types Array is not a keyword rather it is a concept.
It creates continuous memory locations using other primitive or reference types.
Array limitation
Its size is fixed, means we cannot increase or decrease its size after its creation.
For Example:
public static int[] i;
public static Example[] e;
Rule #1: we can place [] Rule #2: Like in C or C++, in Java we cannot
1. after data type mention array size in declaration part. It leads CE.
2. before variable name For Example:
3. after variable name int[5] i; CE: illegal start of expression
4. But not before data type int[] i;
Rule #3: [] is allowed before the variable only for first variable that is placed immediately after data
type.
Ex: int []p, q[];
int []p, []q;
Syntax #1: Array object creation without explicit values or with default values
<Accessibility Modifier> <Modifier> <data type>[] <array name> = new <data type>[<size>];
From the above statement, array object is created with five int type locations.
All locations are initialized with default value ZERO, because the array object is created with primitive
data type int.
Below diagram shows the memory structure of array object with 5 locations.
From the above statement array object is created with five Example type variables. All locations are
initialized with default value null, because the array object is created with referenced data type
Example.
Q) How many String objects are created from the below statement?
String[] s = new String[5];
A) ZERO String objects are created. It creates ONE String array object with 5 variables of type String
with default value "null".
In this array object creation, array contains 4 continuous memory locations with some
starting base address assume 1010, and that address is stored in "ia" variable as shown
in the below diagram.
As you noticed, every
array location has index
starts with ZERO. This
array index is used for
storing, reading, and
modifying array values.
In this array object creation, array contains 3 continuous memory locations with some starting
base address assume 1010, and that address is stored in "ea" variable as shown in the below
diagram.
What is the difference in creating array object with primitive types and referenced types?
As shown in the above diagrams
If we create array object with primitive type, all its memory locations are of primitive type
variables, so values are stored directly in those locations.
If we create array object with referenced type, all its memory locations are of referenced type
variables, so object reference is stored in those locations.
Rule #4: While storing, reading and modifying array values, we must pass array index within the range
of [0, array length-1]. If we pass index negative value or value >= length,
it leads to RE: "java.lang.ArrayIndexOutBoundsException"
Find out errors in the below lines of code Find out errors in the below lines of code
int[] i = new int[5]; int[] i1 = new int[2];
int[] i2 = new int[-4];
i[0] = 6; int[] i3 = new int['a'];
i[1] = 5; int[] i4 = new int["a"];
i[2] = 4; int[] i5 = new int[34.5];
i[3] = 7; int[] i9 = new int[(int)45.34];
i[4] = 8; int[] i6 = new int[0];
i[5] = 9; int[] i7 = {};
i[-3] = 10; int[3] i8 = {1,2,3};
i[10L] = 10; System.out.println(i3[91]);
i['a'] = 10; System.out.println(i6[0]);
i[true] = 10; System.out.println(i3[34.56]);
System.out.println(i3['a']);
System.out.println(i3["a"]);
System.out.println(i1[-1]);
Rule #5: Source data type and destination data type
must be compatible, else it leads to CE: incompatible types
For Example
Example[] ea1 = new Example[5];
Example[] ea2 = new Sample[5];
Example[] ea3 = new String[5];
"length" property
length is a non-static final int type variable. It is created in every array object to store array size. We
must use this variable for finding array object size dynamically for retrieving its elements.
Q) What is the output from the below statement?
Thread[] th = new Thread['a'];
System.out.println(th.length); //97
Q) How many Thread objects are created from above program?
Zero Thread objects are created. Only one Thread array object is created with 97 locations.
Write a program to create int type array with size 5. Then print its values on console.
Q) How can we pass an array with user values without referenced variable?
A) Using Anonymous array
Q) When we pass array object as argument into a method, if we modify its values, will that
modification effect to the original passed-in variable?
A) If we modify array object values with method parameter, the modification is effected to original
referenced variable.
//final array
final int[] ia2 = new int[5];
Q) If we declare array as final, will all its locations are also final?
A) No, only array object referenced variable is final. It means in the above example only “ia2” is final
not its array locations. It means we can modify array locations value, but we cannot assign new array
object reference to this final referenced variable. It leads compile time error.
Find out CE in the below program. Comment the CE, execute and print output.
//ArrayAsFinal.java
class ArrayAsFinal {
public static void main(String[] args) {
System.out.println(ia1[1]);
System.out.println(ia2[1]);
System.out.println(ia3[1]);
Test t = new Test()
System.out.println(t.ia2[1]);
}
}
Q) If we create array object of a class is its class byte codes are loaded into JVM?
Yes, but SV, SBs are not executed. If we create array object from class Example, Example class byte
codes is loaded into JVM, but its SVs and SBs are not executed. If at all in that array object if you create
"Example object", then Example class SVs an SBs are executed.
For example: Below statement loads Example class but doesn’t
class Example{ execute SV and SB from class Example
static{ Example[] e = new Example[5];
Sopln("Example is loaded"); Output: no output
}
Example(){ Below statement loads Example class
Sopln("Example object is created"); Example[] e = {new Example(), new Example()};
} Output: Example is loaded
} Example object is created
Example object is created
Check below program, give output with JVM architecture. Find out CE, RE in Test.java
//Example.java
class Example{
static{
System.out.println("Example is loaded");
}
Example(){
System.out.println("Example object is created");
}
}
//Test.java
class Test{
static Example[] e1 = new Example[5];
Example[] e2 = {new Example(), new Example()};
System.out.println("Test main");
Example[] e3 = new Example[2];
System.out.println(
"e3 array object is created");
System.out.println(e1[0].x);
System.out.println(t.e2[0].x);
System.out.println(e3[0].x);
System.out.println(t.e1[1].y);
}
}
Below syntax is two dimensional array object creation with explicit values
Int[][] ia = { {5, 6, 7}, {8, 9, 10}, {11, 12, 13} };
Below is the array object diagram for this two Below is the table format diagram for the above
dimensional array. two dimensional array object.
Rule: Base array size is mandatory where as child array size is not mandatory.
For Example
int[][] ia = new int[3][];
//int[][] ia = new int[][2]; ->CE: missing array dimension
If we do not pass child array size, child array objects are not be created, only parent array object is
created. Later developer has to pass array objects.
If we pass child array size, all child arrays are created with same size. If we want to create child
arrays with different sizes we must not pass child array size.
Jogged arrays
Multidimensional array with different sizes of child arrays is called Jogged array. It creates a table with
different sizes of columns in a row. To create jogged array, in multidimensional array creation we must
not specify child array size instead we must assign child array objects with different sizes as shown in
the below diagram.
For Example:
int[][] ia = new int[3][]; -> base array is created with size 3
ia[0] = new int[2];
ia[1] = new int[3];
ia[2] = new int[4];
ia[0][0] = 50;
ia[2][3] = 70;
Below is the array object diagram for this two Below is the table format diagram for the above
dimensional array. two dimensional array object.
Below program shows printing multi dimensional array elements in table format
//MultiDimentionalArrayPrinter.java
class MultiDimentionalArrayPrinter {
public static void main(String[] args) {
For example
the class for int type array is "int[]"
the class for Example type array is "Example[]"
the class for Object type array is "Object[]"
3. For all array objects created with referenced types the super class is "Object[]", which is subclass of
"Object"
4. The array objects created with primitive types are not compatible with each other and their super
class is "Object" not "Object[]".
Now observe below hierarchy and strictly remember and follow it in solving next bits.
Find out compile time errors in below list of array objects conversion
SCJP Question:
Given:
11. public static void main(String[] args) {
12. Object obj = new int[] { 1, 2, 3 };
13. int[] someArray = (int[])obj;
14. for (int i : someArray) System.out.print(i + " ");
15. }
What is the result?
A. 1 2 3
B. Compilation fails because of an error in line 12.
C. Compilation fails because of an error in line 13.
D. Compilation fails because of an error in line 14.
E. A ClassCastException is thrown at runtime.
java.lang.ArrayStoreException
JVM throws this exception, if it identifies the incompatible object is passed to store in array location. If
this problem is identified by compiler, it throws CE: "incompatible types".
In this statement compiler thinks "Example array object is created with five locations and is stored in
Object[] variable". This assignment is allowed as Example[] is a subclass of Object[].
class AdditionWithArrayParam {
static void add(int[] a){
if ( a.length == 0){
System.out.println("Values are not passed");
}else{
int sum = 0;
for (int i = 0; i < a.length; i++){
sum = sum + a[i];
}
System.out.println("Result: "+sum );
}
}
public static void main(String[] args) {
add( new int[]{} );
add( new int[]{5} );
add( new int[]{ 5, 6 } );
add( new int[]{ 5, 6, 7 } );
add( new int[]{ 5, 6, 7, 8 } );
}
}
class AdditionWithVarArgParam {
static void add(int... a){
if ( a.length == 0){
System.out.println("Values are not passed");
}else{
int sum = 0;
for (int i = 0; i < a.length; i++){
sum = sum + a[i];
}
System.out.println("Result: "+sum );
}
}
public static void main(String[] args) {
add( );
add( 5 );
add( 5, 6 );
add( 5, 6, 7 );
add( 5, 6, 7, 8 );
add( new int[]{5,6,7, 8, 9});
}
}
//PassingDynamicValues.java
import java.util.*;
class PassingDynamicValues {
}
}
//PassingDynamicValues.java
import java.util.*;
class PassingDynamicValues {
}
}
//VarArgRTvaluesTest.java
import java.util.*;
class A{
void m1(int... ia){
System.out.println(ia.length + " values are passed");
for ( int i : ia ){
System.out.println(" "+i);
}
}
}
class VarArgRTvaluesTest{
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
if(input.isEmpty()){
iNums = new int[0];
}
else{
//Splitting given sting into individual numbers
String[] sNums = input.split(" ");
if(sNums.length != 0){
//Copying nums from sNums to iNums array
// by converting numbers from String form to int form
for(int i = 0; i < sNums.length; i ++){
iNums[i] = Integer.parseInt( sNums[i] );
}
}
}//if-else(empty)
//invoking var-arg method by passing array with '0 - n' number of values
A a1 = new A();
a1.m1( iNums );
}
}
//VarArgReadingNamesRT.java
import java.util.*;
class NamesPrinter{
static void print(String... names) {
System.out.println(names.length +" names are passed");
System.out.println("They are: ");
class VarArgReadingNamesRT{
public static void main(String[] args){
Scanner scn = new Scanner(System.in);
if( input.isEmpty() ){
NamesPrinter.print();
}else{
String[] names = input.split(" ");
NamesPrinter.print( names );
}
}
}
//VarArgRules.java
class Employee{}
class VarArgRules{
//Rule #1:
int... ia;
void m2(int... ia){}
//Rule #2:
void m1(int... ia){}
void m1(int.. ia){}
void m1(int.... ia){}
//Rule #3:
void m3(int... ia){}
void m4(int ...ia){}
void m5(int ia...){}
void m5(...int ia){}
void m6(int...ia){}
//Rule #4:
void m7(int... ia){}
void m7(int...... ia){}
void m7(int[]... ia){}
void m7(int[][]... ia){}
void m8(int[]ia[]){}
void m9(int[]ia...){}
//Rule #5
static void m10(int... ia, int a, int b){
static void m10(int a, int... ia, int b){
//Rule #6:
static void m11(int... a, int... b){}
static void m11(int... a, String... b){}
//Rule #7:
static void m12() { System.out.println("no-param method");}
static void m12(int a) { System.out.println("int-param method");}
static void m12(int... a){ System.out.println("int var-arg method");}
//Rule #8:
static void m13(int... a) { System.out.println("int var-arg method");}
static void m13(long... a) { System.out.println("long var-arg method");}
static void m13(float... a) { System.out.println("float var-arg method");}
//Rule #9:
static void m15(int... a) { System.out.println("int var-arg method");}
static void m15(float... a) { System.out.println("float var-arg method");}
//m15(); m15(5); m15(5L); m15(5F);
//Rule #10:
static void m16(int a) { System.out.println("int param method");}
static void m16(int... a) { System.out.println("int var-arg method");}
//m16(); m16(5); m16(5, 6); m15( new int[]{5});
//Rule #11:
static void m17(int[] a){ System.out.println("int[] arg method");}
static void m18(int... a){ System.out.println("int var-arg method");}
//Rule #12:
static void m19(int[] a){ System.out.println("int[] arg method");}
static void m19(int... a){ System.out.println("int var-arg method");}
m12(); m13();
m12(5); m13(5);
m12(5,6); m13(5L);
m12(5,6,7); m13(5F);
m13(5, 5L);
m13(5, 5L, 5F);
m14();
m14(5);
m14(true);
m16(5);
m16( new int[]{5});
m17();
m17(5);
m17( new int[0] );
m17( new int[]{5} );
m18();
m18(5);
m18( new int[0] );
m18( new int[]{5} );
}//main close
}//class close
e[1] = null;
at this line number, e[1] referencing object is eligible for garbage collection.
e = null;
at this line number, all 5 objects, including array object, are eligible for garbage collection.
Q) In the below program how many objects are eligible for gc?
class Test{
static void m1(Example[] e){
e[1] = null;
e = null;
}
public static void main(String[] args){
Example[] e = new Example[5];
e[0] = new Example();
e[1] = new Example();
e[2] = new Example();
Example e1 = new Example();
e[3] = e1;