Page 1 of 1

About Question enthuware.ocajp.i.v8.3.1487 :

Posted: Wed May 31, 2017 7:43 am
by DonkeyHot
The question is:
What will the following code print when compiled and run?

Code: Select all

public class Data{
    int value;
    Data(int value){
        this.value = value;
    }
    public String toString(){ return ""+value; }
    
    public static void main(String[] args) {
        Data[] dataArr = new Data[]{ new Data(1), new Data(2), new Data(3), new Data(4) };

        List<Data> dataList = Arrays.asList(dataArr); //1

        for(Data element :  dataList){

            dataList.removeIf( (Data d) -> { return d.value%2 ==  0; } );  //2

            System.out.println("Removed "+d+", "); //3
        }
   }      
}
The correct answer is "It will not compile due to //1" instead of "It will not compile due to //3"

You missed an import statement in question body.

Compilation error on line //1 : List can not be resolved to a type.

Re: About Question enthuware.ocajp.i.v8.3.1487 :

Posted: Wed May 31, 2017 12:42 pm
by admin
Oracle has explicitly mentioned in its exam guidelines that if the code listing does not include import statements, you should assume appropriate import statements.


HTH,
Paul.

Re: About Question enthuware.ocajp.i.v8.3.1487 :

Posted: Tue Oct 10, 2017 7:53 am
by JuergGogo

Code: Select all

import java.util.*;

public class Data  {
    int value; 
    Data(int value) {         
        this.value = value;     
    }     
    public String toString() { return ""+value; }          
    
    public static void main(String[] args) {         
//      Data[] dataArr = new Data[] { new Data(1), new Data(2), new Data(3), new Data(4) };        
//      List<Data> dataList = Arrays.asList(dataArr); //1

        List<Data> dataList = new ArrayList<>();
        dataList.add(new Data(1));  dataList.add(new Data(2));
        dataList.add(new Data(3));  dataList.add(new Data(4));
        
        System.out.println("Origin " + dataList);
        dataList.removeIf( d -> d.value%2 ==  0 ); //2
        System.out.println("Result " + dataList);
    }       
}
Without an array backing the List, the code is working fine. This is a rather difficult question...