Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Array of zero size

 
Phillipe Rodrigues
Ranch Hand
Posts: 165
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why I get the junk output for the below program.What am I doing wrong?Wat is wrong at line (1)


Output:
D:\>javac test4.java

D:\>java test4
[I@108786b
 
Sagar Rohankar
Ranch Hand
Posts: 2907
1
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your printing an array object, and which returns its hashcode value !

See How Object#toString() defaults implementation works !!

Whenver you print object ,it calls it toString() method,
 
Phillipe Rodrigues
Ranch Hand
Posts: 165
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i would like to know what happens when we try executing (1) in above code.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15441
41
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It creates an array of length zero, which is perfectly legal in Java.
 
Kaydell Leavitt
Ranch Hand
Posts: 690
Eclipse IDE Firefox Browser Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It creates an array of length zero, which is perfectly legal in Java.


It is not only legal to create an array of zero length but it is usually better to simplify your code so that you don't have to special case to see if the array is null or not.

In the following code, the for-loop just works with a zero-length array without any special casing to see if the array is null or not.



In the above code, a zero-length array runs OK, it just doesn't run the loop-body any times. If arr is null then a NullPointerException is thrown.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic