-1

This is a simple code that focuses on the problem so I can apply this to the actual program.

The first class has the array. The second I want it to print array elements to the scanner. This code gives me a null pointer exception. I tried using an int instead of int array but still got the same exception. How can I fix this?

public class passthrough{

  public void main(String[] args){
   PassTry k = new PassTry();

   System.out.println(k.pass);
   System.out.println(k.her);

  }

}//class

public class PassTry{
  public int[] pass; 
  public int her;

  public PassTry(){
     her = 2;
     pass = new int[]{4, 5, 6, 2};

  }//constructor

  public int res(){
    return  this.her;

  }//res method

}//class
Piyush Gupta
  • 2,181
  • 3
  • 13
  • 28
Lily_
  • 1

1 Answers1

1

You are missing static Keyword in main method so you need to write like this,

public static void main(String args[]) {...

Each word has different meaning and different purpose,

Static : Keyword which identifies the class related this. It means that this class is not instance related but class related. It can be accessed without creating the instance of Class.

Java compiler always look for main method to compile the source code but here is you didn't provide static so compiler is unable to reach main method and trowing compile time error which is java.lang.NullPointerException

Piyush Gupta
  • 2,181
  • 3
  • 13
  • 28