Java Programming - Declarations and Access Control - Discussion


What is the widest valid returnType for methodA in line 3?

public class ReturnIt 
    returnType methodA(byte x, double y) /* Line 3 */
        return (long)x / y * 2; 

[A]. int
[B]. byte
[C]. long
[D]. double

Answer: Option D


However A, B and C are all wrong. Each of these would result in a narrowing conversion. Whereas we want a widening conversion, therefore the only correct answer is D. Don't be put off by the long cast, this applies only to the variable x and not the rest of the expression. It is the variable y (of type double) that forces the widening conversion to double.

Java's widening conversions are:

- From a byte to a short, an int, a long, a float, or a double.

- From a short, an int, a long, a float, or a double.

- From a char to an int, a long, a float, or a double.

- From an int to a long, a float, or a double.

- From a long to a float, or a double.

- From a float to a double.

Hemavathy said: (Apr 2, 2012)  
Can you please explain this in brief? I am new to java programming. What do you mean by narrowing conversion and widening conversion?

Amaz said: (Apr 24, 2012)  
First you learn the type casting in java.mainly there are two types of type-castings are available,these are up-casting and down-casting
For example.
public class a{
int b = 5;
double c = b;
/*(up-casting) putting smaller data types into the bigger one
up-casting is implicitly done.
int is of 4-bytes can be easily cast on 8-bytes double*/

double d = 5;
int e = (int)d;
/*(down-casting)casting bigger data types into smaller one.
In this loss of information occur which must be implicitly
declare to compile the program in this Example we are
declaring the type of e as (int)*/


This leads a concept of narrowing and widening conversion hope you get the answer.

Sagar said: (Mar 1, 2014)  
What is the narrowest return type of the main written program?is it double or int?

Paul said: (Nov 23, 2015)  
Please tell: By "widest valid returnType" do you mean the largest number of bits in the return type? If so, both "long" and "double" are 64 bits.

It seems either of these answers are valid for the question. Please correct me and explain.


Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.