java

Number Class in Java

Usually in Java when we work with numbers, we will represent these numbers with any of the available primitive data type, such as int, byte, long, short, double, float.

Example

int x = 50;
float y = 50.2f;
byte z = 4;

But, there could sometimes be special situations where we will need to use objects instead of the primitive data types.

Java provides a sleek way of achieving that with Wrapper Classes.

What is a Wrapper Class?

Wrapper classes, which include Integer, Long, Short, Byte, Float and Double are actually subclasses of the Number Class.

the object of the wrapper class wraps whatever data type is passed into it, and when we convert primitive data types like this into objects, it is known as boxing.

The Wrapper Class is also converted back to the respective data type, and this is known as unboxing.

Example of boxing

public class NumberClass{
public static void main(Strings args[]){
Double x = 4.5; //boxes double to Double object
x = x + 4.5; //unboxes Double to primitive double
System.out.println(x); //9
}
}

Number Methods

There are more than 20 Number Methods that can be used in Java, but we’ll take examples of some of these methods and see how they are used:

1. equals():

This method determines whether the Number object that invokes the method is equal to the object that is passed as an argument.

public class Test{
public static void main(String args[]){
Integer x = 5;
Integer y = 10;
System.out.println(x.equals(y));
}
}

2. toString():

This returns a String object representing the value of the integer.

 System.out.println(x.toString());

3. round():

This method returns the closest long or int as given by the method’s return type. It takes a double of float.

Math.round(45.5575565);
Share
Published by
codeflare

Recent Posts

Google Announces that AI-developed Drug will be in Trials by the End of the Year

Isomorphic Labs, a drug discovery start-up launched four years ago and owned by Google’s parent…

1 hour ago

Instagram Extends Reels Duration to 3 Minutes

Regardless of whether TikTok faces a U.S. ban, Instagram is wasting no time positioning itself…

2 days ago

AWS Expands Payment Options for Nigerian Customers, Introducing Naira (NGN) for Local Transactions

Amazon Web Services (AWS) continues to enhance its customer experience by offering more flexible payment…

6 days ago

Why JavaScript Remains Dominant in 2025

JavaScript, often hailed as the "language of the web," continues to dominate the programming landscape…

1 week ago

Amazon Moves to Upgrade Alexa with Generative AI Technology

Amazon is accelerating efforts to reinvent Alexa as a generative AI-powered “agent” capable of performing…

1 week ago

Smuggled Starlink Devices Allegedly Used to Bypass India’s Internet Shutdown

SpaceX's satellite-based Starlink, which is currently unlicensed for use in India, is reportedly being utilized…

1 week ago