Java program to add two numbers

java program to add two numbers is a very simple program.

It is required by learners How can we add two numbers.

We will start with simple addition and try to cover additional things here.

Java program to add two numbers

Steps to add two numbers

  1. Store two numbers in two variables
  2. Add both variables and store in another variable
  3. Print the result

Here we take a=5 and a=6 two variables

added a and b and stored in variable sum

printed the sum in consol.

Fig: Addition of two numbers in Notepad++
Fig: Compilation and run of Addition program

Addition of two numbers in java

Above we add two integer numbers.

Here lets take two decimal numbers in java we represent decimal number in float and double

Addition of two decimal numbers in java

The process is same only we changed data types.

Addition of two numbers in java

Here we are considering two numbers one is integer and another is double.

Here a is integer data type and b is double data type.

For addition a is automatically promoted to double data type by the compiler the addition is performed.

Whenever two or more variable of different data types take part in any operation then a lower data type is always converted to higher data type.

This automatic conversion is done by compiler and the process in known as widening.

Addition of short numbers in java

Here variable a and b both are short type.

While adding two short numbers it is converted to integer and the result is stored in integer data type.

Both byte and short data types are converted to an integer.

Sum of two numbers in java using method

In the above program sum() is a static method so we called it with Class name.

add1(), add2(), add3() and add4() are non static so we called by object of class.

Methods are with and without argument and with and without return type.

Write the definition of a method add, which receives two integer parameters and returns their sum.

Adding Two Numbers using Integer class sum()

Java program to add two numbers From User Input

1 add two numbers in java using Scanner class input

2 add two numbers in java using BufferedReader Class input

3. add two numbers in java using Console class input

write a program to add two numbers using class and constructor

Addition if Numbers class in java

The abstract class Number is the superclass of platform classes representing numeric values that are convertible to the primitive types bytedoublefloatintlong, and short.


How to add Two BigInteger in Java

Sum of two numbers using command line arguments in java

Command line argument is as a way to pass arguments in java while running java program.

  • Sum of two integer numbers using command line arguments in java
  • Sum of two double numbers using command line arguments in java
  • Conversion from String to number using Wrapper class
  • How to check length of command line argument in Addition of two numbers
  • Exception handling with command line arguments while adding two numbers

1 Sum of two integer numbers using command line arguments in java

Steps to add two integer numbers is below

  1. Read command-line variable array args[0] and args[1].
  2. Convert it to integer value and store it in two variables.
  3. add both variables and store in another variable sum
  4. print the sum.

Run above program from command prompt


>java CommandLineArguments 8 5

command line arguments in java
Fig: command line arguments in java


value 8 will pass to args[0] and value 5 will store in args[1].

As we know args is String array.

So to convert value from string we used Integer.parseInt() method.

Lets see another example

2 Sum of two double numbers using command line arguments in java


Similar way we can add long, float values.

You have to know how to convert string to long and string to float and from string to other data types.

This is possible with the use of Java wrapper classes.

Each primitive data type has its own class that is known as wrapper class.

Wrapper class contain methods to convert value from string to specify object type.

Following Classes are sub class of Number class.

You can find details in the Number class also check all its sub-classes.

Number Class in Java
Number Class in Java

3 Conversion from String to number using Wrapper class

Sr NoConvert from string toMethod

Above programs are very simple.

Lets assume a situation if use does not provide two values or provides values like alphabet then how to deal with it.

4 How to check length of command line argument in Addition of two numbers

In addition, we should check whether the user has provided two numbers or not.

Let’s check it.


args is string array so we can use the length property to check its length.

if (args.length != 2) then we are showing a message to the user that Please provide two arguments and terminate the execution.

5 Exception handling with command line arguments while adding two numbers

A. Handling ArrayIndexOutOfBoundsException

This exception occurs because we tried to access an array index that does not exist.

Read More

Exception Handling try catch finally blocks in Java
Exception Handling in Java: Hierarchy Example and Types
User-Defined (Custom) Exceptions in Java with Examples

If the user passed only one value and we access the first two values then this error can occur.

To avoid this we have already seen the above validation problem.

Lets again run our first program and pass only one value


Let’s see how to handle it with the exception



B. Handling NumberFormatException in Command line addition of numbers

This exception occurs when the method is unable to convert string to a number type.

For example, a user gives “w” as input so the method is unable to convert it to a number.

Then this method will throw NumberFormatException.


To resolve NumberFormatException again we will use try catch block.


C. Handling Multiple Exceptions from command line input

try can throw multiple exceptions to handle this we can create multiple catch blocks each for a specific exception.

We can also use one catch block to handle multiple exceptions.

Read More

  1. Duplicate Number between 1 to n numbers
  2. Print vowels in a String
  3. Program to reverse a string
  4. Prime number program in java using while loop
  5. Print vowels in a String
  6. Square Star Pattern

User Defined exception in Java | Java custom exception with examples

In Java programming, it is possible to create our own exception and such exception are called user defined exception in Java.

Exception class is a predefined class. Any user defined exception created by us must be a subclass of the predefine Exception class and created by extending the Exception class.

Read More

  1. Exception Handling in Java: Hierarchy Example and Types
  2. Exception Handling in Java with Examples
  3. Exception Handling try catch finally blocks in Java
  4. Throw and Throws Keywords in Java

What is user defined (custom) exception in java

An Exception that is defined by the user/ programmer is known as user defined or custom exception.


  1. Checking user age if not valid age throw an exception
  2. If not in a specified time period then throw an exception
  3. If the user name and password is incorrect then throw an exception

All above exceptions are created by the user and throw when required.

How to throw user defined exception in java

 The throw and throws keyword are used for implementing user defined exception. 

throw: throw keyword is used to throw an exception explicitly from a method or from a block.   

for instance

 Here new NumberIsGreaterException();

is creating new exception and throwing it.

throws: throws keyword is used with method signature that informs that the method can throw mentioned exception.   

Here Scanner is class and above mentioned Scanner represents the constructor call, On the constructor call of above we have to handle File not found Exception.

how to create user defined exception in java

  1. Create a class
  2. Extend the Exception class
  3. Create a String argument constructor to pass custom message.

Examples of User Defined Exception in Java

Example1:   write a program to take a number from user by using command line argument during run time. if user will enter  more than 100 then grnerate user defined exception MyException.

Explaination: In the above program, name of user define exception is NumberIsGreaterException. 

In the above program user enter  the number 111 during run time using command line argument.

Here value of “m” is greter than 100 therefore  “throw  newNumberIsGreaterException ();” this throw statement throw the exception and catch by catch block, but before thorw “NumberIsGreaterException ()” constructer will call.

User defined exception in java program to check age is valid or not


user defined exception in java example to check a time is in range or not, if time is not in range then throw custom exception


Example: Write a program to create user defined exception in Java to check a given name exists or not. If name doesn’t exists then throw a custom exception.


How to write custom exception in java?


How to create custom exception in java?


How to create your own exception in java?

  1. Create a class
  2. Extend Exception class
  3. Create a constructor to show/pass custom message

Increment and decrement operators in Python (+=, -=)


If you’re acquainted with other programming languages like C, Java, or PHP, you’ll recognize that the ++ symbol represents two operators: the increment and decrement operators, respectively.

The increment and decrement operators are not available in Python. 

This may seem strange, but in Python you would write + = or x = x + 1 to increase the value of the variable by 1, and use = or x = x – 1 to decrease the value by 1. 

 Reasons why python does not have increment and decrement operators.

 Here are some of the logical reasons why Python does not have increment and decrement operators. 

  • Similar results can be obtained with + = and -=.
  • Including ++ may slow down the VM engine as it adds a bit more opcode to the language. Frequent use of 
  • ++ is inside a loop, and in Python for loops are usually written in ranges (0, 10) like I, so the ++ operator is not needed.


The following C code outputs an integer from 10 to 1 with for loop.

We can get the same result in Python by writing the following code.

Python Increment Operator

How to increment in python

Special Use of Python Increment Operator 

 You must be familiar with the unary increment/decrement operator (++ /) if you’re comfortable with other high-level programming languages like C/C++ and Java.

There is one. However, unary increments and decrement operators are not allowed in Python programming, resulting in syntax issues.

 This is because Python takes a different approach than other languages ​​and uses immutable objects and names. 

 Let’s explain why the unary increment operator doesn’t exist in Python. 

  • This approach improves storage efficiency and accelerates the VM engine. 
  • Priority can be a bit difficult to use and understand for novice programmers. 
  • All statements in programming languages ​​use simple increments, but Python doesn’t have to use it in the for-statement syntax.

How to Increment a Variable in Python  

Using augmented assignment operator

The increment process using the unary operator using the advanced assignment operator does not occur in Python. However, there is another way to do this process.

Python uses the extended assignment operator + = operator or assigns directly a = a + 1 to perform the increment process. 

This is code that increments a number using the actual increment operator + =


Output : 6

Below is the example of how we use while loop to increment values



In the above example, the value of the variable i is set to 0, the loop is started, and the + = operator is used to increase the loop until it reaches 10.

Using the step parameter in the range () function

In a for loop, you can use the step parameter of the range function to specify the variable increment.

For example,


Invariant role in Python 

Note that integers are invariant in Python. This means that the values ​​in your code do not change over time, which makes them very different from other well-known programming languages. 

To better understand this, let’s look at an example of three integers that are declared together and contain the same value.

The above code gives the following output:

Incrementing the variable x in the above code

The above code gives the following output:

All the integers declared in the code above, namely x, y, z, refer to a single object in Python to save memory. This causes a syntax error when trying the basic unary increment operator ++ in Python code.

Python decrement operator

There is no decrement operator in Python. Python can only decrement values, but Python doesn’t have such an operator. The decrement operator exists in C and C ++ but not in Python.

Ways for decrementing values in python

Using Start, Stop Index, and step to Decrement for loop in Python

This example uses the start and stop indexes to decrement the value of the for loop.

Set the value of the start index to be larger than the stop index so that the value is decremented one after another at each iteration. To further comprehend the notion, consider the following example.



  • First, assign a start index value that is greater than the stop index, or 10. 
  • Then assign the stop index value as 0. 
  • Then the value of the step is assigned as 1, and the value of the for loop is decremented. 
  • Then I used a for loop with the variable `i’ and the range as the start index, stop index and step. 
  • Finally, I printed the output. 
  • Therefore, you can see the output in reverse order.

Using Start, stop, and step in for loop only to Decrement for loop in Python.

To observe the output, we set the stop index to the same value as the start index. The value is decremented because the value of the start index is greater than the value of the stop index. To further comprehend the notion, consider the following example.



  • In this example, we applied all the values ​​in the for loop’s range () function. 
  • The start index is set to 10, the stop index is set to 0, and the step is set to 2. This decrements the value by 2 for each iteration up to 0. 
  • Finally, you get the value of the variable i. issued. 
  • You can now see the output.

Using reversed () Function to Decrement for loop in Python

This example uses the reversed () function internally to pass the range () function and display the output. The inverse () function is used to execute the sequence in reverse order. Let’s look at an example to understand the concept in detail.



  • In this example, I used the reversed () function, which is used to print the values ​​in reverse order. 
  • I applied the for loop directly and applied the reverse () function inside it.
  • In the reverse () function, the range () function is also applied with 5. 
  • Finally, I printed the value of the I variable. 
  • So, you can see the result.

Using while and -= operation

This example uses a while loop and the i = operation to decrement the values ​​one at a time or as per your requirement. Set the while condition and then decrement the value inside the while function. Let’s look at an example to get a more detailed understanding of the concept.



  • First, we take the input variable s and assign it the value we want to decrement (s = 5). 
  • Then apply a while condition likes > 0. 
  • Within the while condition, print the value of s and decrement the value of s by 1 after printing the value (s = 1). 
  • So, you can see the result.

Increment a character in Python

In Python, you can explicitly convert data types, but there is no implicit notion of data types, but you tell operators to work in some way, understand the data types of operands, and manipulate them accordingly. It’s not easy to do. For example, to add 1 to a character, you need to formulate another way to increment the character because you will get an error pointing to a type conflict when you need to increment the character.


Python increase by 1 in for loop

For loops are typically used for sequential traversal. It falls into the most reliable iteration category.

A particular iteration means that the number of iterations is explicitly specified in advance.



Python i++

We do not use ++ operators in Python for consistency and simplicity. I don’t know the exact argument Guido van Rossum proposed for the decision, but I can imagine some. 

  • Simpler parsing. Technically speaking, the analysis of ++ counts is ambiguous. This is because it can be as simple as ++, +, count (two unary + operators) and ++, count (one unary ++ operator). This is not a significant syntactic ambiguity, but it does exist.
  • A simpler language. ++ is just a synonym for + = 1. This shorthand was invented because the C compiler was stupid and didn’t know how to optimize + = 1 in the inc statement you see on most computers. In today’s world of optimizing compilers and bytecode interpretation languages, adding operators to languages ​​that allow programmers to optimize their code is generally discouraged.

+= in Python

The Python + = operator adds two values ​​together and assigns the final value to a variable. This operator is called the additive assignment operator. This operator is often used to add a value to a counter variable that keeps track of how many times something has happened. Addition When you use the assignment operator, two numbers are added. The final value is assigned to a variable.

The syntax for this arithmetic operator is:

variable_name += value



Python to access array elements

The index number is used in Python to access array elements. For accessing elements from the array, we shall utilize the index operator.

Indexing an array in Python is the same as accessing an array element. Access the array element by looking at the index number. Here, I used “(my_arr [1])” to access “12”.



In Python, how do you decrement a for loop?

The for loop is used for iteration. In most cases, use loops in incremental order. However, you can also use for loops in descending order. This subject demonstrates how to utilize Python’s decrement-for-loop function.

Method 1: The range() method 

produces a range of integers in a specified initial parameter.

range (start, stop, step)


  • The Start is an optional value. This is the number that defines the starting position. The default is 0. 
  • The stop is the value to stop the range. It is not included in the range. 
  • The step is another option value. It defines the number of steps that increase or decrease during the iteration. The default is 1.



Method 2: By using reversed () method:

If you don’t want to use a step with a negative value, you can also use the reverse method to pass the output from the range () to that method. The reverse method takes the sequence as a parameter and returns the reverse iterator of the sequence. 

If you use the reverse (), you do not need to use the step. However, the reverse () adds additional processing to the range, so negative value steps are recommended.



Increment operator in python

+= cab be used to increment a in python



Python increment variable in loop

for loop increment in python

increase by one

increase by two

increase by 10


As we discussed Python increment and decrement operators are not directly supported to increment and decrement we need to use += and -= operators.

Here we discussed how to achieve Python increment and decrement operators.

Caret Symbol (^) and its use

Did you ever wondered that what is the symbol above the digit 6 on your standard qwerty keyboard?

Or let me put this in another way. Can you tell me that which is the least used punctuation mark in conventional writing? No, no! I do not mean that it is not used at all.

Well, it is the caret symbol and the symbol of Caret is ^ . This is basically the inverted letter ‘V’, and is found on every keypad or keyboard in this contemporary world.

Caret Symbol (^) and its use

Today, we will be discussing about the caret symbol from the beginning to the end in this article.

Origin of the word ‘Caret’

The origin of the word Caret is Latin. In literal sense, it means ‘there is lacking’.

This is a form of the word ‘Carere’ which means ‘to lack’.

Here’s something way more interesting.

The pronunciation of the word Caret is exactly similar to the way all of us has been pronouncing the word ‘Carrot’ for years!

In other words, it means that both these words i.e. Caret and Carrot are homophones.

Definition of Caret

When an item such as a mark, or a phrase, or a word or letter, has been missed or omitted in a text; Caret is used in such circumstances.

What is the caret Symbol (^) ?

Caret may mean 2 things to many people-

  • It is another name used for a cursor.
  • Caret is also sometimes referred as circumflex. On a standard US qwerty keypad, the caret symbol, denoted by ^, is located above the Number ‘6’ key.

Examples of the Caret

Now, here we will be providing some of the examples of the word Caret to give you a better understanding-

  • Before the students, the teacher arrived (^) the class. (at the)
  • We accepted their sincere (^) heartfelt apologies. (And)
  • You should bring some (^) for the food items. (Plates)
  • He went to (^) convenience. (The)
  • Small drops (^) water results in a mighty and big ocean. (Of)
  • When the boy fell, he (^) holding the flag. (Was)

Uses of caret symbol (^)

The caret symbol can be used in several ways and fields.

It can be used in mathematics, English, HTML, various programming languages, many regular expressions, windows function, in Microsoft Word, and many more.

We will discuss the usage of caret symbol one by one in each of these fields in this article, so stay tuned!

Uses of caret in Math

In Mathematics, the caret symbol is used to represent an exponent, such as exponential power like square or cube.

For example-

  1. 6^2 means the square of 6 i.e. 6 × 6 = 36. It can also be represented as 6².
  2. 7^3 means the cube of 7 i.e. 7 × 7 × 7 = 343. It can also be represented as 6³.

Microsoft Excel users, are you listening? Why have I specifically pointed the Microsoft Excel users here?

This is simply because the exponential use of the caret symbol is frequently used for creating and inserting different statistical formulas and mathematical formulas within the Microsoft Excel software.

Uses of caret in English

The caret symbol is extensively and heavily used in the English language.

It finds its uses in different aspects of the language such as proofreading, contouring in tone, indicating something that has been already said, and for the indication when a long vowel occurs or is used.

So, here one by one, we will discuss the uses of the caret symbol in the English language. Let’s start!

Use of caret in Proofreading

The caret symbol has a big role to play in proofreading.

The proof-readers use the caret symbol to point out the mistakes in a text and inserts it in the space between words where the omission or the mistakes have occurred.

The writers also use the caret symbol when they want to add anything in their text.

For example, here is a sample sentence for the same –

‘When the light went out, my father holding the camera’.

The above sentence when checked, and corrected by a proof-reader will be as follows –

‘When the light went out, my father ^was holding the camera.’

Therefore, one can easily use the caret symbol within their writing if they want to insert something in their texts.

Contour in Tone

You may come across languages in your daily life that can be termed as ‘tonal’.

Tonal languages are the languages in which there is a change of tone from one word to another or from one syllable to another.

Many a people refer to it as observable or significant fact ‘tone contouring’.

Therefore, the caret symbol is used to denote this variation of tones when we transcribe spoken utterance.

Depending on whether the tone goes up or down, the pitch could either be falling tone or rising tone.

Indicating something already said

Okay, now this is a segment for the people who are in their 20s or 30s or maybe 40s, and has a habit of chatting.

You can even use your very own caret symbol in chatting.

The caret symbol can be used to refer to a comment or maybe a chat, that the person has made somewhere up in the chat.

I know, I know, you must be thinking that dude come-on, there are so many emoji and emoticons available in the present age.

We can use any one of them to refer to a comment somewhere placed up in the text. But, ladies and gentlemen, here am I just letting you know that the caret symbol is also a way in which you can refer to a text somewhere placed above in the chat or text.

Also, if you see that a person has just replied to the comment above theirs by the caret symbol, then it means that they agree to the comment made.

Okay, here’s another question that you got to deal with, in this article. Do you know what does it mean that the caret symbol is repeated such as [^^^^^^^^^^^^^^]?

If you doesn’t, here’s the solution – If you see the caret symbol repeated as above, it simply means that the speaker wants to review again the line or sentence that has been mentioned above.

An indication of a long vowel

Linguists often use the caret symbol to represent the presence of a long vowel, in languages such as French and Portuguese.

This is done so that it is easy to differentiate between a long vowel and a short vowel.

Uses of caret In HTML

HTML is a Hyper Text Markup Language used to create web pages.

To show Caret Symbol in html we can use below mentioned codes.





CSS CODE – \005E

Here is an HTML Example of the same-

// html example


Time for a CSS Example now –

// CSS example

span {

  content: “\005E”;


Uses of caret in Programming

For all those of you who are in the coding or programming line, must be aware that the caret symbol is heavily used in the programming languages.

For all those of you who do not know about it, here is our this segment to let you the uses of the caret symbol in the programming languages.

Programmers use the caret symbol while writing the computer programmes or syntax in the field of computer programming.

The caret symbol, in coding, denotes the command of matching the initial character with one string or line of command.

In another programming language i.e.

C Programming Language, the caret symbol (^) is used for the Boolean operation of XOR that is functional for database operations.

Uses of caret in regular expression

There we ended our segment on the uses of the caret symbol. Now, let’s move on to our next segment in which we will be discussing about how can we print the caret sign or symbol on various software and devices.

How to print Caret sign on windows

Now, coming down preferably for the Windows layout, you can type the Caret sign as follows –

  1. Look out for the ‘Alt’ key on your keyboard.
  2. Holding the ‘Alt’ key, you need to press ‘094’ on your numeric keyboard or numeric keypad.

This will work for all the Windows layouts, and you can easily get the caret symbol (^) immediately and instantly on your display screen.

Note – This won’t work if you are holding down the ‘Ctrl’ Key. So avoid getting the caret symbol on your screen by using the ‘Ctrl’ key.

How to use caret key on the keyboard?

As stated earlier, the caret sign or symbol can be typed on windows by pressing the shift key + digit no. 6.

Keyboard Image
Keyboard Image (Photo by Jay Zhang on Unsplash)

This is preferably for the UK Keyboards.

For the US counterparts, you can try Ctrl Key + Shift Key + Number 6, to type the caret symbol on windows.

How do you type a caret symbol?

Below are the simple steps that you can follow to find the caret symbol and type it, whenever you want it at your disposal-

  1. First of all, you need to select the point in your document where you want to insert the caret symbol.
  2. Next, in this step, you need to locate the number or digit 6 in your keyboard. Here’s a cheat code for you as you are reading this article –It will be located somewhere near the top middle area of your standard US qwerty keypad or keyboard (whatever you say it, Ahh!).
  3. Now, after your hunt for the digit no. 6 has been finished. Next, you need to locate the ‘shift’ key which will be present either in the left bottom or the right bottom of your keyboard (It is present at both the sides of the keypad or the keyboard).
  4. Use both your hands in this step – Press the shift key with one hand and the digit no. 6 with the other hand. Why digit no. 6? Because it contains the caret symbol (^) right above it.
  5. And tantananaaaa…. you are going to find the caret symbol i.e. ^ appearing immediately at your display screen.

How to print Caret sign on Microsoft Office

  1. You need to use the Equation Editor i.e. Alt + = ; to print the caret sign on Microsoft Office.
  2. Go to the Equation Tools Tab.
  3. In the structures group, you need to tap on the Accent Button.
  4. You will find the hat in the top row at the rightmost corner.
  5. Then, put the cursor in the box under the hat.
  6. At the left end of the ribbon, click on the Normal text.
  7. And tantananaaaa… Type the word now to see the magic!

Another way to use goto Edit -> symbol.

click on symbol then more symbol.

From there you will get

Microsoft Word 2007 Caret Symbol
Fig Microsoft Word 2007 Caret Symbol

How to print Caret sign on MAC

Here’s the last thing I want to tell you before I sign off.

The caret symbol can be printed with the same ‘Shift + 6’ on every platform, doesn’t matter you are working on a MAC or on a Windows version.

Q: What does this symbol mean (^)

This symbol is known as Caret Symbol
It uses are different in different fields
Uses of caret in Math
Uses of caret in English
Use of caret in Proofreading
Indicating something already said
Uses of caret In HTML
Uses of caret in Programming

Q: How to print Carrot key on keyboard

To print carrot symbol on keyboard use shift key + digit no. 6.

Q: How to prints shift 6 on keyboard

This is used to print carrot symbol (^) in keyboard

Q: How to write exponents on keyboard

use shift key + digit no. 6 to print carrot symbol or use double star


That’s all from our side in this article about Caret Symbol. We have covered that what is the caret symbol, the uses of caret symbol, ways to print the caret symbol on several software and devices.

Today, we learnt everything about the caret symbol (^). It is astonishing to see that the same symbol can be used in so many different ways and distinct disciplines of the world. And who knows that someone out of you might come up with a new, interesting, and exciting way to use this multi – dimensional symbol. And it might also become excessively popular with everyone else in our world!

We hope that you liked our article on the caret symbol. In case you have any queries or questions related to the caret symbol, its uses, and ways to print it; please feel free to mention them in the comment section. And do not forget thinking about the caret symbol (^) and using this figure.

Also, please don’t hesitate in sharing this knowledge or connecting with us as we are just a click away. See you, until next time in another article!