Table of contents | |
Introduction | |
Basic Assignment Operator | |
Arithmetic Assignment Operators | |
Sample Problems | |
Conclusion |
In Java, assignment operators are used to assign values to variables. They provide a convenient way to perform operations while assigning values. This article will cover the various assignment operators in Java and provide examples to help you understand their usage.
The basic assignment operator in Java is the equal sign (=). It assigns the value on the right-hand side of the operator to the variable on the left-hand side. Let's look at an example:
int x = 10;
System.out.println("x = " + x); // Output: x = 10
Explanation:
Java provides several arithmetic assignment operators that combine arithmetic operations with assignment. These operators perform the specified arithmetic operation and assign the result to the variable. Here are the arithmetic assignment operators:
Let's see examples of each arithmetic assignment operator:
Addition assignment (+=)
int a = 5;
a += 3;
System.out.println("a = " + a); // Output: a = 8
Explanation
Subtraction assignment (-=)
int b = 10;
b -= 4;
System.out.println("b = " + b); // Output: b = 6
Explanation:
Multiplication assignment (*=)
int c = 3;
c *= 5;
System.out.println("c = " + c); // Output: c = 15
Explanation:
Division assignment (/=)
int d = 20;
d /= 4;
System.out.println("d = " + d); // Output: d = 5
Explanation:
Modulus assignment (%=)
int e = 17;
e %= 5;
System.out.println("e = " + e); // Output: e = 2
Explanation:
Here are some sample problems to test your understanding of assignment operators:
1. Write a program to calculate the compound interest using the formula:
A = P * (1 + r/n)^(nt), where:
Solution:
double principal = 1000;
double rate = 0.05;
int time = 3;
int compound = 2;
double amount = principal * Math.pow((1 + rate/compound), compound * time);
System.out.println("Compound interest: " + amount);
2. Write a program that swaps the values of two variables without using a temporary variable.
Solution:
int a = 5;
int b = 10;
a = a + b;
b = a - b;
a = a - b;
System.out.println("a = " + a); // Output: a = 10
System.out.println("b = " + b); // Output: b = 5
Assignment operators in Java provide a convenient way to perform operations while assigning values to variables. We covered the basic assignment operator (=) and various arithmetic assignment operators (+=, -=, *=, /=, %=). It's essential to understand how these operators work to write efficient and concise code. By practicing the examples and solving the sample problems, you'll gain a solid understanding of Java assignment operators.
60 videos|37 docs|12 tests
|
|
Explore Courses for Software Development exam
|