ASSIGNMENTS & OPERATORS
ASSIGNMENTS
Stack and Heap makes easy of understanding of the topics
like argument passing, polymorphism, threads, exceptions, and garbage collection.
Most of the java programs live on stack and heap memory.
i.
Instance variables
ii.
Local variables
iii.
Objects
·
Instance variables and objects live on heap
·
Local variables live on the stack
Ex: java
program and how it’s various pieces are created and map into the stack and the
heap
1. Class
Collar{}
2. Class
Dog{
3. Collar
c;//instance variable
4. String
name;//instance variable5.
6.
7. Public
static void main(String args[]){
8.
9. Dog
d;//local variable
10. d=new
Dog();
11. d.go(d);
12. }
13. Void
go(Dog dog){//local variable dog
14. C=new
Collar();
15. dog.setName(“Aiko”);
16. }
17. Void
setName(String dogName){//local variable dogName
18. Name=dogName;
19. }
20. }
Line 7: main()
is placed on the stack
Line 9:
Reference variable d is created on the stack, but there is no Dog object yet
Line 10: A new
Dog object is created and is assigned to the d reference variable
Line 11: A copy
of the reference variable d is passed to the go() method
Line 13: the
go() method is placed on the stack , with the dog parameter as local variable
Line 14: A new
Collar object is created on the heap and assigned to Dog’s instance variable.
Line 17:
setName() is added to the stack, with the dogName parameter as its local
variable
Line 18: the
name instance variable now also refers to the String object.
Notice the two
different local variables refer to the same Dog object
Notice that one
local variable and one instance variable both refer to the same String Aiko
After Line 19
completes, setName() completes and is removed from the stack. At this point the
local variable dogName disappears, too, although the String object it referred
to is still on the heap
Literals , Assignments, and Variables:.
1. Literals:
2. Assignment Operators:
Assigning a value
to a variable seem straightforward enough; you simply assign the stuff on the
right side of the ‘=’ to the variable on the left.
X=6;
What is a variable?
How are the variable and its value related?
Variables are just bit holders, with a designated type. you
can have an int holder, a double holder, a Button holder, and even a String[]
holder. Within that holder is a bunch of bits representing the value.
For example primitives the bits represent a number value. A
byte with value of 6 means that the bit pattern in the variable is 00000110 ,
represents 8 bits.
What is inside an object holder?
Button b=new Button()
What is inside Button
holder b?is it the button object ?
NO a variable referring to an object is just that- a
reference variable. A reference variable bit holder contains bits representing
a way to get to the object. We don’t know what the format is . The way in which
object references are stored is Virtual machine specific.
If reference variable has not been assigned a value or has
been explicitly assigned a value of null, the variable holds to represent it
null
i.
Primitive
Assignments:
The ‘=’ sign is used for assigning a value to a variable, it
is named as assignement operator. There are actually 12 assignment operators.
But in scjp exam only 5 comes.
You can assign a primitive variable using a literal or
result of the expression.
Ex:
Int x=7;//literal assignment
Int y=x+2;//assignment with an expression including a
literal
Int z=x+y;//assigning with an expression
Note: literal integer is always implicitly an int.
What about if you are assigning to a byte variable?
Byte b=7;
Here compiler automatically narrows the literal value to a
byte.it puts in the cast.
Byte b=(byte) 7;//explicitly cast the int literal to a byte
Note: the result of an expression involving anything
int-sized or smaller is always an int.
Byte a=3;//No problem, 3 fits in byte
Byte b=8;//No problem , 8 fits in byte
Byte c=a+b;//should be no problem, sum of the two bytes fit
in byte
The last line won’t compile we get Compile time error
Possible loss of precision
Found : int
Required : byte
If would compile if we give byte c=(byte)(a+b);
Note 1:
It is legal to declare multiple variables of the same type
with a single line by placing a comma between each variable.
Int a,b,c;
You also have the option to initialize any number of variables right in place:
Int j, k=1,m=3;
And these variables are each evaluated in the order that you
read them, left to right. It’s just as if you were to declare each one on a
separate line
Int i;
Int k=1;
Int l;
Int m=3;
But the order is important
Int j,k=1,l,m=k+3; // legal: k is initialized before m uses it
Int j,k=m+3,l,m=1; //illegal, m is not initialized before k
uses it.
Int x, y=x+1, z; //illegal: x is not initialized before y
uses it.
Primitive Casting:
Casts can be
implicit or explicit.
An implicit cast
means you don’t have to write code for the cast;
The conversion happens automatically typically an implicit
cast happens when you are doing a widening conversion in other words putting a
smaller thing (say a byte) into a bigger container (say int) .
The possible loss of precision happens when we tried to put
a larger thing (say long ) into a smaller container(say a short). The
large-value into small container convention is referred as narrowing and requires an explicitly cast.
Where you tell the compiler that you are aware of the danger and accept full
responsibility.
Implicitly cast:
Itn a=100;
Long b=a;//implicitly cast, an int value always fits in long.
An explicit casts looks like the
Float a=100.001f;
Int b=(int )a;//Explicitly cast, the float could loss info
Double d=100L;//implicit typecasting
Need to convert double to int:
Int x=1234.980//illegal
Here integer is not capable of storing decimal places, an
error occurs.
Int x=(int)3456.987;//legal cast
When you cast a floating point number to an integer type,
the value loses all the digits after decimal.
Int x=3456;
We can also cast a larger number type such as Long into a
smaller number type, such as byte.
Long l=56L;
Byte b=(byte) l;
Sop(b);
o/p: -126
here we don’t get Runtime error, even when the value being
narrowed is too large for the type. the bits to the lef to fthe lower 8 just go
away. In the byte now happens to be a 1, the primitive will have a negative
value.
Casting primitives:
Create a float number type of any value, and assign it to a
short using casting:
1.
Declare a float variable: float f=234.56f;
2.
Assign the float to a short: short s=(short)f;
Type Casting [SCJP]:
there are two types of type casting
1.
implicit type casting
2.
Explicit type casting.
1.
Implicit Type casting:
Compiler is responsible to perform this
type of casting. Wheneever we are assigning smaller data type value to the
bigger data type variable implicit type casting will be performed.
It is also known as widening or up casting
No loss of information in this type casting
The following is the list of all possible
implicit type casting
Byte -- Short -- int -- long -- float -- double
Char -- int --long --float -- double
Ex: int x=’a’;
Sop(x);//97 compiler converts char to int
automatically
Double d=10;
Sop(d);10 compiler converts int to double
automatically
2.
Explicit Type casting:
Programmer is responsible to perform type
casting whenever we are assigning bigger data type value to the smaller data
type variable explicitly typecasting will be performed.
It is also known as Narrowing or down
casting
There may be a chance of loss of
information in this type of casting.
The following are various possible
conversions where explicit typecasting will be required.
Double -- float --- long -- int --- short --- byte
Double -- float -- long -- int -- char
Ex: int x=130;
Byte b=x;CE: possible loss of precision
found: int required : byte
Byte b=(byte)x;
Sop(b);//-126
Whenever we are assigning bigger data type
value to the smaller data type variable the most significant bits will be lost
ii.
Assigning
Floating – point Numbers:
Every floating point literal is implicitly a double.(64 bit)
. if you try to assign a double to a float, the compiler knows you don’t have
enough room in 32 bit float container to hold the precision of a 64 bit double.
And it lets you know.
Float f=34.89;
Here you must either cast to the value or append an f to the
end of the literal
Float f=(float)34.89;
Float g=32.3f;
Assigning a literal that is too large for the variable:
We will get a compile time error if we are trying to assign
a big value into the variable
Byte a=128;//byte can only hold up to 127?
CE: possible loss of precision
Found: int
Required: bye
We can fix it with cast
Byte a=(byte)128;
What is the result?
When you are narrowing a primitive java simply truncates the
higher-order bits that won’t fit. It loses all the bits to the left to the bits
you are narrowing up
Ex: above example 128 is the bit pattern 100000000. It takes
a full 8 bits to represent 128. But because the literal 129 is an int. we
actually get 32 bits with the 128 living in the rightmost(lower order) 8 bits .
so a literal 128 is
00000000 00000000 00000000 10000000
Here 32 bits are there.
To narrow 32 bits representing 128 , java simply lops off
the leftmost(higher order) 24 bits. Hence 10000000 remains. Hence either byte
is singed and the leftmost bit representing a sign. so we end up with a negative
number
For finding the value of negative number using 2’s
complement notation. You flip all of the bits and then add 1.
Flipping the 8 bits gives us 01111111, and adding 1 to that
gives us 10000000 or back to 128. And when we apply the sing bit we get -128.
Compound assignment operator:
Byte b=3;
B + =7;// No problem adds 7 to b
And it is equivalent to
Byte b=3;
B=(byte) (b+7)//won’t compile without the cast, since b+7
results an int
The compound assignment operator += lets you add to the
value of b, without putting in an explicit cast, in fact ( +=,-=,*=,/= )will all
put in the implicit cast.
Assigning one primitive variable to another primitive
variable:
When you assign one primitive to another the content of the
right hand side copied.
Ex: int a=6;
Int b=a;
Here the pattern of a copied and place the copy into
variable b. but if we change the contents of either a or b , theother variable
won’t effect.
Int a =10;
Int b=a;
B=30;
Sop(a +’’ +b);
10
30
iii.
Reference
Variable Assignments:
You can assign a
newly created object to an object reference variable as follows
Button b=new Button();
It makes a reference variable named b, of type Button
Creates a new Button object on the heap
Assigns the newly created Button, object to the reference
variable b
You can also assign null to an object reference variable.
Which means variable is not referring to any object
Button c=null;
The preceding line creates space for the Button reference
variable(the bit holder for a reference variable) but it doesn't create an actual
button object.
You can also assign a subclass of the declared type but not
a superclass of the declared type.
Ex:
Public class Foo{
Public void doFooStuff(){}
}
Public class Bar extends Foo{
Public void doBarStuff(){}
}
Class Test{
Public s v main(-){
Foo reallyABar = new Bar();/legal because Bar is the
subclass of Foo
Bar reallyAFoo=new Foo();//illegal Foo is not a subclass of
bar
Note : assigning primitive with respective Wrapper class.
Long x=new Long(42);//create an instance of Long with value
42
Short s=new Short(“57”);//create an instance of short with
value 57
A wrapper object is an object that holds the value of a
primitive. Every kind of primitive has an associated wrapper class: Boolean,
Byte, Character, Double, Float ,Integer ,Long, and Short,
Sop(x+””+s);
o/p: 42 57
------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------
3.
SCOPE:
i.
Variable
scope:
Class Layout{//class
Static int s=343;//static variable
Int x; //instance variable
{x=7 ; int x2=5;}//initialization block
Layout(){
X+=8; int x3=6;}//constructor
Void doStuff(){ //method
Int y=0;//local variable
For(int z=0; z< 4;z++)
Y ==z+x;
}
}
}
Variables scope in this program:
·
S is a
static variable
·
X is an instance variable
·
Y is a local variable(method local)
·
Z is a block variable
·
X2 is an init block variable, a flavor of local
variable
·
X3 is a constructor variable, a flavor of local
variable
For a scope of variable:
·
Static variables have the longest scope; they are
created when the class is loaded and they survive as long as the class loaded
in the JVM
· Instance variable are the next most long-lived ; they are created when a new
instance is created and they live until the instance is removed
·
Local
variables are next, they live as long as their method remains on the stack.
However local variables can be
alive and still be “out of scope”
·
Block
variables live only as long as the code block is executing
Scoping errors come in may
sizes and shapes.
Most common error is an attempt to access a variable that is not in
scope.
Ex 1: attempting to access
instance variable form static content
Class scopeError{
Int x=5;
P static void main(-){
X++;//won’t compile x is an instance variable
}
}
Ex 2:
Attempting to access a local
variable from a nested method
Class ScopeErrors{
Public static void main(-){
socpeErrors s=new ScopeErrors();
s.go();
}
Void go(){
Int y=5;
Go2();
Y++;//once go2 completes, y is back
in scoe
}
Void go2(){
Y++;//won’t compile , y is local to
go()
}
}
Ex 3: attempting to use a block variable after a code block has
completed.
Void go3(){
For(int z=0;z <5 ; z++){
Boolean test=false;
If(z==3){
Test = true;
Break;
}
}sop(test);// test is an ex-variable it has ceased to be…
}
CE: cannot find the symbol for the last two examples
ii.
Variable
Initialization:
Using a Variable or Array Element That is Uninitialized and Unassigned:
When we attempt to use the uninitialized
variable, we can get different behaviour depending on the type of variable or
array we are dealing with . and also depends on the level(scope) at which we
are declaring our variables.
Local variables sometimes called
stack, temporary, automatic, or method variables.
i. Primitive and object type Instance Variables:
Instance variables or member
variables defined at the class level. Instance variables are initialized to a
default value each time a new instance is created, although they may be given
an explicit value after the objects’ super constructor have completed.
Default values for Primitives and
Reference types
Variable type
|
Default value
|
Object reference
|
Null
|
Byte,short,int,long
|
0
|
Float , double
|
0.0
|
Boolean
|
false
|
Char
|
‘\u0000’
|
Primitive Instance Variables:
Class A{
Int a;//instance variable
When the program is started, it
gives the variable a default value zero.
It’s a good idea to initialize all
your variables, even if you are assigning them with default value. your code
will be easier to read; programmers who have to maintain your code.
Object Reference Instance Variables:
Public class A{
Public String title;// instance
reference variable
Public Stirng getTitle(){
Return title;}
Main(){
A a=new A();
Sop(a.getTitle());
}
}
o/p: null
the title variable has not been
explicitly initialized with a string assignment. So that instance variable
value is null.
Public class Book{
Private String title;
Public String getTitle()
{
Return title;
}
Public static void main(String
args[]){
Book b=new Book();
String s=b.getTitle();//Compiles
and runs
String t=s.toLowerCase();//Runtime
Exception
}
}
The JVM produces:
Exception in thread “main”
java.lang.NullPointerException
At Book.main(Book.java)
Because here the reference variable
title doesn't point to an object. We can check to see weather the object has
been initialized by null keyword
If(s!=null)
String t=s.toLowerCase();
The value of s is a copy of the
value of title so if title is null reference s will be too.
ii. Array Instance Variables:
An array is an object not an instance variable hence the not explicitly initialized will have a value of null.
The array elements are always, given default values, regardless of where the
array itself is declared or instantiated.
If we initialize array, object
reference elements will equal null if they are not initialized individually
with values. If primitives are contained in array, they will be give their
respective default values.
iii. Local(Stack, Automatic) Primitives and Objects:
Local variables are defined within
a method, and they include a methods parameters.
Local Primitives:
Local variables including
primitives must be initialized before you attempt to use them. Java doesn't
give any default value to the local variables
Ex:
Class Timetravle{
P static voidmain(String args[]){
Int year;//local variable (declared
but not initialized)
Sop(“the year “+year);
}
}
CE: variable year may not have been
initialized
but ,We can declare the variables:
Class Timetravel{
P s v main(-){
Int year;//declared but not initialized
Int day;//declared but not
initialized
Sop(“you step into the prtal”);
Year=2000;//initialize
Sop(“Wecome to the year”+year);
}
}
Compiler may not always tell whether
local variable has been initialized before use.
Ex: public class TestLocal{
P s v main(-){
Int x;
If(arg[0]!=null){//assume you know
this is true
X=7;//compiler can’t tell the
statement will run
}
Int y=x;//the compiler will choke
here
}
}
CE: variable x might not have been
initialized
Because compiler can’t tell for
certain problem, you will sometimes need to initialize your variable outside
the conditional block, just to make the compiler happy.
Local Object Reference:
For the compiler null is a value.
locally declared references can’t get away with checking for null before use,
unless you explicitly initialize the local variable null.
Ex:
Ex:
Import java.util.Date;
Class TeimTravel{
P s v main(-){
Date date;
If(date==null)
Sop(“date is null”);
}
}
CE: variable date may not have been
initialized
For local references are not give a
default value; they aren't null. If you don’t initialize it doesn't have any
value at all;
Local Arrays:
You must explicitly initialize an
array reference if its’ declared and used within a method, but at the moment
you construct an array object, all of its elements are assigned their default
values.
Assigning one reference variable to another:
If you assign reference variable a1
to reference variable b1, the bit patter in a1 is copied and the new copy is
placed in b1.if we assign an existing instance of the object to a new reference
variable then two reference variable swill hold the same bit. Pattern—a bit
pattern referring to a specific object on the heap
Import java.awt.Dimension
Class ReferenceTest{
P s v main(-){
Dimension a1=new Dimension(5,10);
Sop(a.high);
Dimension b1=a1;
B1.height=30;
Sop(a1.height+”after change”);
}
}
o/p:
10
30 after change
Her both a1,b1 refer to same
object.
One exception for the objects
reference is String. Because String objects are immutable you can’t change the
value of the String object.
Ex:
Class String Test{
P s v main(-){
String x=”Java”;//assign a value to
x
String y=x;//now y and x refer to
the same String object
Sop(“y string”+y);
X =x+”Bean”;//Now modify the object
using the x reference
Sop(“y String”+y);
}
}
o/p:
y String = Java
Y String = Java
Any time we make any changes at all
to a String the VM will update the reference variable to refer to a different
object.t the different object might be a new object or it might not be but it
will definitely be different object. The reason we can’t say for sure whether a
new object is created because of String constant pool
What happens when you use a String
reference variable to modify:
·
A new String is created (or a matching String is
found in the String pool ) leaving the original String object untouched
·
The reference
used to modify the String (or rather , make a new String by modifying a
copy of the original) is then assigned the brand new String object.
·
So when you say
String s=”Fred”
String t=s;// now t and s refer to the same string object
t.toUpperCase()//invoke a string method that changes the
string
you haven’t changed the original object created at line 1 when line 2 completes both t and s reference the same String object but when
line 3 runs rather than modifying the object referred by t and s a brand new string object is created.
And then its abandoned. Because the new string isn't assigned to a string
variable the newly created string is toast. So although two String objects are
created in the preceding code only one is actually important in the exam .
Passing Variables
into Methods:
Methods can be declared to take primitives and object
references. We must know how the caller’s variables can be effected by the
called method.
i.
Passing
Object Reference Variables:
When we pass object variable into a method, we are passing
the object reference and not the actual object itself. a Reference variable
holds bits that represent (to the underlying VM) a way to get the specific
object in memory(on the heap) . you are not even passing the actual reference
variable, but rather a copy of the reference variable a copy of a variable
means you get a copy of the bits in the variable. A copy of a variable means
you get a copy of the bits in that variable so when you pass a reference variable,
you are passing a copy of the bits representing how to get to a specific
object. In other words both the called and the called method will no have
identical copies of the reference. Thus bot will refer to the same exact (not
copy) object on the heap.
Ex: import java.awt.Dimension;
Class ReferenceTest{
P s void main(String s[]){
Dimension d=new Dimesnion(5,10);
ReferenceTest rt=new ReferenceTest();
Sop(“Before modify() d.hight”+d.height);
Rt. Modify(d);
Sop(“AfterModify() d.height”+d.height);
}
Void modify(Dimension dim)
{
Dim.height=dim.height();
Sop(“dim=” +dim.height);
}
}
o/p:
Before modify() d.height=10
Dim=11
After modify() d.height=11
Does Java use Pass By
Value Semantics?
Not exactly. Java is actually a pass-by-value for all
variables running within a single VM. Pass by value means pass by variable
value. and that means pass-by-copy of the variable.
It makes no difference if you are passing primitive or
reference variables; you are always passing a copy of the bits in the variable.
The called method can’t change the caller’s variable,
although for object reference variables
,the called method can change the caller’s object the variable referred to.
What is the difference between changing the variable and changing
the object?
For object referenced it means the called method can’t reassign
the caller’s original reference variable and make it refer to a different
object or null.
Ex:
Void bar(){
Foo f=new Foo();
doStuff(f);
}
Void doStuff(Foo g){
g.getName(“Boo”);
g=new Foo();
}
Reassigning g doesn’t reassign f! at the end of the bar()
method, tow Foo object have been created one referenced by the local variable f
and one referenced by the local variable g. Because the doStuff() method has a copy of the reference
variable.it has a way to get to the original Foo object, for instance to call
the setName() method. But doStuff() method doesn’t have a way to get to the f
reference variable.so doStuff() can change the values within the object f refer to but doStuff() can’t change the
actual contents(bit pattern) of f. In other words, doStuff() can change the
state of the object that f refers to but it can’t make f refer to a different
object.
ii.
Passing
Primitive Variables:
Class ReferenceTest{
P s v main(-){
Int a=1;
ReferenceTest rt=new ReferenceTest();
Sop(“Before modify()a =”+a);
Rt.modify(a);
Sop(“After modify()a =”+a);
}
Void modify(int number)
{
Number=number+1;
Sop(“number =”+number);
}
}
o/p:
Before modify a=1
Number =2
After modify a=1
Note : when primitive variable is passed to a method it is
passed by values, which means pass by copy of the bits in the variable
Shadowing:
Shadowing involves reusing a variable name that is already
been declared somewhere else.
Ex:
Class Foo{
Static int size=7;
Static void change(int size)
{
Size= size+200;
Sop(“size in changeIt is “+size);
}
P s v main(-){
Foo f=new Foo();
Sop(“size”+size);
changeIt(size);
sop(“size after change IT is :”+size);
}
}
o/p:
size 7
size in changeIT is 207
size after change it is 7
what happens if the shadowing
variable is an object not a primitive?
class Bar{
int barNum=28;
}
Class Foo{
Bar myBar=new Bar();
Void changeIt(Bar myBar){
myBar.barNum=99;
sop(“myBar.barNum in changeIt is “+myBar.barNum);l
myBar=new Bar();
myBar.barNum=420;
sop(“myBar.barNum is changeIt is now”+myBar.barNum);
}
Public static v main(-){
Foo f=new Foo();
Sop(“f.myBar.barNum is “+f.myBar.barNum);
f.changeIt(f.myBar);
sop(“f.myBar.barNum after change it is”+f.myBar.barNum);
}
}
o/p:
f.myBar.barNum is 28
f.myBar.barNum is 28
myBar.barNum is 99
myBar.barNum in change It is 420
f.myBar.barNum after changeIt is 99
you can see that the shadowing variable (the local parameter
myBar in changeIt()) can still affect the myBar a reference to the saminstance variable, because the myBar parameter receivese Bar object. But when the local
myBar is reassigned a new Bar object, which we then modify by changing its
barNum value, Foo’s original myBar instance variable is untouched.
Key points:
Stack and Heap:
Local variable (method variables)
live on the stack
Objects and their instance variables live on the heap
Literals and
Primitive Casting:
Integer literals can be binary, decimal, octal, or
hexadecimal
Literals for longs end int L or l
Float literals end in F or f, and double literals end in a
digit or D or d
The Boolean for chars are a single character inside single quotes
’d’
Scope:
Scope refers to the lifetime of the variable
There are four types of basic scopes:
i.
Static variables live basically as long as their
class lives.
ii.
Instance variables live as long as their object
lives
iii.
Local variables Live as long as their method is
on the stack; however if their method invokes another method, they are
temporarily unavailable
iv.
Block variables (for example in a for or an if)
live until the block completes
Basic Assignments:
i.
Literal integers are implicitly ints
ii.
Integer expressions always results in an int
sized result never smaller
iii.
Floating point numbers are implicitly doubles(64
bit)
iv.
Narrowing a primitive truncates the high order
bits
v.
Compound assignments (such as +=) perform an
automatic cast
vi.
A reference variable holds the bits that are
used to refer to an object
vii.
Reference variables can refer to subclasses of
the declared type but not to super classes
viii.
When you create a new object , such as Button
b=ne Button() the JVM does the things
Makes a reference variable named b, of type Button
Creates a new Button object
Assign this Button object to the reference
variable b
Using a Variable or
Array Element that is Uninitialized and Unassigned:
When an array of objects is instantiated , objects within
the array are no instantiated automatically , but all the references get the
default value of null
When an array of primitives is instantiated elements get
default values
Instance variables are always initialized with a default
value.
Local/automatic/method variables are never given a default
value. if you are tempt to use one before initializing it, you will get a
compiler error.
Passing variables
into method:
Methods can take primitive and/or object reference as arguments
Method arguments are always copies.
Method arguments are never actual objects (they can’t be
reference to objects)
A primitive argument is an unattached copy of the original
primitive
A reference argument is another copy of a reference to the
original object
Shadowing occurs when two variables
with different scopes share the same name. This leads to hard to find bugs and
hard to answer the exam questions.
Operators
1. Increment and Decrement operator
2. Arithmetic operators
3. String concatenation operators
4. Relational
5. Equality
6. Instanceof
7. Shortcircuit
8. Bitwise
9. Typecast
10. Assignment
11. Conditional
12. Newoperators
13. [] operator
14. Operator precedence
15. Evaluation order of operands
1. Increment and Decrement operators:
increment:
increment:
Pre-increment: ++x
Post-increment: x++
Expression
|
Initial value of x
|
Value of y
|
Final value of x
|
Y=++x
|
10
|
11
|
11
|
Y=x++
|
10
|
10
|
11
|
Y=--x
|
10
|
9
|
9
|
Y=x--
|
10
|
10
|
9
|
i. We can apply increment and decrement operators only for variables but not for constant values.
Ex:
Int x=4;
Int y=++x;
Sop(y);
Ex: int x=4;
Int y=++4;
Sop(y);
CE: unexpected type
Found: value
Required: variable
ii. Nesting of increment and decrement operators not applicable .otherwise we will get compile time error
Int x=4;
Int y=++(++x);
Sop(y);l
CE: unexpected type
Found: value
Required: variable
iii. We can’t perform increment and decrement operators for final varaibles
Ex: final int x=4;
X++;
Sop(x);
CE: can’t assign value to final variable ‘x’
iv. We can apply increment and decrement operators for every primitive.
Ex:
Int x=10
X++;
Sop(x);
Output: 11
|
Char ch=’a’;
Ch++;
Sop(ch);
o/p: b
|
Double d=10.5;
D++;
Sop(d);
o/p: 10.5
|
v.
Boolean b=true;
Boolean b=true;
B++;
Sop(b);
CE: operator ‘++’ can’t be applied to Boolean
Difference between “b++” and “b=b+1”
If we apply any arithmetic operator between two variables a and b the result type is always.
Max(int ,type of a, type of b)
Byte-àshortàint-àlongàfloatàdouble
Charà int-àlongàfloatàdouble
Ex:
Byte a=10;
Byte b=20;
Byte c=a+b;
Sop©;//CE: possible loss of precision found:int required:byte
Max(int, byte,byte);//int
Byte c=(byte)(a+b);//o/p: 30
Ex 2:
Byte b=10;
B=b+1;
Sop(b);
Ce: Possible loss of precision
Found: int
Required: byte
If we type b=(byte)b+1;//11
In the case of increment and decrement operators internal typecasting will be performed by the compiler automatically
B++;
B=(type of b)(b+1);
Ex: byte b=10;
B++;
Sop(b);//ll
2. Arithmetic Operators (+,-,*, /, %):
if we apply any arithmetic operator between two variables a and b the result type is always max(int, type of a, type of b)
if we apply any arithmetic operator between two variables a and b the result type is always max(int, type of a, type of b)
Byte+byte = int
Byte+short=int
Short+short=int
Char+char=int
Char+int=int
Long+int=long
Long+float=float
Float+double=double
Char+double=double
Ex: sop(‘a’+’b’);//195
Sop(‘a’+1);//98
Sop(‘a’+0.0);//97.0
Infinity: in integral arithmetic (byte, short, int, long) there is no way to represent infinity. Hence if infinity is the result we will get Runtime Exception saying Arithmetic Exception in integral arithmetic.
Ex: sop(10/0);
RE: division by zero
But in floating point arithmetic(float,double) there is a way to represent infinity.
For this float and double classes( Wrapper Classes) contains the following constants.
Positive infinity
Negative infinity
Hence if the result is infinity we won’t get any arithmetic exception in floating point arithmetic.
Ex: sop(10/0);àinfinity
Sop(-10/0);àinfinity
Not a Number:
In integral arithmetic byte,short, int, long there is no way to represent undefined results hence if the request is undefined we will get RE saying: Arithmetic Exception
But in Floating point arithmetic there is no way to represent undefined results for those Float and Double classes contains “NaN constants”. Result is undefined we don’t get any AE in floating point.
Ex: sop(0/0);
Division by zero
Sop(0.0/0);NaN
Sop(-0/0.0);NaN
Sop(-0/0.0);NaN
Sop(10>Float.Nan);false
Sop(10<Float.Nan);false
Sop(10==Float.Nan);false
Sop(Float.Nan==Float.Nan);//invalid statement
Sop(Float.Nan!=10);valid
Sop(10>=Float.NaN);//invalid statement
Sop(10!=Float.NaN);
For any x-value including NaN, the following ex returns false
X>Float.NaN//false
x>=Float.NaN//false
x<Float.NaN//false
x<=Float.NaN//false
x==Float.NaN//false
x!=Float.NaN//true
àfor any x-value including NaN, the following expression returns
ArithmeticExpression:
It is RE but not CE
It occurs only in integral arithmetic not in floating arithmetic
The only operators which cause AE are “/” and “%”.
3. String Concatenation opearator(+):
The only overloaded operator in Java is “+” operators sometimes it acts as Arithmetic addition operator and sometimes it acts as string concatenation operator.
If at least one argument is String type then ‘+’ operator acts as concatenation and if both arguments are number type then ‘+’ operator acts as Arithmetic addition operator.
Ex:
String a=”durga”;
Int b=10,c=20,d=30;
Sop(a+b+c+d);//durga 10 20 30
Sop(b+c+d+a);//60 durga
Sop(b+c+a+d);//30 durga 30
Sop(b+a+c+d);//10 durga 20 30
Consider the following declarations:
String a=”durga”;
Int b=10,c=20,d=20;
Which of the following declarations are valide?
i. A=b+c+d;
CE: incompatible types
Found: int
Req:java.lang.String
ii. A=a+b+c;//valid
iii. B=a+c+d;CE: incompatible types found: java.lang.String required: int
iv. B=b+c+d;//valid
4. Relational Operator(<,<=,>,>=)
We can apply relational operator for every primitive type except boolean.
Ex:
Sop(10<20);//true
Sop(‘10’>10);//true
Sop(‘a’>’b’);//false
Sop(10<10.5);//true
Sop(true<false);
CE: operator < can’t be applied to Boolean we can’t apply relational operators for object types.
Ex: sop(“durga123”>”durga”);
CE: operator > can’t be applied to java.lang.String
We can’t perform Nesting of Relational opearators
Ex: sop(10<20<30);
CE: operator < can’t be applied to Boolean,int, equality , opearators.(==,!=)
we can apply equality operators for every primitive type including Boolean type.
Sop(10==10.0);//true
Sop(‘a’==97);//true
Sop(false==false);//true
We can apply equality operators for object types also for object reference r1 and r2
(r1==r2) is true iff both references pointing to the same object i.e ==
Operator always meant for Reference comparison (address comparison)
Ex: Thread t1=new Thread();
Thread t2=new Thread();
Thread t3=t1;
Sop(t1==t2);//false
Sop(t1==t3);//true
5. Difference between == operator and .equals method:
We can use == operator for reference comparision (address comparision) where as .equals() fro content comparision
String s1=new String(“durga”);
String s2=new String(“durga”);
Sop(s1==s2);//false
Sop(s1.equals(s2));//true
Hence if objects are differenc == operator returns false eventhouth content is same
.equals() returns true if the content is same evethough objects are different
To use equality operators between object types compulsory there should be some relationship between argument types otherwise we will get compiletime error saying incompatible types the relationship can be either parent or child or child to parent or same type
Ex: thread t1=new Thread();
Object o1=new Object()
String s1=new String(“durga”);
Sop(t1==o1);//false
Sop(o1==s1);//false
Sop(t1==s1);
CE: incompatible types java.lang.Thread ;java.lang.String for any object reference r,(r==null) is always false but (null==null) is always true.
Ex: Thread t=new Thread();
Sop(t==null);//false
Thread t=null;
Sop(t==null);//true
Sop(null==null)//true
6. Instanceof operator:
we can use instance of operator to check wether the given object is of particular type or not
syntax: r instanceof x
r is object reference and x is class/interface
Ex: thread t=new Thread();
Sop(t instanceof Thread);//true
Sop(t instanceof Object);//true
Sop(t instanceof Runnable);//true
Thread is child class of object
Thread implements Runnable interface
To use instanceof operator compulsory there should be some raltionship between argument types, otherwise we will get CE saying incovertable types
Ex:
Thread t=new Thread();
Sop(t instanceof String);
CE: incovertable types
Found: java.lang.Thread
Required: java.lang.String
Whenever we are checking parent object is of child type or not by using instanceof operator then we will get flase as output.
Ex: object o=new Object();
Sop(o instanceof String)//false
Object o=new String(“durga”);
Sop(o instanceof String);//true
For any class or interface ‘X’
Null instanceof x is always false
7. Bitwise operator:
1. & AND if both arguments are true then only the result true
2. | OR if at least one argument is true then result is true
3. ^ XOR if both arguments are different then result is true
Ex:
Sop(true & false);//false
Sop(true | false);//true
Sop(true ^ false);//true
Sop(4 & 5);//4
Sop(4/5);//5
Sop(4^5);//1
100---4
101---5
001---1
We can apply bitwise operators even for integral types also
Bitwise complement operator (~):
We can use this operator only for integral types but not for Boolean type.
Ex: sop(~true);
CE: operator ~ can be applied to Boolean
2. sop(~4);//-5
+4=00000100
-4=11111011—2s complement
Note : the most significant but represent sign bit ‘0’ means “+ve” 1 means “-ve” numbers will be represented directly in the memory where as –ve numbers will be represented in 2s complement form.
Boolean complement operator(!):
We can apply this operator only for Boolean type but for integral types
Ex: sop(!4)
CE: Operator ! can’t be applied to int
Sop(!true);//false
Note:
Bitwise operators
& , |, ^ --apllicable for both Boolean and integral types
~--applicable only for integral types but not for Boolean type
!—applicable only for Boolean type not for integral types
Shortcircuit operator(&&, ||):these are exactly same as bitwise operators &, | except the following differences.
&,|
|
&&,||
|
Both arguments should be evaluated always
|
Second argument evaluation is optional if it is required then only it will be evaluated
|
Relatively performance is low we can apply for both integral and Boolean types
|
Relatives performance is high we can apply only for Boolean types but not for integral types
|
X && y => y is evaluated if ‘x’ is true i.e if x is false then y won’t evaluated x||y=> y will be evaluated if x is false
Ex: int x=10;y=15;
If(++x >10 & ++y<15)
{
++x;
}
Else{
++y;
}
Sop(x+”…”+y);
Operator
|
X
|
Y
|
&
|
11
|
17
|
|
|
12
|
16
|
&&
|
11
|
17
|
||
|
12
|
15
|
Ex:
Int x=10;
If(++x<10 && (x/0>1))
{
Sop(“Hello”);
}
Else
{
sop(“Hi”);
sop(“Hi”);
}
o/p: hi
if we replace && with & then we will get AE division by zero
Assignment Operator:
There are three types of assignment operators:
1. Simple assignment
Int x=10;
2. Chained assignment
Int a,b,c,d;
A=b=c=d=20;
Sop(“a “+a+” b”+b+” c”+c+” d”+d);//a=20 b=20 c=20 d=20
We can’t perform chained assignment at the time of declaration directly.
Ex 1: int a=b=c=d=20;
CE: can’t find symbol
Symbol : variable b
Location: class Name
Ex 2: int b,c,d;
Int a=b=c=d=20;//compiles fine
3. Compound Assignment:
Sometimes we can combine assignment operator with some other operator to form compound assignment operator
Ex: int x=10;
X+=20;
Sop(x);//30
The following is the list of all possible compound assignment operators in java
+=
|
-=
|
*=
|
%=
|
/=
|
&=
|
!=
|
^=
|
>>=
|
>>>=[unsigned
Right shift]
|
<<=
|
In compound assignment operators the required typecasting will be performed automatically by the compiler.
Ex: byte b=10;
B=b+1;
Sop(b);
CE: Possible LP
Found :int
Required : byte
Ex 2: byte b=10;
B++;
Sop(b);//11
Ex 3: byte b=10;
B+=1;
Sop(b);//11
Ex 4: byte b=127;
B+=3;
Sop(b);//-126
Ex 5:
Int a, b,c,d;
A=b=c=d=20;
A+=b-=c*=d/=2;
Sop(a+” …”+b+”….”+c+”…”+d);
o/p:
-160 … -180 …200 …10
New Operator:
We can use new operator to create objects . there is no delete operator in java because destruction of useless objects is the responsibility of Garbage collector
Conditional operator:(?:):
The only possible ternary operator in java is conditional operator.
Ex: int x=(true)?10:20
Sop(x);//10
We can perform nesting of conditional operator also
Int x=(10>20)?30L(40>50)?60:70);
Sop(x);//70
[] operator: we can use this operator to declare and create arrays.
Java Operator Precedence:
Unary operators
|
[],X++,X--,--X,++X, ~,!,new,<type>
|
Arithmetic operators
|
*,/,%,+,-
|
Shift operators
|
>>,<<,>>>
|
Comparision
|
<,<=,>,>=,instanceof
|
Equality operators
|
==, !=
|
Bitwise operators
|
&, ^
|
Shortcircuit operators
|
&&, ||
|
Conditional operators
|
?:
|
Assignment operators
|
=, i+=, -=, *
|
Evaluation order of operands:
There is no particular presidence for operands before applying any operator all oeprands will be eavaulated from left to rigt
Ex: class Test
{
P s v main(-){
Sop(m1(1)+(m1(2)*m1(3))/m1(4)+m1(5)*m1(6);
}
Public static int m1(int i)
{
Sop(i);
Return I;
}
}
Op: 1+2*3/4+5*6
1+6/4+5*6
1+1+30=2+30=32
Operands are the things on the right or left side of the operator. In Java there are a few exceptional operators that are overloaded
i. The + operator can be used to add two numeric primitives together or to perform a concatenation operation if either operand is a String.
ii. The &, |, and ^ operators can all be used in two different ways.
1. Assignment Operators:
When assigning a value to a primitive , size matters.
Reference variable is not an object it’s a way to get to an object
When assigning a value to a reference variable, type matters.
Compound Assignment Operators:
There are actually 11 or so compound assignment operators. But only the 4 most commonly used (+=,-=,*=,/=) .
Ex: y-=2; is equal to y=y-2;
Note: when using a compound operator, the expression on the right side of the = will always be evaluated first.
Ex: x*=2+5;
To be evaluated like
X=(x*2)+5//incorrect
Because multiplication has higher precedence than addition. Instead , however the expression on the right is always placed inside parentheses. It is evaluated like this:
X= x*(2+5);
2. Relational Operators:
Six relational operators (,,<=,>,>=,==, and !=). These operators always returns Boolean.
Ex: int x=6;
If(x<7){
//do something
}
Mostly Boolean value used in if test.
Java has four relational operators that can be used to compare any combination of integers. Floating-point numbers or characters
‘>’ greater thant
‘>=” greater than equal to
‘<’ less than
‘<=’ less than or equal to
Ex:
Class GuessAnimal{
P s v main(-){
String animal=”unknown”;
Int weight=700;
Char sex=’m’;
Double colorWavelenght=1.630;
If(weight >= 500)
{
Animal=”elephant”;
}
If(colorWavelength >1.62)
{
Animal=”gray” +animal;
}
If(sec<=’f’)
{
Animal=”female”+animal;
}
Syso(“The animal is a “+animal);
}
}
o/p:
The animal is a gray elephant
Its legal to compare character primitive with any number . when we are comparing a character with a character or with a number java will use the Unicode value of the character as the numerical value for comparision.
“Equality” Operators:
Java has two relational operators that compare two similar things and return Boolean.
Ø == Equal (known as equal to)
Ø != Not Equal (known as not equal to)
Each individual comparision can involve two numbers/chars/Boolean values/reference variables . you can’t compare incompatible types
There are four different types of things that can be tested:
Ø Numbers
Ø Characters
Ø Boolean primitives
Ø Object reference variables
Equality for primitives:
Comparing primitive values
Class ComparePrimitives{
Ps v main(-){
Sop(‘char ‘a’ == ‘a’?”+(‘a’ ==’a’));
Sop(‘char ‘a’ == ‘b’?”+(‘a’ ==’b’));
Sop(‘5 ! =6?”+(5 ==6));
Sop(‘5.0 ==5L?”+(5.0 ==5L));
Sop(‘true== false?’+(true == false));
Equality for Reference Variables:
Two reference variables can refer same object.
JButton a=new JButton();
JButton b=a;
Reference variables can be tested to see if they pointing to the same object by == operator. It looks at the bits in the variable.
Sop(“IS reference a==b ? ”+(a==b));
o/p: true
Note: don’t mistake = for == in a Boolean expression
Ex: Boolean b=false
If(b = true)
Sop(“ b is true”);
Else
Sop(“b is false”);here the Boolean variable ‘b’ is not being compared to true; it is being set to true. Once b is set to true , the println executes and we get b is ture. The result of any assignment expression is the value of the variable following the assignment. This substation of = for ==works only for Boolean variables. Sicn ethe if test can be done only on Boolean exprdessions.
Ex: int x=1;
If(x=0);;this won’t compile
Equality for Strings and Java.lang.Object.equals()
Every class in java inherits a method from class Object that tests to see if the two objects of the class are “equal” . So the equals() method is used to test if the two objects are meaningfully equal or not.
Eaquals() method
Ø What equals() method means in the class Object:
if two references point to different objects , even if they have the same values, the method will return false
if two references point to different objects , even if they have the same values, the method will return false
Ø What equals() method means in the class String:
It has been overridden in class String. When the equals() method is used to compare two strings, it will return true if the Strings have the same value. and return false if the strings have the different value. Stings equals() method values are case sensitive.
Ex:
class Budgie{
p s v main(-)
{
Budgie b1=new Budgie();
Budgie b2=new Budgie();
Budgie b3=b1;
String s1=” Bob”;
String s2=” Bob”;
String s3=”bob”; //lower case ‘b’
Syso(b1.equals(b2));//false, different object
Syso(b1.equals(b1));//true, same objects
Sop(s1.equals(s2));//true, same values
Sop(s1.equals(s3));//false, values are case sensitive
Equality for enums:
Once you declared enum, its not expandable. At runtime there is no way to make additional enum constants. You can either use == operator or equals() method to determine whether two variables are reffering to the same enum constant.
Class EnumEqual{
Enum Color {RED,BLUE};//; optional
Color c1=Color.RED;
Color c2=Color.RED;
If(c1==c2)
Sop(“==”);
If(c1.equals(c2))
Sop(“dot equal”);
}
}
o/p:
==
Dot equal
3. Instanceof Comparision:
Used only for object reference variables only, and you can use it to check whether an object is of a particular type . here type can be class or interface. Whether the object referred by the variable on the left side of the operator passes the IS-A test for the class or interface type on the right side.
Ex:
Public static void main(-)
{
String s=new String(“foo”);
If(s instanceof String)
Sop(“S is a String”);
}
}
o/p:
S is a String
Even if the object being tested is not an actual instantiation of the class type on the right side of the operator, instanceof will still return true if the object being compared is assignment compatible with the type of the right.
Ex:
Class A{}
Class B extends A{
Public static void main(-){
A myA=new B();
M2(myA);
}
Public static void m2(A a){
If(a instanceof B)
((B)a).doBstuff();//downcasting an A reference to a B reference
}
Public static void doBstuff()
{
Sop(“ ‘a ‘ refers to a B”);
}
}
o/p:
‘a’ refers to a B
Use of instanceof operator protects the program from attempting an illegal downcast.
Note:
If an object is said to be of a particular interface type if any of the object’s superclass implements the interface.
Interface Foo{}
Class A implements Foo{}
Class B extends A{}
…
A a =new A();
B b=new B();
The following are true
Ø a instanceof Foo
Ø b instanceof A
Ø b instanceof Foo //implemented indirectly
It is legal to test whether the null reference is an instance of a class.
Ex:
Class InstanceTest{
P s v main(-){
String a=null;
Boolean b=null instanceof String;
Boolean c=a instanceof String;
Sop(b +” “ +c);
}
}
o/p:
false false
instanceof compilerError:
comes when we test two different class hierarchies
class cat{}
class Dog{}
Dog d=new Dog();
Sop(d instanceof Cat)
Compilation fails there is no way that d could ever refer to Cat or a subtype of Cat.
Note: an array is always an instanceof object
Int [] nums=new int[3];
If(nums instanceof Object){}//result is true.
Ex: use of instanceof operator
Summarize:
Interface Face{}
Class Bar implements Face(){}
Class Bar implements Face{}
Class Foo extends Bar{}
Operands and Results using instanceof operator
First Operand(Reference being tested)
|
Instanceof operand (Type we are comparing the Reference Against)
|
Result
|
Null
|
Any class or interface type
|
Flase
|
Foo instance
|
Foo, Bar, Face, Object
|
True
|
Bar instance
|
Bar, Face, Object
|
True
|
Bar instance
|
Foo
|
False
|
Foo[]
|
Foo, Bar,Face
|
False
|
Foo[]
|
Object
|
True
|
Foo[]
|
Foo, Bar, Face, Object
|
true
|
4. Arithmetic Operators:
Basic arithmetic oeprators:
Ø + addition
Ø - subtraction
Ø * multiplication
Ø / division
The Remainder(%) operator (a.k.a the Modules Operator):
Divides the left operand by the right operands, And the result is remainder.
Ex: int x=15;
Int y=x%4;
Sop(y);
Note: expressions are evaluated from left to right by default . you can change this sequence or precedence by adding parenthesis . also remember the *,/ and % operators have a higher precedence thant the + or – operators.
When working with ints the remander and the division operator relate to each other in an interesting way
The modulus operator throws out everything but the remainder
The division operator throws out the remainder
String concatenation operator:
Combines two stings it also combines when you include numbers.
Ex: String a=”Stirn”;
Int b=3;
Int c=7;
Sop(a+b+c);
o/p: Stirng37
the int values were simply treated as characters and glued on to the right side of the String.
If you say
Sop(a +(b+c));//10
Using parenthesis cause (b+c) evaluate first.
If either operand is a Stirng, the + operator becomes a String concatenation operator. If both operands are numbers , the + operator is the addition operator.
It’s legal to much together the compound additive operator(+=) and Strings like so:
String s=”123”;
S +=”45”;
S +=67;
Sop(s);
o/p:
123456
Note: int b=2;
Sop(“” +b+3);
o/p: 23 not 5
Increment and Decrement Operators:
Ø ++ increment (prefix and postfix)
Ø -- decrement (prefix and postfix)
Class MAthTest{
Static int players=0;
P s v main(-){
Sop(“players online” +players++);
Sop(“the value of players is “+players);
Sop(“the value of players is now “+ ++players);
}
}
o/p:
players online : 0
The value of players is 1
The value of players is now 2
Ex: int x=2, y=3;
If((y==x++) |(x<++y)){
Sop(“x=”+x+”y”+y);
]
o/p:
x=3 y=4
Note: you cant’ apply incrementd and decreament on final variables
Final int x=5;
Int y=x++;
CE; can’t assing a value to final variable x
5 Conditional Operator:
It is a ternary operator used to evaluate Boolean expressions.
This uses question makr(?) and : (colon);
X=(Boolean expression)?value to assing if true:value to assing it false
A conditional operator starts with a boolean operation, followed by two possible values for the variable to the left of the assginemnt(=) operator. The first value is assigned if the conditional test is true. And the second value is assigned if the conditional test is false.
5. Logical Operators:[not in java exam]
(&, |,^,!,&&, and ||)
Bitwise Operators:
Ex:
Byte b1= 6& 7;//legal
Byte b2= 7|9//legal
Byte b3=5^4//legal
Bitwise operators compare two varibles bit by bit and return a variable whose bits have been set based on whether the two variables being compared had respective bits that were either both “on”(&) , one or the other “on” (|) , or exactly one “on” (^) . by the way , when we run the preceding code, we get
0 15 1
Short-Cirtcuit Logical Operators:
used to evaluate statmeents that containe more than one Boolean expression.
used to evaluate statmeents that containe more than one Boolean expression.
2 operaros:
Ø && short-circuit AND
Ø || Short Circuit OR
&&: to be true , both operands must be true
If((2<3) && (3<4)){}
A short circuit evaluates left side of the operation first, and if it resolves to false, the && operator doesn’t bother looking at the right side of the expression since the && operarot already knows that the complete expression can’t possibly true.
|| it evaluates true if EITHER of the operands is true.If the first operand is true, the result will be true.
If the first operands is false then only the short circuit should evaluate second operands to see if the result of the OR operand will be true or false.
&& and || operator works only on Boolean operands.
Ex: if( 5 && 6)//illegal
Logical Operators(not shortcircuit)
Thow non-short-circuit operators
Ø & Non-short-circuit AND
Ø | Non short circuit OR
These operatos evaluate both side of the expression always. They are ineffificent. Ex: even if the first operand in an d& expression is flase, the second operand will still be evaluated even though its now impossible for the result to be true. And the | is just as inefficient ; if the first operand is true , the JVM still plows ahead and evaluates the second operand even when it knows the expression will be true regardless.
Logical Operators ^ and !
Tow logical operators
Ø ^ Exclusive – OR(XOR)
Ø ! Boolean invert
Evaluates only Boolean values. The ^ operator is related to the non-short-circuit operators.it always evaluates the both the left and right operands in an expression. For Exclisive-oR9^) expression to be true, Exactly one operand must be true.
Ex:
Sop(“xor” +((2<3) ^(4>3));
Xor flase
The ! operator returns the opposite of a boolean’s current value.
If(!(7==5)){
Sop(“not equal”);
}
o/p: not equal
KEY POINTS:
Relationl Operators:
Ø Relational operators always result in a Boolean value(true or false)
Ø There are six relational operators: >,<,>=,<=,==, and != the last tow are sometimes referred as equality operators
Ø When comparing characters, java uses the Unicode value of the characters as the numerical value
Ø Equality operators
There are two equality operators: == and !=
Four types of things can be tested : numbers, characters, Booleans, and referred valriables
Ø When comparing reference variables, == returns true only if both references refer to the same object.
Instanceof Operator:
Ø Instanceof is for reference variables only; it check whether the object is of a particular type
Ø The instanceof operator can be used only to test objects(or null) against class types that are in the same class hierarchy
Ø For instances , an object passes the instanceof test if any of its superclasses implement the interface on the right side of the instanceof operator.
Arithmetic Operators:
Ø The four primary math operators and add(+), subtract (-), multiply(*), and divide(/).
Ø The reaminder operator (%) returns the remainder of a division
Ø Expressions are evaluated form left to right, unless you add parantheses, or unless some operators in the expression have higher precedence than others.
Ø The *,/, and % operators have higher precedence htant + and –
String Concatenation Operator:
Ø If either operand is a String, the + operator concatenates the operands
Ø If both operands are numeric, the + operato add the operands
Increment and Decrement Operators:
Ø Prefix operators (++x,--x) run after the value is used in the expression
Ø Postfix operators(x++,x--) run after the value is used in the expression
Ø In any expression, both operands are fully evaluated before the operator is applied
Ø Variables marked final can’t be incrementd or decremented
Ternary(Conditional) operator:
Ø Returns on of tow values based on whether its boolean expression is true or false
Returns the value after the ? if the expression is true
Returns the value after the : if the expression is false
Logical Operators:
Ø The exam covers six “logical operators: & | ^ ! && and ||”
Ø Logical operators work two expressions(excepti !) that must resolve to Boolean values.
Ø The && and & operators return true only if both operands are true
Ø The || and | operators return true if either of both operands are true
Ø The && and || operators are knowsn as short-circuit operators
Ø The && operator does not evlaluate the right operand if the left operand is false
Ø The || doesn’t evaluate the right operand if the left operand is true
Ø The & and | operators always evaluate both operands
Ø The ^ operator( called the logical XOR) returns true if exactly one operand is true
Ø The ! operator(called the “inversion” operator) returns the opposite value of the Boolean operand it precedes.
Comments
Post a Comment