Java Program To Input a Number and Display Its Square

By | June 30, 2019

Task: Write a Java Program To Input a Number and Display Its Square. The sample run of the required Java program is shown in the image below:

Output of java program to find square of a number

Output of java program to find square of a number

Stop Here, Please, Click to Read : Getting input from keyboard in Java, first

For getting input in a Java program, we may use the Scanner class. Please click on the above heading to read the complete input process step by step with images and the sample Java program.

The Source code of Java Program to input a number and calculate its square

/*
 This is Java Program to input
 a number from user through keyboard
and display its square.
 */
package numsquare;
/**
  * @author www.EasycodeBook.com
 */
// step 1 for keyboard input -
// import Scanner class
import java.util.Scanner;
public class NumSquare {
   public static void main(String[] args) {
       int num, square;
       // step 2 for keyboard input
       // create an object let "keyboard" of Scanner class
       // by passing it System.in (standard system input device)
       Scanner keyboard = new Scanner(System.in);
       //Step 3
       // Show message to enter data
       System.out.print("Enter a number to calculate square=");
        //Step 4 for keyboard input
       // call nextInt() method to initiate integer input
       num = keyboard.nextInt();
       square = num * num;
       System.out.print("Square = " + square);
             
    }
    
}

The Source code without comments of Java Program to find square of a number

package numsquare;
import java.util.Scanner;
public class NumSquare {
   public static void main(String[] args) {
       int num, square;
       Scanner keyboard = new Scanner(System.in);
       System.out.print("Enter a number to calculate square=");
 
       num = keyboard.nextInt();
       square = num * num;
       System.out.print("Square = " + square);
             
    }
    
}

Output and sample run of Java Square of number program

Loading

3 thoughts on “Java Program To Input a Number and Display Its Square

  1. Pingback: Java Program To Check a Number is Prime or Composite » EasyCodeBook.com

  2. Pingback: Write and Execute First Java Program in NetBeans » EasyCodeBook.com

  3. Pingback: Get Keyboard Input in Basic Java Program | EasyCodeBook.com

Leave a Reply

Your email address will not be published. Required fields are marked *