Please open the menu to show more

Friday, August 25, 2017

Frequently asked interview question on java programming language part Eight (8)

Question: Can you tell me the output of this code. Also justify your answer.

Note: Before using this code please create a Java project inside Eclipse and save this class inside TestOfArray.java file

class TestOfArray {

public static void main(String[] args) {

int[] array1 = {1,2}; // lets assume it is line 1
String[] array2 = {"1","2"}; // lets assume it is line 2
char[] array3 = {'1','2'}; // lets assume it is line 3

System.out.println(array1); // lets assume it is line 4
System.out.println(array2); // lets assume it is line 5
System.out.println(array3); // lets assume it is line 6
System.out.println(array3.toString()); // lets assume it is line 7

}
}

The output of this code will be something like ->

array of int: [I@15db9742
array of string: [Ljava.lang.String;@6d06d69c
array of char: 12


Explanation of this code ->

In Java the arrays are represented as an object, and every object has an address.
The name of array is treated like a reference-variable/object-name.

At line number 1 we are creating an array of int
At line number 2 we are creating an array of string
At line number 3 we are creating an array of string

Now,
Actually println is an overloaded methods of PrintStream class (means, many methods in a class with same name but with different parameters).

list of println() method inside PrintStream class is given below ->

1. public void println();
2. public void println(boolean);
3. public void println(char);
4. public void println(int);
5. public void println(long);
6. public void println(float);
6. public void println(double);
7. public void println(char[]);
8. public void println(java.lang.String);
9. public void println(java.lang.Object);

So, at line number 4 and 5 when we pass array name inside println() method the compiler will convert the address of array into string by using toString() method and then this method "public void println(java.lang.String)" will be called, and it will print the address of array in string format

But, when we pass array of char inside println method at line number 6, the method " public void println(char[])" will be called and it will print the content of array rather than address.

Now, at line number 7 we are explicitly calling toString() method on array of char in order to convert it into string, then in this case the method "public void println(java.lang.String)" will be called and address of array will be printed


4 comments:

  1. Awesome sir but one question that any special character is used in any address

    ReplyDelete
    Replies
    1. @ Anshul, yes we can use any special char inside array of char like char[] ch = {'a','$','B'};

      Delete
  2. Thanks for sharing this nice and very useful article.
    Java Programming Interview Questions .
    thanks

    ReplyDelete