Insurance Loans Mortgage Attorney Credit Lawyer Donate Degree Hosting Claim Conference Call Trading Software Recovery Transfer Gas/Electricity Classes Rehab Treatment Cord Blood
Conditional Operator ( ? : ):
Conditional operator is also known as the ternary operator. This operator consists of three operands and is used to evaluate Boolean expressions. The goal of the operator is to decide which value should be assigned to the variable. The operator is written as
variable x = (expression) ? value if true : value if false
Example :-
class BasicOperators{
public static void main(String[] args) {
int x = 30;
int one = ((x==30) ? 10 : 20);
System.out.println("First "+ one);
int two = ((x < 10) ? 10 : 20);
System.out.println("Two "+ two);
}
}
Output is :-
First 10
Two 20
public static void main(String[] args) {
int x = 30;
int one = ((x==30) ? 10 : 20);
System.out.println("First "+ one);
int two = ((x < 10) ? 10 : 20);
System.out.println("Two "+ two);
}
}
Output is :-
First 10
Two 20
Instance Of Operator
This operator is used only for object reference variables. The operator checks whether the object is of a particular type(class type or interface type). instanceOf operator is wriiten as
( Object reference variable ) instanceOf (class/interface type)
If the object referred by the variable on the left side of the operator passes the IS-A check for the class/interface type on the right side, then the result will be true. Following is the example:
class BasicOperators{
public static void main(String[] args) {
String Svalue = "Java";
boolean isString = Svalue instanceof String;
System.out.println(isString);
}
}
Output is true
public static void main(String[] args) {
String Svalue = "Java";
boolean isString = Svalue instanceof String;
System.out.println(isString);
}
}
Output is true
This operator will still return true if the object being compared is the assignment compatible with the type on the right. Following is one more example:
class Vehicle {}
class Car extends Vehicle {
public static void main(String args[]){
Vehicle a = new Car();
boolean result = a instanceof Car;
System.out.println( result);
}
}
Output is true
class Car extends Vehicle {
public static void main(String args[]){
Vehicle a = new Car();
boolean result = a instanceof Car;
System.out.println( result);
}
}
Output is true
No comments:
Post a Comment