Java Array Initialization


Array InitializationJava Array Initialization


Once we create an array every element by default initialize by default values.


example 1:

         int [ ] x =new int [ 3];

          System.out.println(x[0]);         o/p is    0            (default initial value)

          System.out.println(x[1]);          o/p is    0            (default initial value)

          System.out.println(x[2]);         o/p is    0            (default initial value)

          System.out.println(x);               o/p is      [ I@3e25a5


surprise What is this number???

Remember Carefully that whenever we are trying to print any reference variable internally toString()

the method will be called which is by default implemented to return in the following from.



                Classname@hashcode_in_hexadecimalform

                      means

                   [ is 1-D array

                   I is for Integer class

                   @3e25a5 hashcode (For every system it is different)


          List of corresponding classes:


javabychetan.blogspot.com

example 2:
int [ ] [ ] x = new int [3] [ 2]
System.out.println(x);               o/p is      [ [  I@3e15a9
System.out.println(x[0]);               o/p is      [  I@5e25a5
System.out.println(x[0][0]);               o/p is       0      (default initial value)

let take a look at the memory representation:-
javabychetan.blogspot.com

example 3:


int [ ] [ ] x= new int [ 3] [ ];


             System.out.println(x);                        o/p is      [ [  I@3e15a9

System.out.println(x[0]);                   o/p is    null
System.out.println(x[0][0]);               no o/p we will get "NullPointerException"
because we are trying to operate on null.

Once we creates an array every array element by default initialize values ,if we are not satisfied with default values then we can override these values with our customized values.
for example:
int [ ] x= new int [3];
x[0]=40;
x[1]=50;
x[2]=60;
System.out.println(x[0])    o/p is         40;
System.out.println(x[1])    o/p is         50;
System.out.println(x[2])    o/p is         60;

No comments:

Post a Comment

Be the first to comment!

Don't just read and walk away, Your Feedback Is Always Appreciated. I will try to reply to your queries as soon as time allows.

Note:
1. If your question is unrelated to this article, please use our Facebook Page.
2. Please always make use of your name in the comment box instead of anonymous so that i can respond to you through your name and don't make use of Names such as "Admin" or "ADMIN" if you want your Comment to be published.

Regards,
JavaByChetan
Back To Home

Flipkart End Of Season Sale






© Copyright 2017 Javabychetan.blogspot.com