How to Square a Number in Java
Yes, we use math in Java! This lesson will explain how to square a given number in Java and provide working code examples that highlight this key math function.
Math in Java
Yes, it might be a shock, but there is math in programming. Joking aside, you’ll discover that numerous mathematical concepts are used when developing applications. If you’ve ever wondered when you’d use advanced math and algebra in the real world, here is your answer.
This lesson will cover the square function. This can be explained in two ways: we can describe it as multiplying a number by itself or as raising a number to the second power. Once you’ve learned the functions in this lesson, you’ll be able to go beyond squaring numbers and raise them to other powers.
Option 1: Squaring a Number
If you need to square a number, a very simple solution is to just multiply the number by itself. After all, 52 is really 5 * 5. In this instance, it’s totally acceptable to multiply a number by itself, although there is another tool that will achieve this purpose.
Below is the basic Java code to square the number 5.
//Square a Number
double x = 5;
double z = x * x;
System.out.println(z);
The output of this code is below, which says, as you can see:
Java square basic output
We’ll talk about data types in a couple moments, but you’ll notice that we made x into a double, even though it’s a 5. When we start using other powers and squaring larger numbers, it’s good to have room to grow. If we’re absolutely sure that the number will be an integer, we can declare them as the long data type instead.
Option 2: Math.pow()
While the previous code is legal and compiles, there’s a delivered math function we can use. In fact, it’s a good idea to use this function, because it works for raising numbers to any chosen power. Java’s Math.pow() function takes two parameters: the number being modified, and the power by which you are raising it. In our case here, it’ll be 2.
//Square a number using pow
double squareme = 52;
double result = Math.pow(squareme, 2);