Operators
Operators
Introduction to JAVA
By
Arvind Kumar
Asst. Professor, LPU
Contents
• Naming convention
• Primitive data types
• Operators in Java
• Arithmetic Operators
• Bitwise Operators
• Relational Operators
• Logical Operators
• Data Types
Identifiers and Naming Conventions
Names of things that appear in the program are called identifiers.
Rules:
An identifier is a sequence of characters that consists of letters,
digits, underscores (_), and dollar signs ($).
An identifier must start with a letter, an underscore (_), or a dollar
sign ($). It cannot start with a digit.
An identifier cannot be a reserved word.
An identifier cannot be true, false, or null.
An identifier can be of any length.
Casting converts a value of one data type into a value of another data type
* widening a type – 1. Casting a variable of a type with a small range to a
variable of a type with a larger range can be
performed automatically (implicit casting)
* narrowing a type – 1. Casting a variable of a type with a large range to a
variable of a type with a smaller range must be
performed explicitly (explicit casting)
Type Conversion, Casting and Promotion
1. Numeric Type Conversions
Implicit casting
double d = 3; (type widening)
Explicit casting
int i = (int)3.0; (type narrowing)
int i = (int)3.9; (Fraction part is truncated)
1. Arithmetic
2. Bitwise
3. Relational
4. Logical.
Arithmetic Operators
• Used in mathematical expressions.
• We can not use them on boolean types, but we can use them
on char types, since the char type in Java is a subset of int.
Arithmetic Operators
Operator Result
+ Addition
- Subtraction (also unary minus)
* Multiplication
/ Division
% Modulus
++ Increment
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
- - Decrement
class ArithmeticOp
{ public static void main(String args[])
{
int a = 2 + 1; int b = a * 2; int c = b / 4; int d = c - a; int e = -d;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
System.out.println("e = " + e);
double p = 2 + 1; double q = p * 2; double r = q / 4; double s = r -a; double t = -q;
System.out.println(“p = " + p);
System.out.println(“q = " + q);
System.out.println(“r = " + r);
System.out.println(“s = " + s);
System.out.println(“t = " + t);
}
}
Modulus Operator (%)
Operator Result
== Equal to
!= Not equal to
• Here, the type of var must be compatible with the type of expression.
• The assignment operator does have one interesting attribute that you
may not be familiar with: it allows you to create a chain of
assignments. For example, consider this fragment:
o int x, y, z;
o x = y = z = 100; // set x, y, and z to 100
• This fragment sets the variables x , y, and z to 100 using a single
statement.
The ? Operator
• Java includes a special ternary (three-way)operator that can
replace certain types of if-then-else statements.