Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variables type after math actions

I have a question about variable types in Java. If I have a long variable (called x) and an int variable (called y), what's the type of (x/y)?

I've tried to use the "instanceof" option but it didn't helped me.

IMO It's long but I just want to be sure. Thanks in advance!

like image 692
user3623297 Avatar asked Jun 25 '26 04:06

user3623297


1 Answers

A long/int is an long due to widening rules which is basically the result of any two values is the "widest" in terms of range of either of them. Types byte, short and char are cast to an int in any operation with another number. (But not a String like String + char)

Note: long % int is also a long even though it couldn't possibly be outside the range of an int Similarly int / long is a long even though it can only be in the range of an int

Note2: int * int is still an int even though there is a good chance of an over flow.

You can only use instanceof on Object instances. Primitives are not instances.


You might find these methods useful

public static void main(String... ignored) {
    System.out.println("2 / 1L is " + toString(2 / 1L));
}

public static String toString(boolean b) {
    return "boolean " + b;
}

public static String toString(byte b) {
    return "byte " + b;
}

public static String toString(char x) {
    return "char " + x;
}

public static String toString(short x) {
    return "short " + x;
}

public static String toString(int x) {
    return "int " + x;
}

public static String toString(long x) {
    return "long " + x;
}

public static String toString(float x) {
    return "float " + x;
}

public static String toString(double x) {
    return "double " + x;
}

prints

2 / 1L is long 2
like image 96
Peter Lawrey Avatar answered Jun 27 '26 20:06

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!