M
M
Millerish2016-08-10 22:53:46
Java
Millerish, 2016-08-10 22:53:46

Why does Java throw java.lang.NullPointerException?

Good evening!
I understand java. Why do I get java.lang.NullPointerException when I check for Null? How right?

import java.util.Arrays;
import java.util.Scanner;

public class l9 {

    public static void main(String[] args){
        class Arr{


            int[] mass;

            void sayLen(){
                if (mass == null) {
                    System.out.println("0");
                } else {
                    int len = this.mass.length;
                    System.out.println(len);
                }
            }

            void addToMass(int e){
                if (mass == null) {
                    this.mass[0] =e;
                } else {
                    this.mass[mass.length+1] = e;
                }

            }

        }

        Arr arr = new Arr();
        Scanner in = new Scanner(System.in);

        while (true){
            try {
                int a = in.nextInt();
                System.out.println(a);
                arr.addToMass(a);
                arr.sayLen();
            }
            catch (Throwable e){
                System.out.println(e);
                break;
            }

        }

    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evhen, 2016-08-10
@Millerish

And who will create the array?
int[]mass; is a reference to an array which is null, which means that any access to it, such as mass.length or mass[0] will result in a NullPointerException. You are trying to find out the length or access the null element of an array that does not exist.
this.mass[mass.length+1] = e; - what are you trying to do? Assign a value to an array cell that is outside the array size....get another exception.
An array is a fixed length structure, i.e. you cannot reduce or increase its size, only re-create and copy elements from the old to the new one.
An array index can take a value from 0 to length - 1.
In general, carefully read the entire chapter on arrays...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question