Jump to content

How to fix NullPointerException Error With Array?

- - - - -

  • Please log in to reply
1 reply to this topic

#1
VakhoQ

VakhoQ

    Programmer

  • Members
  • PipPipPipPip
  • 126 posts

public class test {

	public static void main(String Args[]){

					

	      cls [] arr = new cls [10];			

	       arr[0].m=2; // line8 is this :)

	       arr[0].n="b";

	}


}


class cls{	

	int m; String n;

	public cls(){

		 m=1;  

		 n="a";		

	}

	

}


ERROR

[COLOR="#B22222"]Exception in thread "main" java.lang.NullPointerException

	at test.main(test.java:8)

[/COLOR]


could you tell me, what mistakes do I have, please?
GNU/Linux Is the Best.

#2
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
[COLOR=#0000BB]cls [/COLOR][COLOR=#007700][] [/COLOR][COLOR=#0000BB]arr [/COLOR][COLOR=#007700]= new [/COLOR][COLOR=#0000BB]cls [/COLOR][COLOR=#007700][[/COLOR][COLOR=#0000BB]10[/COLOR][COLOR=#007700]];[/COLOR]
At this line the array is created, not the objects inside it. The objects inside it are given the default value: null.
For int the default value is 0, double: 0.0, boolean: false, float: 0, long 0 .

Everything else (classes with a capital letter even Integer, Double, Boolean,...) will be null.
(Your own classes should start with a capital letter as well)

[COLOR=#0000BB]arr[/COLOR][COLOR=#007700][[/COLOR][COLOR=#0000BB]0[/COLOR][COLOR=#007700]] = new cls(); [/COLOR]
Is what you need to do first.

To fill the whole array:
import java.util.Arrays;

...

Arrays.fill(arr, new cls());





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users