What are the common methods in the Number class in Java?

0178

The Common Methods in the Number Class in Java

The Number class in Java is an abstract class that serves as the superclass for all numeric wrapper classes, such as Integer, Long, Float, and Double. It provides a set of common methods that can be used to perform various operations on numeric values. Here are some of the common methods in the Number class:

1. doubleValue()

This method returns the value of the Number object as a double value.

Example:

Integer i = 42;
double d = i.doubleValue(); // d will be 42.0

2. floatValue()

This method returns the value of the Number object as a float value.

Example:

Long l = 1234567890L;
float f = l.floatValue(); // f will be 1.234568E9

3. intValue()

This method returns the value of the Number object as an int value.

Example:

Double d = 3.14;
int i = d.intValue(); // i will be 3

4. longValue()

This method returns the value of the Number object as a long value.

Example:

Float f = 3.14f;
long l = f.longValue(); // l will be 3

5. byteValue()

This method returns the value of the Number object as a byte value.

Example:

Short s = 127;
byte b = s.byteValue(); // b will be 127

6. shortValue()

This method returns the value of the Number object as a short value.

Example:

Integer i = 32767;
short s = i.shortValue(); // s will be 32767

7. compareTo(Number obj)

This method compares this Number object to the specified Number object. It returns a negative integer, zero, or a positive integer as this number is less than, equal to, or greater than the specified number.

Example:

Integer i1 = 42;
Integer i2 = 24;
int result = i1.compareTo(i2); // result will be 1

8. equals(Object obj)

This method compares this Number object to the specified Object. It returns true if and only if the argument is not null and is a Number object that contains the same value as this object.

Example:

Integer i1 = 42;
Integer i2 = 42;
boolean result = i1.equals(i2); // result will be true

These are some of the common methods in the Number class in Java. The Number class provides a set of utility methods that can be used to perform various operations on numeric values, making it a useful class for working with numbers in Java.

graph TD Number --> doubleValue Number --> floatValue Number --> intValue Number --> longValue Number --> byteValue Number --> shortValue Number --> compareTo Number --> equals

0 Comments

no data
Be the first to share your comment!