Page 1 of 1

Implicit narrowing and arrays

Posted: Sun Sep 22, 2019 7:17 am
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? :?

Re: Implicit narrowing and arrays

Posted: Sun Sep 22, 2019 10:42 am
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

Re: Implicit narrowing and arrays

Posted: Sun Sep 22, 2019 11:26 am
by zuzu007
Thank you!