Boxing Unboxing Var-args em métodos + Exercicios

2 respostas
iwallas

Tah tah… por hj é a ultima… ehehe

/* Classe que cobre uma parte do objetivo 3.1 do Exame SCJP 5
 *  - Boxing, Unboxing, Var-args E Widening com Overloading de métodos
 *  - Comentários adicionais no final do documento.
 * @author Wallas dos Santos Souza [email removido]
 * @since 15 de Dezembro de 2006
*/

class BoxUnBoxVarArgs {
	
	public void go(Short...s){
		for(int i=0;i<s.length;i++)
		   System.out.print(s[i] + " ");
		System.out.println("Short ... Pai");
	}
	
	public void go(short s){
		System.out.println(s + ": short Pai");
	}
}

class BoxLittle extends BoxUnBoxVarArgs{
	
	public void go(Short s){
		System.out.println(s + ": Short Filho");
	}
	
	public void go(Short...s){
		for(int i=0;i<s.length;i++)
		   System.out.print(s[i] + " ");
		System.out.println("Short ... Filho");
	}
	
	public void go(short s, short s1){
		System.out.println(s + "," + s1 + ": short, short Filho");
	}
	
	public void go(short...s){
		for(int i=0;i<s.length;i++)
		   System.out.print(s[i] + " ");
		System.out.println("short ... Filho");
	}
	
	public void go(long s){
		System.out.println(s + ": long Filho");	
	}
	
	public void go(Integer s){
		System.out.println(s + ": Integer Filho");	
	}
	
	public static void main(String[] args){
		
		BoxLittle bl = new BoxLittle();
		short s1 = 2;
		
		bl.go(0);
		bl.go(new Short("1"));
		bl.go(s1);
		bl.go(s1,s1);
		bl.go(new Short("1"),new Short("1"));
		bl.go(s1,new Short("1"));
		
		/*
		0: long Filho - prefere fazer widening(alargamento), ou seja,
		                melhor aumentar de int para long do que fazer
		                boxing de int para Integer;
		1: Short Filho - pega o go() desta classe;
		2: short Pai - pega o go() da classe BoxUnBoxVarArgs (pai);
		2,2: short, short Filho - prefere este do que fazer boxing ou var-args;
		1,1: short, short Filho - prefere fazer boxing do que var-args;
		2,1: short, short Filho - passa o 1º parametro e faz boxing do 2º;
		
		Prioriadades: 
		
		 1º  Prefere fazer alargamento do que var-arg;
         2º  Prefere fazer alargamento do que boxing;
         3º  Se houver herança, prefere pegar o método que "alarga" da classe pai
             do que fazer boxing ou var-arg na classe atual;
         4º  Prefere fazer boxing do que var-arg, ou seja var-arg só em ÚLTIMO CASO!;
		
		Erro 1: passar vários parametros:
		
		  bl.go(new Short("1"),new Short("1"),new Short("1"),new Short("1"));
		    ou
		  bl.go(s1,s1,s1,s1);
		  
		  neste caso há 4 parâmetros, e o compilador pode optar por:
		    1 - public void go(Short...s) 
		    2 - public void go(short...s)
		  E esta opção gera erro de compilação! neste caso só um método seria aceito.
	  */	  
	}
	
}

2 Respostas

iwallas

Questões Var-args:

  1. What is the result of compiling and running the following code?
    class VarArgOne {
    public static void printArgs(String s, Integer … i, String s) { //line 1
    for(int j : i) { //line 2
    System.out.print(j + " " + s); //line 3
    }
    }
    public static void main(String … args) { //line 4
    printArgs(“exam”, 12, 34, “scjp”); //line 5
    }
    }

Options :

a) Compilation fails due to error at line 1.
b) Compilation fails due to error at line 2.
c) Compilation fails due to error at line 4.
c) Compilation fails due to error at both line 1 and line 4.
d) Compiles fine and Prints output “12 scjp 34 scjp”.

Answer :
A is the correct answer.
The var-arg must be the last parameter in the method’s signature. Here it is followed by another argument.
B is incorrect, var-args variable can be used in enhanced for loop(Tiger loop).
c is incorrect, we can use var-args in the place of String [] in main method.

  1. what are the lines can be independently inserted there to make code compiles and run sucessfully.
    
    class VarArgTwo {
    
    public static void countValue(Double  dd) {
    
    double ddd = 0.0;
    
    for (double d : dd) {
    
    ddd += d;
    
    }
    
    System.out.println("count : " + ddd);
    
    }
    
    public static void main(String[] args) {
    
    // insert the method call here
    
    }
    
    }
    

    Options :

    a) countValue();
    
    b) countValue(10 , 33.1);
    
    c) countValue(12.3, 15.6);
    
    d) countValue(20, 50, 45.5);
    
    e) All the above.
    

    Answer :
    A and C are the correct answers.
    A is correct because var-args will accept 0 to n arguments.
    C is valid, there method is invoked with 2 double as arguments.
    B and D are invalid, because it contains int in its method arguments.

  2. What is the result of compiling and running the following code?
    
    class VarArgThree {
    
    public void invoke(Integer j, int  i) {
    
    System.out.println(Var-args and Integer invoked);
    
    }
    
    public void invoke(Integer i, Integer j) {
    
    System.out.println(Integer and Integer invoked);
    
    }
    
    public static void main(String[] args) {
    
    new VarArgThree().invoke(10, 20);
    
    }
    
    }
    

    Options :

    a) compiles fine and produces output “Var-args and Integer invoked”.
    b) compiles fine and produces output “Integer and Integer invoked”.
    c) compilation fails due to ambiguous method call.
    d) Compilation will suceed only when invoke method changed with 3 integer arguments.
    e) none of the above.

    Answer :
    B is the correct answer.
    If Var-Args is present as a method parameter then, It will have the least precedence.
    So, In this case method with two Integer as parameter is invoked.

  3. what are the lines can be independently inserted in to the blank to make code compiles and run sucessfully.
    
    class VarArgFour {
    
    public static void display( _______________________) {
    
    System.out.println(Hi, I am here);
    
    }
    
    public static void main(String[] args) {
    
    display(25, 50, scjp, exam);
    
    }
    
    }
    

    Options :

    a) Integer … i, String … s
    b) Integer i1, Integer i2, String … s
    c) Integer … i, String s1, String s2
    d) all of the above.
    e) none of the above.

    Answer :
    B is the correct answer.
    First two integer parameter will take 25, 50 respectively and var-args string parameter will take two String arguments “scjp”, “exam”.
    A is incorrect because you can have only one var-arg in a method.
    C is incorrect because var-arg must be the last parameter in the method’s signature.

  4. what is the result of compiling and running the following code?
    
    class VarArgFive {
    
    public static void checkThis(Double d1, Double  d2) {
    
    System.out.println(Double and Var-Args);
    
    }
    
    public static void checkThis(Double d1, Double d2, Double  d3) {
    
    System.out.println(Double , Double and Var-args);
    
    }
    
    public static void checkThis(double d1, Double d2, Double  d3) {
    
    System.out.println(double , Double and Var-args);
    
    }
    
    public static void main(String [] args) {
    
    checkThis(15.5, 26.6, 37.7);                    // line 1
    
    }
    
    }
    

    Options :

    a) Compiles fine and produces output “Double and Var-Args”.
    b) Compiles fine and produces output “Double , Double and Var-args”.
    c) Compiles fine and produces output “double , Double and Var-args”.
    d) Compilation fails.
    e) Compilation suceeds only when line 1 is removed.

    Answer :
    D and E are Correct answer.
    D is valid. Since all the method declaration have var-args in it, compilation will fails saying ambiguous method call.
    E is correct. Since according to overloading rules checkThis() method is overloaded properly but method call is the reason for the compilation error.

  5. what is the result of compiling and running the following code?
    
    class VarArgSix {
    
    public static void isValidMethod(String  sv) {  //line 1
    
    String[] sa = (String[])sv;                          //line 2
    
    for(String s : sv) {                                    //line 3
    
    System.out.print(s + " ");
    
    }
    
    }
    
    public static void main(String  args) {          //line 4
    
    isValidMethod(hi, how, are, you);
    
    }
    
    }
    

    Options :

    a) Compilation error at line 1, since Var-Arg cannot be assigned to Array.
    b) Compilation error at line 2, Since Var-Arg cannot be used in Tiger for loop.
    c) Compilation error at line 3, Since Var-arg cannot be used in main method.
    d) Compiles fine and outputs “hi how are you”.
    e) ClassCastException at runtime.

    Answer :
    D is the correct answer.
    Since all are valid. We can assign Var-Arg to Array(Even without Casting), We can use Var-Arg in Tiger for loop, we can use Var-arg in main method.

  6. what are the lines that can be independently inserted in to place, so that code can compiles and run sucessfully.
    
    class Vehicle {}
    
    class Car extends Vehicle {}
    
    class VarArgSeven {
    
    public static void washVehicle(Vehicle  v) {
    
    for(Vehicle vv : v) {
    
    Car c = (Car)vv;
    
    System.out.print©;
    
    }
    
    }
    
    public static void main(String[] args) {
    
    //insert the line here
    
    }
    
    }
    

    Options :

    a) washVehicle(new Car[] { new Car()});
    
    b) washVehicle(new Vehicle[]{new Car(), new Vehicle()});
    
    c) washVehicle(new Car(), new Car());
    
    d) washVehicle(new Vehicle(), new Vehicle());
    
    e) none of the above.
    

    Answer :
    A and C are the correct answers.
    Array can be passed as an argument to call the method having parameter taking var-args.
    B and D also can be inserted in the place, so the code will compiles fine. But it will throw ClassCastException because of casting done in washVehicle() method.

  7. what is the result of compiling and running the following code?
    
    class Fruit {}
    
    class  Apple extends Fruit {}
    
    class VarArgEight {
    
    public static void invokeMe(Fruit  f) {
    
    System.out.print(Fruit Var-Args + " ");
    
    }
    
    public static void invokeMe(Apple  f) {
    
    System.out.print(Apple Var-Args + " ");
    
    }
    
    public  static  void  invokeMe(Apple[] a) {
    
    System.out.print(apple array + " ");
    
    }
    
    public static void invokeMe(Fruit[] f) {
    
    System.out.print(fruit array + " ");
    
    }
    
    public static void main(String[] args) {
    
    invokeMe(new Fruit[] {new Apple(), new Fruit()});
    
    invokeMe(new Apple[] {new Apple(), new Apple()});
    
    }
    
    }
    

    Options :

    a) Compiles fine and prints output "apple array fruit array"
    b) Compiles fine and prints output "fruit array apple array"
    c) Compiles fine and prints output "fruit Var-Args apple Var-Args"
    d) Compiles fine and prints output "apple Var-Args fruit Var-Args"
    e) Compilation fails.

    Answer :
    E is the correct answer.
    Since compiler will view “var-args” and “array” as similar one. So it will not allow to declare a method with Array type as parameter, when it has var-args
    of same type in it.

  8. What are the valid declaration of var-args for a method?

    Options :
    
    a) void calculate(int x) { }
    
    b) void evaluate(int x) { }
    
    c) void combine(int x, char y) { }
    
    d) void checkDog(Dog d) { }
    
    e) void doThis(String s, byte b)
    
    f) void printThis(Car c, int x) { }
    

    Answer :
    A, D and F are the correct answers.
    B is wrong because of invalid var-args syntax.
    C is wrong because there can be only one var-arg parameter type in a method.
    E is wrong because var-arg must be the last parameter in the method declaration.

  9. what is the result of compiling and running the following code?
    
    class VarArgTen {
    
    public static void countValue(Double  dd) {
    
    for(int i=0; i < dd.length; i++) {             //line 1
    
    System.out.print(dd[i] + " ");                   //line 2
    
    }
    
    }
    
    public static void main(String[] args) {
    
    countValue(12.4, 45.6);
    
    }
    
    }
    

    Options :

    a) Compilation fails due to error at line 1 only.
    b) Compilation fails due to error at line 2 only.
    c) Compilation fails due to error at line 1 and line 2.
    d) Compilation suceeds and prints output “12.4 45.6”.
    e) Exception will be thrown at runtime.

Answer :
D is the correct answer.
Since var-args will be treated as arrays. The variable "length" will be available in it and also can be accessed with index as normal array variable.

Fonte: javabeat.net

iwallas

Boxing e Unboxing

Question 1

public class Boxing1 {

public static void main(String[] args) {

Integer i = null;

method(i);

}

static void method(int k){

System.out.println(k);

}

}

What is the output of the above program?
1)Null Pointer Exception
2)Number Format Exception
3)null
4)0

Question 2

public class Boxing2 {

public static void main(String[] args) {

byte b = 10;

method(b);

}

static void method(int i){

System.out.println(Primitivae Type call);

}

static void method(Integer i){

System.out.println(Wrapper Type Call);

}

}

What will be output for the above program?
1)Wrapper Type Call
2)Primitive Type Call
3)Compiler Error
4)Compiles fine, throws runtime exception

Question 3

public class Boxing3 {

public static void main(String[] args) {

int i = 10;

method(i);

}

static void method(Long l){

System.out.println(Widening conversion);

}

}

What will be output for the above program?
1)Widening conversion
2)Compiler Error
3)Runtime Exception
4)0

Question 4

public class Boxing4 {

public static void main(String[] args) {

Integer i = 10;

Integer j = 10;

System.out.print(i==j);

System.out.print(i.equals(j));

}

}

What will be output for the above program?
1)falsefalse
2)truetrue
3)truefalse
4)falsetrue

Question 5

public class Boxing5 {

public static void main(String[] args) {

Integer i = 200;

Integer j = 200;

System.out.print(i==j);

System.out.print(i.equals(j));

}

}

What will be output for the above program?
1)falsefalse
2)truetrue
3)truefalse
4)falsetrue

Question 6

public class Boxing6 {

public static void main(String[] args) {

Boolean b1 = new Boolean(true);

Boolean b2 = new Boolean(true);

boolean b3 = true;

Boolean b4 = true;

System.out.println(b1==b2);

System.out.println(b1==b3);

System.out.println(b3 == b4);

System.out.println(b1 == b4);

}

}

What is the output for the above program?
1)false true true false
2)false false false false
3)true true true true
4)false false true true

Question 7

public class Boxing7 {

public static void main(String[] args) {

int i = 10;

method(i);

}

static void method(long l){

System.out.println(long called);

}

static void method(Integer i){

System.out.println(Integer called);

}

}

What will be the output for the above program?
1)long called
2)Integer called
3)Compiler error
4)Runtime exception

Question 8

public class Boxing8 {

public static void main(String[] args) {

Integer i = 10;

int k = 10;

method(i,k);
}   
static void method(int i,Integer k){
    System.out.println("int,Integer called");
}
static void method(int i,int k){
    System.out.println("int,int called");;
}
static void method(Integer i,Integer k){
    System.out.println("Integer,Integer called");;
}
static void method(Integer i,int k){
    System.out.println("Integer,int called");;
}

}

What will be the output for the above program?
1)int,Integer called
2)Integer,int called
3)int,int called
4)Integer,Integer called

Question 9

public class Boxing9 {

public static void main(String[] args) {

int i = 10;

method(i);

}

static void method(Object o){

System.out.println(Object called);

}

static void method(Number n){

System.out.println(Number called);

}

}

What will be the output for the above program?
1)Object called
2)Number called
3)Compiler Error
4)Runtim Exception

Question 10

public class Boxing10 {

public static void main(String[] args) {

int i = 10;

int k = 20;

method(i,k);

}

static void method(Integer i){

System.out.println(Integer varargs is called);

}

static void method(Integer i,Integer j){

System.out.println(Integer,Integer is called);

}

static void method(int i){

System.out.println(int varargs is called);

}

}

What will be the output for the above program?

1)Integer varargs is called
2)Integer,Integer is called
3)int varargs is called
4)Compiler Error

Answers

  1. 1)Null Pointer Exception

    Explanation :
    When wrapper type is null, we cannot do the boxing conversion. It will throw the NullpointerException when its is trying the convert to primitive type.

  2. 2)Primitive Type Call

    Explanation :
    When comes to method overloading in Java 5.0, it works like the previous versions. First JVM will check for the matching primitive types, then it will search for the Wrapper types.

  3. 2)Compiler Error

    Explanation :
    Primitive tpes cannot be widened to the Wrapper classes. This behaviour is restricted in Java 5.0.

  4. 2)truetrue

    Explanation :

Consider the following code fragment:

Integer i1 = 100;

Integer i2 = 100;

Integer i3 = 1000;

Integer i4 = 1000;

System.out.println(i1==i2);

System.out.println(i3==i4);

Can you guess what will be printed on the screen? If your answer is false–well, you’re wrong.

In this case, J2SE 5.0 works differently. Certain ranges of values are stored as immutable objects by the Java Virtual Machine. So, in this case, the output is:

true
false

Normally, when the primitive types are boxed into the wrapper types, the JVM allocates memory and creates a new object. But for some special cases, the JVM reuses the same object.

The following is the list of primitives stored as immutable objects:

* boolean values true and false
* All byte values
* short values between -128 and 127
* int values between -128 and 127
* char in the range \u0000 to \u007F
  1. 4)falsetrue

    Explanation :
    When you assign a primitive to wrapper, compiler still creates a new object and assign into the same.

  2. 1)false true true false

  3. 1)long called
    Explanation:
    Method overloading gives preference to the primitive types.

2)Integer,int called
2)Number Called
Explanation:  The int i was boxed to a Integer.The Integer reference was widened to an Object (since Integer extends Object).The method() method got an Number reference that actually refers to a Integer object.
2)Integer,Integer is called
  Explanation : Compiler will check for the matching method signature then it look for the
 varargs method. This intend to maintain the behaviour of the previous versions.

fonte: javabeat.net

Criado 6 de fevereiro de 2007
Ultima resposta 6 de fev. de 2007
Respostas 2
Participantes 1