java code for square

java code for square

Here is a simple example of Java code that calculates the square of a number:

refer to:‮ruttual‬i.com
public class Main {
  public static void main(String[] args) {
    int n = 5;
    int squared = n * n;

    System.out.println("The square of " + n + " is " + squared);  // Outputs: "The square of 5 is 25"
  }
}

In this example, the n variable is initialized with the value 5, and the squared variable is calculated as the square of n. The result is then output to the console using the println method.

You can use a similar approach to calculate the square of any other number. For example, to calculate the square of a number read from the user:

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    System.out.print("Enter a number: ");
    int n = scanner.nextInt();
    int squared = n * n;

    System.out.println("The square of " + n + " is " + squared);

    scanner.close();
  }
}

In this example, the Scanner class is used to read an integer from the user, and the nextInt method is used to parse the input. The square of the integer is then calculated and output to the console using the println method.

Created Time:2017-11-03 00:14:50  Author:lautturi