Table of Contents
Java Assignment Operators: Examples and Usage
This is a simple example that demonstrates the assignment operators. Copy and paste the following Java program in AssignmentOperator.java file. Compile and run this program
Example of Assignment Operator
public class AssignmentOperator {
public static void main(String args[]) {
int a = 5;
int b = 10;
int c = 0;
c = a + b;
System.out.println("c = a + b = " + c );
c += a ;
System.out.println("c += a = " + c );
c -= a ;
System.out.println("c -= a = " + c );
c *= a ;
System.out.println("c *= a = " + c );
a = 10;
c = 15;
c /= a ;
System.out.println("c /= a = " + c );
a = 10;
c = 15;
c %= a ;
System.out.println("c %= a = " + c );
c &= a ;
System.out.println("c &= a = " + c );
c ^= a ;
System.out.println("c ^= a = " + c );
c |= a ;
System.out.println("c |= a = " + c );
c = 2 ;
System.out.println("c >>= 2 = " + c );
c >>= 2 ;
System.out.println("c >>= 2 = " + c );
}
}
Output
c = a + b = 15
c += a = 20
c -= a = 15
c *= a = 75
c /= a = 1
c %= a = 5
c &= a = 0
c ^= a = 10
c |= a = 10
c = 2 = 10
c >>= 2 = 2
Press any key to continue . . .
Problem in addition of two short datatype
class OperatorAddShortExample{
public static void main(String args[]){
short a=10;
short b=10;
//a+=b;//a=a+b internally so fine
a=a+b;//Compile time error because 10+10=20 now int
System.out.println(a);
}
}
Output
OperatorAddShortExample.java:6: error: incompatible types: possible lossy conversion from int to short
a=a+b;//Compile time error because 10+10=20 now int
^
1 error
solution of the above problem using type conversion
class OperatorAddShortExample{
public static void main(String args[]){
short a=10;
short b=10;
a=(short)(a+b);//20 which is int now converted to short
System.out.println(a);
}
}
Output
20
Press any key to continue . . .
Home & Online Tuition
Learn from an experienced tutor with personalized guidance.
Available Locations
Hatiara
Baguiati
Noapara
Chinar Park
Others - Online
Expert Home & Online Tuition
Personalized one-to-one tuition that focuses on concept building, practical learning, problem-solving skills, and excellent academic performance. Suitable for school students looking for structured, interactive, and result-oriented learning.
Subjects We Teach
Computer Science
Programming
Java
Python
HTML
CSS
JavaScript
PHP
MySQL
SQL
Why Choose Our Tuition?
✅ One-to-One Attention
✅ Concept-Based Learning
✅ Practical Examples
✅ Weekly Tests
✅ Doubt Solving Sessions
✅ Concept-Based Learning
✅ Practical Examples
✅ Weekly Tests
✅ Doubt Solving Sessions
✅ Printed & PDF Notes
✅ Practice Worksheets
✅ MCQ & Assignments
✅ Exam Preparation
✅ Flexible Class Timings
✅ Practice Worksheets
✅ MCQ & Assignments
✅ Exam Preparation
✅ Flexible Class Timings