Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing char into a method with an int parameter

The output from the following code is 123 because substring takes from beginIndex to EndIndex - 1. However, I am surprised how char here is understood as 3 (int) because substring take two ints. What is the concept behind this?

String x = "12345";
char a = 3;
x = x.substring(0, a);
System.out.println(x);
like image 989
Hussein Zawawi Avatar asked Oct 28 '11 16:10

Hussein Zawawi


2 Answers

This goes all the way back to C, where char is in essence a narrow integer type and gets implicitly converted to int whenever necessary.

In Java, this is technically known as a "widening primitive conversion", and is covered in section 5.1.2 of the JLS.

like image 55
NPE Avatar answered Sep 19 '22 06:09

NPE


Others already explainted why it works but note that it is bad practice to use char variables for indices, since they have different associated semantics and thus it is confusing to use a char as an index.

Use chars only to store character data and probably better: try to avoid char altogether, since they are not even wide enough to store every character (see Unicode and code point discussion). Use int to store character code points instead.

like image 36
Puce Avatar answered Sep 21 '22 06:09

Puce