Java Tutorial
🔍
What is OOP?Classes & ObjectsConstructorsAccess Modifiersthis Keywordstatic KeywordEncapsulationInheritancesuper KeywordMethod OverridingOverloading vs OverridingPolymorphismUpcasting & Downcastinginstanceof OperatorAbstractionAbstract ClassesInterfacesMarker InterfacesAbstract Class vs InterfaceObject ClasstoString() Methodequals() & hashCode()
Collections OverviewCollections HierarchyIterable InterfaceCollection InterfaceMap Interfaceequals() and hashCode()IteratorListIteratorFail-fast vs Fail-safe IteratorConcurrentModificationExceptionArrayListLinkedListHashSetLinkedHashSetTreeSetQueuePriorityQueueDequeArrayDequeHashMapLinkedHashMapTreeMapConcurrentHashMapCopyOnWriteArrayListList vs Set vs MapChoosing the Right CollectionComparableComparatorComparable vs ComparatorCollections Utility ClassArrays Utility ClassImmutable CollectionsCollection vs CollectionsVectorHashtableStackArrayList Internal WorkingLinkedList Internal WorkingHashMap Internal WorkingTreeMap Internal Working
Add Two Numbers in Java
beginner· Basics & I/O · Arithmetic
Problem
Adding two numbers together with the + operator is one of the most basic arithmetic operations in Java.
Given two integers, add them and print the result.
Input
5, 3
Output
Sum: 8
Java Program
Java
public class AddTwoNumbers {
public static void main(String[] args) {
int a = 5;
int b = 3;
int sum = a + b; // numeric addition
System.out.println("Sum: " + sum);
}
}Output
Sum: 8
Core Logic
The + operator between two int values adds them directly, and the result can be stored in a third variable before printing.
How It Works
- 1Two int variables,
aandb, hold the numbers to add. - 2
a + bevaluates to their sum, which is stored insum. - 3
System.out.printlnconcatenates the label"Sum: "with the numeric value using+.
With
a = 5 and b = 3, a + b evaluates to 8, so the program prints "Sum: 8".💡
Key Point: Java's + operator does either numeric addition or string concatenation depending on the operand types — mixing an int with a String (like here) triggers concatenation, not addition.
Key Concepts
+ operatorintarithmetic