Chapter 5

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 44

CHAPTER 5

OPERATORS AND
EXPRESSIONS
ARITHMETIC OPERATORS
The arithmetic operators are the operators that perform any
basic form of mathematics. This include.
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Modulus.
OPERATOR DESCRIPTION EXAMPLE
CONSIDER A=10
AND B=10

ADDITION - Adds values on the either side A+B will


+ of the operator give 30

- SUBTRACTION - Subtracts right hand A-B will


operand from the left hand operand give-10

* MULTIPLICATION - Multiplies the values A*B will


on the either side of the operator give 200

/ DIVISION - Divides the left hand operand B/A will


by the right hand operand give 2
% MODULUS - Divides left hand operand by B%A will
the right hand operand and returns remainder give 0
Unary operators

 Unary operators are operators that only require one operand .

 They simply perform their operations on a single variable


,changing its value appropriately.

 The unary operators are

 +

 -

 ++

 --
1.The unary “+” operator refers to a positive value.
• It serves a no task except to emphasize that a value must be positive.
• Example:
int a = + 10;
int b = +a;
In the example b will contain a positive value of a .

2. The “-” operator refers to the negative value. It serves no task except
to emphasize that a value must negative.
Int a=20;
Int b = 6;
Int c = -a;
Int d = -b;
Int e = -50 +10;
in the example ,c and d contain negative value of a and b,being -20 and -
6 respectively .the value of e is -40;
Increment and decrement operator
(++ and --)
• The increment and decrement operators are very simple
operators that simple increase or decrease the value by 1.
• These operators are generally used in loops to increment or
decrement the counter variables.
• The increment operator adds 1 to its operand ,and decrement
operators subtracts 1
• x = x + 1; is the same as x++;
and
x = x - 1; is the same as x--;
• The increment and decrement operators can either prefix or
postfix the operand .
x = x +1 ; can be written as
++x; // in the prefix form or as x++; // postfix form

• If the operand follows its operand ,java will obtain the


operand’s value before incrementing or decrementing it.

x = 10;
y = ++x;
// first increment the value of x and then assign the value to y.

X= 10;
Y = x++;
// first the value of x is to y and the it will get increment.
The assignment operator
The assignment operator is the signal equal sign , = .this
behavior of assignment operator is similar to other
programming language like c and c++ .

The general syntax is :


Var = expression;
Example: age = 5;
Operators and expressions
• Shorthand Assignment Operator
• Relational Operators
• Bitwise Operators
Shorthand Assignment
Operator
• In many cases assignment operator can be combined
with other operators to build a shorter version of
statement called Compound Statement. For example,
instead of a = a+5, we can write a += 5.
• Java provides special shorthand assignment operators
that simplify the coding of certain assignment
statements.
• It is also called as Compound Assignment Operators.
• General syntax: var1 operator = var2.
• The above statement is same as,
var1 = var1 operator var2.
Operators Description Example
+= It adds left operand with the C+=A Equivalent to
right operand and assigns the C=C+A
result to left operand.
-= It subtracts left operand with C-=A Equivalent to
the right operand and assigns C=C-A
the result to left operand.
*= It multiplies left operand with C*=A Equivalent to
the right operand and assigns C=C*A
the result to left operand.
/= It Divides left operand with the C/=A Equivalent to
right operand and assigns the C=C/A
result to left operand.
%= It takes modulus using two C%=A Equivalent to
operands and assign the result C=C%A
to left operand.
<<= Left shift and assignment C<<=2 Equivalent to
operator. C=C<<2
>>= Right shift and assignment C>>=2 Equivalent to
operator. C=C>>2
&= Bitwise AND and assignment C&=2 Equivalent to
operator. C=C&2
^= Bitwise Exclusive OR and C^=2 Equivalent to
assignment operator. C=C^2
|= Bitwise Inclusive OR and C|=2 Equivalent to
assignment operator. C=C|2
• 2 BENEFITS:
a)They are more compact
b)They are implemented more
efficiently by the java run-time
system.
Relational Operators
• Relational operators are used to compare two
values and determine the relationship
between them.
• All these expressions return a Boolean value
that is true or false.
• The comparison of equality is done with the
double equal signs(==) as opposed to a single
equal sign(=). The single equal sign is used
only for value assignment.
Operator Description Ex:( A=20, B=30)
Checks if the value of two operands are equal or (A==B) is not
== not, if yes then condition becomes true. true
Checks if the value of two operands are equal or (A!=B) is true
!= not, if values are not equal the condition becomes
true.
Checks if the value of left operand is greater than (A>B) is not true
> the value of right operand, if yes then condition
becomes true.
Checks if the value of left operand is less than the (A<B) is true
< value of right operand, if yes then condition
becomes true.

Checks if the value of left operand is greater than (A>=B) is not


>= or equal to the value of right operand, if yes then true
condition becomes true.

Checks if the value of left operand is less than or (A<=B) is true


<= equal to the value of right operand, if yes then
condition becomes true.
Bitwise Operators
• Bitwise operator works on bits and performs
bit by bit operation.
• The operations on bits are performed on 1s
and 0s only.
• Example: A=60 and B=13 (A&B)
A=00111100 B=00001101
Ans: 12 (00001100).
Operator Description Example
& Binary AND operator. (A&B)

| Binary OR operator . (A|B)

^ Binary XOR operator . (A^B)

~ Binary Ones Complement (~A)


operator is unary and has the
effect of negative bits.
<< Binary Left Shift operator. A << 2

>> Binary Right Shift operator. A >> 2

>>> Binary Unsigned Right Shift A>>> 2


Operator or Shift right Zero fill
operator.
The Result of applying Bitwise operators
between two corresponding bits.
Operator Example Same as Result Decimal

& 5&1 0101 & 0001 0001 1

| 5|1 0101 | 0001 0101 5

~ ~5 ~0101 1010 10
^ 5^1 0101 ^ 0001 0100 4

<< 9 << 1 1001 << 1 0010 2

>> 9 >> 1 1001 >> 1 1100 12

>>> 9 >>> 1 1001 >>> 1 0100 4


• Bitwise Left shift:
Ex: 9<<1
1001<<1
1001 for 1 time
001 letting the leftmost bits fall off
0010 pushing zeroes in from the right

To perform a left shift operation on these


bits, we push each from its position to left,
depending on the number of pushes
specified. And fill the empty bits on the right
end with 0 value.
• Bitwise Right shift:
Ex: 9>>1
1001>>1
1001 for 1 time
100 letting the rightmost bits fall off
1100 pushing sign bit in from the left

To perform a right shift operation on these bits, we


push each from its position to right, depending on
the number of pushes specified. And fill the empty
bits on the left end with the original value of sign
bit.
• Bitwise Unsigned Right Shift Operator:
Ex: 9>>>1
1001>>>1
1001 for 1 time
100 letting the rightmost bits fall off
0100 pushing zeroes in from the left

It is similar to right shift operator, except


that, shift all bit values to the right and fill
empty bits on the left end with 0. Even if
signed bit is 1, fill with 0’s only.
HIGHLIGHTS
 ARITHMETIC OPERATORS
 UNARY OPERATORS
 ASSIGNMENT OPERATORS
 SHORT HAND OPERATORS
 RELATIONAL OPERATORS
 BITWISE OPERATORS
 CONDITIONAL OPERATOR
 INSTANCEOF OPERATOR
 ADDITIONAL OPERATORS
CONDITIONAL OPERATOR (?:)

The conditional operator is a ternary operator


it is used to evaluate expressions, much like
an if else statement except instead of
executing a block of code if the test is true, a
conditional operator will assign a value to a
variable.

The term ternary is used because this


operator consists of three operands which are
used to evaluate expressions.

 The ultimate aim of the operator is to decide


which value is to be assigned to the variable.
SYNTAX : variable x = ( expression ) ? value if true : value if false

IF ELSE STATEMENT
if( Expression 1) If to specify a block of code to be executed , if specified
{ condition is true.
Statements // block of code
Else to specify a block of code to be executed , if
}
else specified condition is false.
{ Conditional operator follows the same algorithm as of if-
Statements // block of code else statement, but it takes less space and helps to write
}
the if-else statements in the shortest way possible..
Instanceof operator
• It is used to check whether an object is an instance of a particular class
or not.
• The operator also checks whether an object is an instance of a class
that implements an interface
SYNTAX : (Object reference variable) Instanceof (class/interface type)
EXAMPLE :
Public static void main(String args[])
{
String name = “JAVA”;
System.out.println(“Is name an instance of String:” + (name
instanceof String));
}
OUTPUT :
Is name an instance of string : true
ADDITIONAL OPERATORS
 SEMI-COLON(;)
 CURLY BRACKETS { }
 PARENTHESES( )
 SQUARE BRACKETS [ ]
 COMMA (,)
 SINGLE QUOTE (‘)
 DOUBLE QUOTES (“)
 DOT OPERATOR (.)
 NEW OPERATOR (new)
SEMI COLON (;)
The semi-colon is used to indicate the end of an expression, a declaration or a statement
Example: System.out.println(“Hello”);

CURLY BRACKETS{ }
Curly Brackets are used to create a section of code. Curly brackets are also used to create variable
scope.
Example : class Test{ if(a>10) {
}}

PARENTHESES ( )
Parentheses are used to differentiate a method such as main from a regular variable. It is also used to
isolate an operation or an expression with regard to another operation or expression.
Example : main()
or
int a=(2*(9/3-1))*(4-8/2)
SQUARE BRACKETS [ ]

Square brackets are mostly used to control the dimension or index of an array.
EXAMPLE : int a[5];

COMMA ( , )
The comma is used to separate variables used in a group.

Example : String firstname , lastname , fullname;

SINGLE QUOTE ( ‘ )
The single quote is used to include one character to initialize or assign a symbol to , a
variable declared as char.

Example : char alphabet


alphabet= ‘A’;
DOUBLE QUOTES( “ “ )
Double quotes are used to delimit a string . We can include an empty
space , a character , a word or group of words making it a string.
Example : String str
Str = “HELLO WORLD”;

DOT OPERATOR ( . )
Dot operator is used to access the instance variables and methods of class using an object.
Example : function.f1;
function.simple();

NEW OPERATOR
The new operator is used to create objects . Instances of classes and arrays.
Example : Student age = new Student();
Expressions In Java

Expressions:
• An Expression is a Combination of variables, Literals,
and Operators.
• An expressions in java is any valid combination of
variables, literals and operators.
Example: In a expression x = 3;
Types of Expressions:
• Arithmetic Expressions
• Boolean Expressions
• String Expressions

Arithmetic Expressions:

• Java Arithmetic Expressions use arithmetic operators such as +,-,/,*, and %.


• Arithmetic Expressions are used to assign arithmetic values to variables.
• It also combine parentheses to an expression to calculate a value.
Examples: (a * b + c + 3) - 5.5
package expression;

public class ArithmeticExpression {

public static void main(String[] args) {


// TODO Auto-generated method stub
int a = 10;
int b = a + 2 – 3;
double c = b % 5;
double d = c+(a*2+b*100)/5;
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
}
}
Boolean Expressions:

• Java Boolean expressions are expressions which are true or false.


• The different Boolean operators are <,>,==,>=,<=,!=.
• A Boolean expression can also be a combination of other Boolean
expressions. Two or more Boolean expressions can be connected using &&
[logical AND] and || [logical OR] operators
• The && operator represents logical AND. The expression is true if both
Boolean expressions are true.
Example: int x=10; int y=4; int z=5;
(x<=10) &&(y>6)
• The || operator represents logical OR. The expression would be true if any
one of the associated expressions is true.
Example: (x*y==40)||(z==7)
public class Boolean {

public static void main(String[] args) {


// TODO Auto-generated method stub
int a = 10;
int b = 5;
System.out.println(a > b);
System.out.println(a < b);
System.out.println(a == b);
int c = 15;
int d = 25;
System.out.println(c >= d);
System.out.println(c <= d);
System.out.println(c != d);
int x = 10;
int y = 4;
int z = 5;
System.out.println((x<=10) && (y>1));
System.out.println((x*y==40)||(z==5));
}
}
String Expressions

• One Special expression in java is the use of the addition operator (+) to create
and concatenate Strings.
• Java string expressions are expressions which results in string. the string
expression may consist of operators, variable, literals and strings.

Example: System.out.println(“the value of a=“ +a+ “and b=“ +b);

• The + operators, when used with the strings and other objects, creates a single
string that contains the concatenation of all its operands.
• If any of the operands in string concatenation is not string, it is automatically
converted to a string
package expressions;

public class StringExpression {

public static void main(String[] args) {


// TODO Auto-generated method stub
String str1="java";
String str2 = str1 + "Programming";
System.out.println(str2);
String str3 = 9+5+1+"java";
System.out.println(str3);
String str4 = 9+(5+(1+"java"));
System.out.println(str4);
}

}
PRECEDENCE OF ARITHMETIC
OPERATORS

The java compiler must apply some rules to determine the order of execution
in expressions.
x = a * b + c * d / 10
Here, the expression is made up of five variable names (x , a , b , c and d)
and four operators ( = , * , + ,and /)
When the two or more operators occur in the same larger expression, the
compiler applies two rules
1. Precedence
2. Associativity
OPERATOR PRECEDENCE

• WHAT IS OPERATOR PRECEDENCE ?


Operator precedence determines the order in which expressions are
Evaluated . And Operators with a higher precedence are executed before
those of a lower precedence .

• Example for precedence .


1 + 2 * 3 is treated as 1 + (2*3)
1 * 2 + 3 is treated as (1 * 2)+ 3
Operator precedence
table
ASSOCIATIVITY

• WHAT IS ASSOCIATIVITY ?
When two operators have the same precedence associativity determines
evaluation order .
If an expression contains same precedence , in this case associativity
determines the evaluation order . Associativity can be either left –to- right or
right- to- left.
• Example for associativity.
x = y = z = 17 is treated as x = ( y = ( z =17)) this is right -to -left associativity .
72 / 2 / 3 is treated as (72 / 2 ) / 3 this is left- to - right associativity
MATHEMATICAL
• FUNCTIONS
The java.lang.Math contains a set of basic math functions for
obtaining the absolute value, highest and lowest of two
values, rounding of values, random values etc. These basic
math functions of the Java Math class will be covered in the
following methods.
• Math. Abs()
The Math. Abs() function returns the absolute value of the parameter passed to
it. The absolute value is the positive value of the parameter. If the parameter
value is negative, the negative sign is removed and the positive value
corresponding to the negative value without sign is returned.
EXAMPLE
int abs1 = Math.abs(10); // abs1 = 10
int abs2 = Math.abs(-20); // abs2 = 20


Math.min()
The Math.min() method returns the smallest of two values passed to it as
parameter.

EXAMPLE
int min = Math.min(10, 20);
• Math.max()
The Math.max() method returns the largest of two values passed to it
as parameter. Here is a Math.max() Java example:

EXAMPLE
Int max = Math.max(10, 20);

You might also like