• No results found

STACK HEAP a

In document core java (Page 129-138)

Example-2 class p

STACK HEAP a

1000 B 5000 1000 x=2 5000 x=1

Now consider the 2nd program q.java. up to the function call valueSwap(), everything is similar to that of p.java. Here inside the method valueSwap() of the program q.java things are different. „temp‟ is an reference of class q. temp=k; means now temp=1000;, k=l; means k=5000 & l=temp; means l=1000. When control goes out of the method valueSwap(), k&l become dead because they are local reference variables created inside stack. Hence changes are not reflected.

One has to understand the concept that local variables always die when control goes out of a method. But, if the local variables are of

reference type then the changes they have made in the memory locations they are pointing are permanent.

Hash code

When an object is created through new operator by calling the constructor of the corresponding class a unique identifier is assigned to the reference variable, known as hash code. Hash code is allotted by JVM. How to determine the hash code?

Example-3

class p {

public static void main(String args[ ]) { p x=new p(); System.out.println(x.hashCode()); } }

The method hashCode() returns the hash code of the corresponding reference when object is created. Hash code is assigned only to reference variables when memory is allocated from heap area.

Local variables of primitive data types are created inside stack area & memory is allocated from there also. All the above complexities are not involved here. Local variables of primitive data types do

not have any hash code because they do not acquire memory from heap area. To get hash code the variable must be of reference type.

Example-4 class p

{

public static void main(String f[ ])

{

int mak=5;

System.out.println(mak.hashCode());

}

}

Above program will result a compilation error because mak is not a reference variable & memory is not allocated to it from heap. The error is “int can not be dereferenced”. The next question that arises is it possible to allocate memory to variables of primitive data type from heap & the answer is yes. I will explain it in array.

 A note from author: Ok, our voyage of “OBJECT & REFERENCE” is completed. But, there is a mystery still to be unrevealed. Mystery is about static variables. Static variables are created inside method area. Objects are inside heap. References are inside stack. Static variables can be accessed by reference variables, but only after the object is created by invoking the constructor of the class through new operator, other wise compilation error will arise. When an object is created inside heap, along with the instance variables it also contains a

pointer to the memory location of method area which contains the static variables of corresponding class. All the objects of a particular class contains pointer which holds the address of same particular memory location inside method area containing the static data member of that class.

Chapter-8

Array

Array is a linear homogeneous data structure. It is simply a collection of similar type elements. An element present in the array is accessed through its index. You can define an array either as int[ ] arr; Or as int arr[ ]. But the former one is preferred by most java programmer. A specific element of an array is accessed by the index. The syntax of one dimensional array declaration is

Data_Type variable_name [ ] =new Data_Type[size]; Or

Data_Type [ ] variable_name=new Data_Type[size];

Here Data_Type specifies the type of array that is created, size specifies number of elements in the array, and variable_name is the array variable or in particular a reference variable of the corresponding data type. But, things are quite different in case of an array of objects.. The 1st element of the array is accessed by placing 0 in the [ ]. 0th index represents the 1st element of the array.

Example-1

public class Demo {

public static void main(String[] args) {

int[] arr=new int[2]; System.out.println(arr[0]); System.out.println(arr[1]); } } Output is 0 0

In general to create an array you must follow three steps

 Declaration

 Construction

 Initialization

Declaration tells the java compiler what the array‟s name is and what the type of its elements will be. For example,

int[ ] ints;//ints ia an integer array variable double[ ] dubs;//dubs is a double array variable char[ ] chars//chars is a character array variable. float[ ] floats;//floats is a float array variable.

Construction means calling the new operator to allocate memory for the array variable. During initialization process the elements of the array is initialized to their default values.

Array Element Initialization Values Element Type Initial Values Byte 0 Int 0 Float 0.0f Char „\u0000‟ Short 0 Long 0L Double 0.0d Boolean false reference null

In the above program array constructed where it is declared. You can separate the process.

Example-2

public class Demo {

public static void main(String[] args) {

int[] arr;//array declaration

arr=new int[2];//array construction System.out.println(arr[0]);

System.out.println(arr[1]); }

}

A closer look at array Example-3

public class Demo {

public static void main(String args[])

{

int [ ]mak=new int[3]; //Array declaration in java mak[0]=1; mak[1]=2; mak[2]=3; System.out.println(mak[0]); System.out.println(mak[1]); System.out.println(mak[2]); } } Output is 1 2 3

int mak[ ]=new int[3]; is the statement to create the integer array of length 3. Remember that new operator always allocates memory from the heap. If [ ] is associated with variable declaration then, that variable is of reference type. So „mak‟ is a reference type variable that

means it is going to hold the address of a memory location. The new operator allocates memory from heap according to the size specified & the starting address is stored in mak. The memory is allocated continuously for mak from heap.

„mak‟ is the reference variable created inside stack. The new operator allocates memory from heap & the starting address of the memory location i.e. 65556 is stored in mak. Since for array continuous memory allocation is done & integer takes 4 byte of memory therefore the address of the next memory location is 65560 & so on.

To access the elements present in the array the statement is System.out.println(mak[0]);

System.out.println(mak[1]); System.out.println(mak[2]);

Value stored in mak

mak[0] means value stored at (65556+0* size of integer ) mak[1] means value stored at (65556+1* size of integer) mak[2] means value stored at (65556+2*size of integer)

In general if you have declared

Data_Type [ ]var_name=new Data_Type[size];

var_name[i] means value stored at (starting address+ i* size of Data_Type)

here i is an integral index & i<size.

If the data type is of object reference then size will be 4 bytes.

Array actually are objects, even to an extent you can execute methods on them, mostly of the object class. But, you can not create child class or sub class of an array.

Creating a programmer-initialized array Example-4

public class Demo {

public static void main(String args[])

{

int [ ]mak={1,2,3};

//Array declaration in java mak[0]=1; mak[1]=2; mak[2]=3; System.out.println(mak[2]); } } Output is 3

One may think that how array is created with out new operator. In the above situation java compiler implicitly calls the new operator to allocate memory from heap.

Accessing the element beyond the size of an array throws a compile time error as shown in the program below.

Example-5

public class Demo {

public static void main(String args[])

{

int [ ]mak={1,2,3};

//Array declaration in java mak[0]=1; mak[1]=2; mak[2]=3; System.out.println(mak[3]); } }

This program generates an Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3

at Demo.main(Demo.java:13)

Creation of reference to a primitive:

This is a useful technique to create a reference of primitive data type. Array in java provides such technique. In this procedure the data is stored in heap instead of stack. Simply you just create an array of one element of primitive data type

Example-6

public class Demo {

public static void main(String args[])

{

int [ ]mak=new int[1]; //Array declaration in java mak[0]=10;

changeIt(mak);

System.out.println(mak[0]);

}

static void changeIt(int []p) {

p[0]=100;

}

Out put are 100

Due to reference change is reflected.

In document core java (Page 129-138)

Related documents