Implicit narrowing and arrays

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
zuzu007
Posts: 12
Joined: Mon Sep 09, 2019 2:08 pm
Contact:

Implicit narrowing and arrays

Post by zuzu007 »

Hi! I have a big problem with implicit narrowing/widening. I read it on the forum your explanations but I still can't figure out if I know well:

So, given:

class EJavaGuruArray {
public static void main(String args[]) {
int[] arr = new int[5];
byte b = 4; char c = 'c'; long longVar = 10;
arr[0] = b;
arr[1] = c;
arr[3] = longVar;
System.out.println(arr[0] + arr[1] + arr[2] + arr[3]);
}
}

The code won't compile because of arr[3] = longVar. So, implicit narrowing can't be made for arrays (the array is of type int and the primitive variable is of type long). But widening is ok for arrays (if I delete the line with arr[3] = longVar, the output is 103 (4 + 99). Is that correct?

But what about that:

ArrayList<Long> lst = new ArrayList<>(); <- error (int converting in Long)
lst.add(10);

or:

ArrayList<long> lst = new ArrayList<>(); <- error (implicit widening: int converting in long)
lst.add(10);

ArrayList<int> lst = new ArrayList<>(); -> error (required: reference, found: int) ??? I don't understand that.
lst.add(10);

But if I change it like that will compile:

package cap4;
import java.util.ArrayList;
class AppendStringBuiler2 {
public static void main(String args[]) {
ArrayList<int> lst = new ArrayList<>();
Integer a = 10;
lst.add(a); -> error (required: reference, found: int)
}
}

ArrayList<Integer> lst = new ArrayList<>(); -> compile (autoboxing is ok)
lst.add(10);

or:

ArrayList<Long> lst = new ArrayList<>(); -> compile (unboxing is ok)
long a = 10;
lst.add(a);

So, autoboxing/unboxing is accepted with arrays but implicit widening/narrowing don't? :?

admin
Site Admin
Posts: 10404
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: Implicit narrowing and arrays

Post by admin »

Implicitly narrowing is not about arrays but about type of the value and type of the variable. If the value is a compile time constant and can fit into the type of the variable (or an array element), then implicit narrowing will happen.

You might want to read about implicit narrowing from a good book. For example, "Section 3.3.3 Assigning values to variables" of this book explains this whole topic in details: https://amzn.to/2Up2ZUk

zuzu007
Posts: 12
Joined: Mon Sep 09, 2019 2:08 pm
Contact:

Re: Implicit narrowing and arrays

Post by zuzu007 »

Thank you!

Post Reply

Who is online

Users browsing this forum: No registered users and 12 guests