Java Tut – Operators

Arithmetic operator – Just like other languages
+,-,*,%,/++,– etc.

Relational Operators: ==,!=,>,<,>=,<= etc.
e.g:

public class RelationalOperator {
public static void main(String[] args)
{
int a=10;
int b=20;
System.out.println("a==b = "+(a==b));
System.out.println("a!=b = "+(a!=b));
System.out.println("a>b = "+(a>b));
System.out.println("a<b = "+(a<b));
System.out.println("a>=b = "+(a>=b));
System.out.println("a<=b = "+(a<=b));
}
}

Bitwise Operators: Java defines several bitwise operators,which can be pplied to the integer types,long,int,short,char, and byte

Bitwise operator works on bits and performs bit-by-bit operation.
Assume if a=60 and b=13; now in binary format they will be a s follows:
a=00111100
b=00001101
——————
a&b=00001100
a|b=00111101
Some operators:
& bitwise and, | bitwise inclusive or,^ bitwise exclusive XOR,~ bitwise compliment,<< left shift,>> right shift,>>> zero fill right shift
e.g:

public class Bitwise {
public  static void main(String[] args)
{
	int a =60;
	int b=13;
	int c=0;
	
	c=a&b; /*12=0000 1100 */
	System.out.println("a&b = "+c);
	
	c=a|b;
	System.out.println("a|b="+c);
}
}

Logical Operators:
&& logical AND,|| logical OR,! logical NOT
e.g:
assume boolean variable a holds true,b holds false.

public class Logical {
public static void main(String[] args)
{
	boolean a=true;
	boolean b=false;
	
	System.out.println("a && b = "+(a&&b));
	System.out.println("a || b = "+(a||b));
	System.out.println("!(a&&b) = "+!(a&&b));
}
}

Assignment Operator:

= simple assignment operator, += Ass and assignment operator c+=a is equivalent to c=c+a,-=,*=,/=,&=,%=,<<=,>>=,^=,|=

Conditional Operator/ternary operator:
syntax:
variable x= (expression)?value if true:value if false
e.g:

public class Ternary {
public static void main(String args[]){
int a,b;
a=10;
b=(a==1)?20:30;
System.out.println("Value of b is: "+b);

b=(a==10)?20:30;
System.out.println("Value of b is: "+b);
}
}

Instance of operator:
This  operator is used only for object reference variables.The operator checks whether the object is of particular type(class type or interface type).instance of operator is written as:

(Object reference variable)intsanceof(class/interface type)

e.g:

public class InstanceOf {
	public static void main(String[] args){
String name="James";
boolean result=name instanceof String;
System.out.println(result);
}
}

output:

true

another example will still return true if the object being compared is the assignment compatible with the type on th right.

public class Vehicle {
public static class Car extends Vehicle{
	public static void main(String[] args)
	{
		Vehicle a = new Car();
		boolean result=a instanceof Car;
		System.out.println(result);
	}
}
	
}

output:

true

 

It would be a great help, if you support by sharing :)
Author: zakilive

Leave a Reply

Your email address will not be published.