-6

When I run my code it gives me an error as follows:

 Exception in thread "main" tony
 java.lang.ArrayIndexOutOfBoundsException: 1
 at tt.main(tt.java:17)

The code is as follows:

import java.util.ArrayList;
import java.util.Arrays;

public class tt {


   static int oldAge[];
   static Integer ages[];
   static ArrayList<Integer> ageObject;

public static void main(String args[]){

    System.out.println("tony");
    setAges();


        System.out.println(ages[1].intValue());
    System.out.println(oldAge[2]);



   }

   public static void setAges(){


    oldAge = new int[3];

     oldAge[0] = 50;
     oldAge[1] = 60;
     oldAge[2] = 70;

     ages = new Integer[1];
     ages[0] = 50;

     ageObject = new ArrayList<Integer>(Arrays.asList(ages));

 for(int x =0; x < oldAge.length; x++){

  if(oldAge[x] == 60){
    ageObject.add(oldAge[x]);
 }
  else if(oldAge[x] == 56){
    ageObject.add((Integer)(oldAge[x]));
 }
  else if(oldAge[x] == 70){
    ageObject.add((Integer)(oldAge[x]));
 }



       }

     }

  }

I want the code to to print the newly added value of ages which is supposed to be 60.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
tony rox
  • 37
  • 3
  • 5
    Why did you say `NullPointerException` in your title if you are actually getting an `ArrayIndexOutOfBoundsException`? – khelwood Nov 02 '18 at 22:43

1 Answers1

2

This line

System.out.println(ages[1].intValue());

is incorrect. ages is exactly one element. It should be

System.out.println(ages[0].intValue());

with no other changes I get

tony
50
70

To get 60, you would need to print the second element of oldAge. Like,

System.out.println(oldAge[1]);
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249