CodeGym /Java Blog /Java Numbers /How to Square a Number in Java
Author
Volodymyr Portianko
Java Engineer at Playtika

How to Square a Number in Java

Published in the Java Numbers group

What is the “square” of a number?

In mathematics or algebra, you can find the “square” of a number, by multiplying the same number with itself. For example, the square of 2 is 4, and the square of 3 is 9.

How to square a number in Java?

There are different ways of computing the square of a number in Java, but let’s start with the simplest method. Have a look at the following example for better understanding.

Example 1


package com.square.java;
public class AlgebricSquare {

	public static int getSquare(int number) {
		return number * number;
	}
	
	public static void main(String[] args) {
		
		int number = 2;	
		System.out.println("Square of " + number + " is: " + getSquare(number));

		number = 5;	
		System.out.println("Square of " + number + " is: " + getSquare(number));
		
		number = 7;	
		System.out.println("Square of " + number + " is: " + getSquare(number));
	}
}

Output

Square of 2 is: 4 Square of 5 is: 25 Square of 7 is: 49

Explanation

In this example, we have created a simple method getSquare() taking one integer as a parameter. The method returns an integer after multiplying it with self. So we get the square of the number passed as a parameter in line 11, 14 and 17 of example 1.

Example 2


package com.square.java;
public class MathSquare {

	public static final Integer POW = 2;
	public static Double getSquare(Double number) {
		return Math.pow(number, POW);
	}
	
	public static void main(String[] args) {
		
		Double number = 3.5;	
		System.out.println("Square of " + number + " is: " + getSquare(number));

		number = 11.1;	
		System.out.println("Square of " + number + " is: " + getSquare(number));
		
		number = 13.0;	
		System.out.println("Square of " + number + " is: " + getSquare(number));
	}
}

Output

Square of 3.5 is: 12.25 Square of 11.1 is: 123.21 Square of 13.0 is: 169.0

Explanation

In this example, we have used Math.pow(number, POW) method provided by Java to multiply the number with itself to the times “POW” is passed. You can use this method to find “cube” or up to any power specified.

Conclusion

By the end of this post, your query of how to square a number in Java should have been resolved. However, you can get more grab of this by practice. Keep learning & happy coding!

More reading:

Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION