• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

Doubt

 
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is a question in mock exam like

public class test
{
private static int[]x;
public static void main(String a[])
{
System.out.println(x[0]);
}
}

I didn't understand why the answer of this is NullPointerException.
Plz explain......

Thanks
UmaVinodh.
 
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Array is an object.
 
Amieya Prabhaker
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To elaborate:

Although we know, Array elements are always given default values, regardless of where the array itself is declared or instantiated.

In your code, the array is declared, not instantiated. Moreover, since x is an object, it is not yet existing to be called.

If you replace your array declaration with an instantiation as well:
private static int[] x = new int[5];

you will get your expected "0" output.
 
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Initial Values of Variables.
 
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because You wany to print the value before initializing array object. Thats it.
 
Amieya Prabhaker
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's a subtle terminology:
Array objects are automatically initialized with default values.

What's missing here is "instantiation" not initialisation.
 
Ranch Hand
Posts: 324
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Array elements get their defualt value when array is initialized.
when we declare array i.e. int [] x; it is null a this moment. When we say
x = new int [6]; now all the 6 elements of array will get thier defualt value
 
Do the next thing next. That’s a pretty good rule. Read the tiny ad, that’s a pretty good rule, too.
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
reply
    Bookmark Topic Watch Topic
  • New Topic