Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
439 views
in Technique[技术] by (71.8m points)

type conversion - Java char is also an int?

I was trying to get some code done for class:

public int getValue(char value) {
    if (value == 'y') return this.y;
    else if (value == 'x') return this.x;

Since I might not be able to return anything in the end, it told me to do this at the end:

return value;

This surprised me because the return type for the method was of type int. Yet, it was telling me to return a char! I'm using eclipse, and accustomed to the endless number of warnings and stuff, this was a major surprise.

So, is a char really an int? Why is this happening?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The Java Language Specification states

When a return statement with an Expression appears in a method declaration, the Expression must be assignable (§5.2) to the declared return type of the method, or a compile-time error occurs.

where the rules governing whether one value is assignable to another is defined as

Assignment contexts allow the use of one of the following:

and

19 specific conversions on primitive types are called the widening primitive conversions:

  • char to int, long, float, or `double

and finally

A widening primitive conversion does not lose information about the overall magnitude of a numeric value in the following cases, where the numeric value is preserved exactly: [...]

A widening conversion of a char to an integral type T zero-extends the representation of the char value to fill the wider format.

In short, a char value as the expression of a return statement is assignable to a return type of int through widening primitive conversion.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...