0% found this document useful (0 votes)
120 views5 pages

Java Program for Adding Two Numbers

This document discusses two Java programs to calculate the sum of two numbers. The first program hardcodes the numbers, while the second program takes numbers as input from the user. It also explains how to calculate the area of a circle in Java using a static method, importing the Scanner class to take user input, and applying the formula for area of a circle which represents Pi as 22/7. The document provides line-by-line explanation of the code to demonstrate how it works.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
120 views5 pages

Java Program for Adding Two Numbers

This document discusses two Java programs to calculate the sum of two numbers. The first program hardcodes the numbers, while the second program takes numbers as input from the user. It also explains how to calculate the area of a circle in Java using a static method, importing the Scanner class to take user input, and applying the formula for area of a circle which represents Pi as 22/7. The document provides line-by-line explanation of the code to demonstrate how it works.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Program to Add two Numbers

Here we will see two programs to add two numbers, In the first program we specify the value of
both the numbers in the program itself. The second programs takes both the numbers (entered by
user) and prints the sum.

First Example: Sum of two numbers


public class AddTwoNumbers {

public static void main(String[] args) {

int num1 = 5, num2 = 15, sum;


sum = num1 + num2;

[Link]("Sum of these numbers: "+sum);


}
}

Output:

Sum of these numbers: 20

Second Example: Sum of two numbers using Scanner


The scanner allows us to capture the user input so that we can get the values of both the numbers
from user. The program then calculates the sum and displays it.

import [Link];
public class AddTwoNumbers2 {

public static void main(String[] args) {

int num1, num2, sum;


Scanner sc = new Scanner([Link]);
[Link]("Enter First Number: ");
num1 = [Link]();

[Link]("Enter Second Number: ");


num2 = [Link]();

[Link]();
sum = num1 + num2;
[Link]("Sum of these numbers: "+sum);
}
}

Output:
Enter First Number:
121
Enter Second Number:
19
Sum of these numbers: 140
Print Area Of Circle 5 Different Ways With Examples
[wp_ad_camp_3]

Below is the program to calculate the AOC in java, if you were new to java coding then we can
also share the complete step by steps with detailed explanation on how this java program works,
just below this code check it out.

1. Static Method
Static Method Program
Java
1 import [Link];
2 class AreaOfCircle
3 {
4    public static void main(String args[])
5     {  
6       
7       Scanner s= new Scanner([Link]);
8         
9          [Link]("Enter the radius:");
10          double r= [Link]();
11          double  area=(22*r*r)/7 ;
12          [Link]("Area of Circle is: " + area);      
13    }
14 }
Output:
1 Enter the radius :
27
3 Area of circle : 154.0
 

As we know that formula in math is : 

But, if you were written like that, then the system won’t understand, until and unless you assign
the value of “PIE” is 22/7.  As usual , you always represent the values in binary numbers.

The system can’t able to understand whether the given number is a number, or given letter is a
letter.  All it understood as ” Character ” or just a “ Symbol “. Here goes the complete step by
step explanation of the above code and how it works.
Step – 1:

1 import [Link];

( here ‘import’ is a keyword in java used to get features from inbuilt packages. here we using a
package called until it consists of many classes and we using one of the class Scanner to get
command over console which is the interface between user and program. )

Step – 2:

1 public static void main(String args[])

( The main function, where the execution of  program start  from here onwards )

Step – 3:

1 Scanner s= new Scanner([Link]);

( 1. The scanner is a class used to scan the input data which was given by the user through a
console.

so to get access on a console we want to create an object  Syntax:new Scanner(); after creating an
object that reference will store in variable ‘s’ )

Step – 4:

1 [Link]("Enter the radius:");

( above code is giving instructions for the user to  give the input  for radius)

Step – 5:

1 double r= [Link]();

 ( here above instruction is get input in the required format.  first we want to know about
nextDouble() method it takes a token(collection of symbols divide by white space
example:”ABC”,  “DEF” , “GHI”,”10″,”20″)

which is given by  [Link] user give 10 as input actually in user perspective  it is number but
any number or string  which entered on  console by default  those are  strings,  1o as  string but
we want  10 as  number format  for that we have method to convert string to number(Int, Double,
Float, Long…..)  some of those method are:

[Link]() ,

2 nextFloat(),
[Link](),   

[Link]()

[Link]()

[Link]() or nextString() ).

Step – 6:

1 double  area=(22*r*r)/7 ;

Step – 7: [Link](“Area of Circle is: ” + area);   ( Once, you entered the radius , the
value stored in a particular function ( nextDouble(); ) and read those values with the help of a
scanner and display the output for a given value.

A : The major difference is where double can represent the output even after the decimal point ,
whereas in ” Int ” only the numbers before decimal point will take into consideration.

Common questions

Powered by AI

A static method, like the one used in the program to calculate the area of a circle, allows the method to be called without creating an instance of the class. This means that the method belongs to the class itself rather than an object of the class. Static methods can be beneficial for utility or helper methods, which perform tasks that do not require any object state. In contrast, non-static methods require an instance of a class to be invoked and can access instance variables of the class, which is not possible with static methods .

Using 'nextDouble()' has the advantage of accommodating decimal numbers, providing greater flexibility and precision in handling user input. For example, when calculating the area of a circle, using 'nextDouble()' allows users to input the radius as a floating-point number, which is crucial for precise calculations. In contrast, 'nextInt()' can only handle integer values, which might not be suitable for all computational requirements, especially those involving measurements or calculations that depend on fractional values .

Console input allows programs to be dynamic and interact with users by asking for live inputs during runtime, making software more flexible and applicable in different scenarios. It enhances user experience by enabling customization based on user needs. Predefined values, while quicker to implement, limit the program to static inputs fixed at compile time, which could be beneficial for testing but not practical for real-world applications where inputs often vary .

Hardcoding input values can lead to inflexible programs that are non-reusable in situations where dynamic input is required. This approach also limits testing to fixed scenarios and hinders adaptability. To mitigate these issues, developers can use scanner inputs to allow interactive user data entry, enhancing flexibility and reusability. Additionally, parameterization techniques and configuration files can be employed to separate code from dynamic data, thus improving adaptability and maintainability .

In Java, arithmetic operations follow a specific order of precedence, where multiplication (*) and division (/) are performed before addition (+) and subtraction (-). Associativity for arithmetic operators is left to right, meaning in expressions with operators of the same precedence, evaluation starts from leftmost to rightmost. In the context of computing the sum of numbers, this understanding ensures that addition is conducted after any contained multiplication or division operations unless parentheses dictate otherwise. For pure addition operations, precedence affects evaluation only when combined with other operations .

Using integer division to approximate π as 22/7 is beneficial in simplifying calculations without the need for floating-point arithmetic, which can introduce rounding errors. This approach is easy to implement for quick computations. However, it significantly reduces precision, as it approximates Pi with a non-infinite range. For calculations requiring high precision, such as scientific computations, using Java’s Math.PI is preferable due to its closer approximation of the true value of π. This balance of precision versus simplicity must be considered based on the program's requirements .

The Java program ensures correct format and conversion by using specific methods provided by the Scanner class, such as nextInt() for integers and nextDouble() for floating-point numbers. These methods parse the input data from its default string type into the required primitive data types. The use of these methods ensures that user input is converted into a format that can be directly used in computations, protecting the program from type mismatch errors .

The 'Scanner' class in Java is used to capture user input by creating an instance that reads from the standard input stream (System.in). This allows the program to interactively prompt the user for input values during execution, which makes programs dynamic and responsive to user inputs. It also has methods like nextInt() and nextDouble() to convert the captured strings into respective primitive data types, enhancing the program's ability to process numerical data directly from user input .

In Java, program execution begins from the 'main' method, designated with the signature 'public static void main(String[] args)'. This method acts as the entry point for the program, where logic is initiated and the flow of execution is defined. The JVM calls the 'main' method, and any code within this block is executed sequentially. The 'main' method serves as the starting point from where other classes and methods can be invoked to perform the intended operations .

The mathematical principle behind calculating the area of a circle in Java programming is based on the formula A = πr², where A represents the area, π (Pi) is a constant approximated to 22/7 in the program, and r is the radius of the circle. In the Java code, this formula is translated into an expression that calculates the area using (22 * r * r) / 7, to cater to the reciprocal when using Pi's approximation. This formula captures the relationship between a circle’s radius and its total surface area .

You might also like