Using operators - 1
Assignment operators
You can assign a primitive variable using a literal or the result of an expression. The result of an expression involving integers (int, short, and byte) is always at least of type int. Narrowing conversions are not allowed, as they would result in the loss of precision. For instance:
byte b = 5;
byte c = 4;
byte d = b + c; // does not compile because int cannot fit in a byte
float f = (float)35.67; // implicitly double, so casting to float
float f = 35.67F;
A boolean cannot be assigned any type other than boolean.
If we assign an existing object reference to a reference variable, both reference variables refer to the same object. It is legal to assign a child object to a parent object, but the reverse is not allowed. You can also assign an object reference to an interface reference variable, if the object implements that interface. For instance:
class Base{}
public class Child extends Base
{
public static void main(String argv[])
{
Child child = new Child();
Base base = new Base();
base = child; // Compiles fine
child = base; // Will not compile
}
}
instanceof operator
The instanceof operator is used to check if an object reference belongs to a certain type or not. The type can either be an interface or a superclass. For instance:
class A{}
class B extends A
{
public static void main(String args[])
{
B b = new B();
if(b instanceof A)
System.out.println("b is of type A"); // "b is of type A" is printed
}
}
Note that an object is of a particular interface type if any of its superclasses implement that interface.
The plus (+) operator
The plus (+) operator is typically used to add two numbers together. If the operands are String objects, the plus (+) operator is overridden to offer concatenation. For instance:
String s1 = "hello ";
String s2 = "World ";
System.out.println(s1 + s2); // prints "hello world"
If one of the operands is a String and the other is not, the Java code tries to convert the other operand to a String representation. If the operand is an object reference, then the conversion is performed by invoking its toString() method:
int i = 10;
String s1 = " rivers";
String s2 = i + s1;
System.out.printlns(s2); // prints "10 rivers"
No comments:
Post a Comment