Assignment
Operator
Assignment
operator is used to assign a value to a variable.
Syntax
type
variable = value;
Example
int
a = 10.
int
b = 20
Java
supports compound assignments
Compound
Assignment
Syntax:
variable operator= value
Example:
lets
say
int
a = 10;
a+=10 evaluates to a=a+10
| Compound
Operator |
Example |
Description |
| += |
a+=10 |
a=a+10 |
| -= |
a-=10 |
a=a-10 |
| *= |
a*=10 |
a=a*10 |
| /= |
a/=10 |
a=a/10 |
Example
Program
class CompoundAssignment{
public static void main(String args[]){
int var1 = 100;
int sum=10, sub=10, mul=10, div=1000;
System.out.println("sum+var1 is " + (sum+=var1));
System.out.println("sub-var1 is " + (sub-=var1));
System.out.println("mul*var1 is " + (mul*=var1));
System.out.println("div/var1 is" + (div/=var1));
}
}
Output
sum+var1 is 110
sub-var1 is -90
mul*var1 is 1000
div/var1 is10
The
Type Comparison Operator instanceof
The
instanceof operator compares an object to a specified type. You can
use it to test if an object is an instance of a class, an instance of
a subclass, or an instance of a class that implements a particular
interface.
Example
class InstanceOfEx{
public static void main(String args[]){
Object obj = new Object();
System.out.println(obj instanceof Object);
System.out.println(obj instanceof InstanceOfEx);
}
}
Output
Don't
worry much about this program, you will learn about this while
discussing about class and object.
Ternary
operator( ?: )
Returns
one of two expressions depending on a condition.
Syntax
test
? expression1 : expression2
Returns
expression1 if the “test” condition evaluates to true other wise
returns expression 2.
Example
class TernaryEx{
public static void main(String args[]){
int a = 100;
int flag = a>10 ? 1 : 0;
System.out.println(flag);
flag = a>1000 ? 1 : 0;
System.out.println(flag);
}
}
Output
Observation
See
the statement “flag = a>10 ? 1 : 0”, a>10 is true, so 1 is
returned and assigned to the flag
Bit wise operators
Control flow statements
Home