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

Operators in Java

Operator in Java is a symbol which is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
Java Unary Operator
The Java unary operators require only one operand. Unary operators are used to perform various
operations i.e.:
o incrementing/decrementing a value by one
o negating an expression
o inverting the value of a Boolean.
Pre and post increment:
In pre increment, the value of the operand first increases and then used in the expression.
++a (pre- increment)
--a (pre- decrement)
In post increment, the value of the operand used in the expression and there after it’s value
increases.
a++ post increment
a—post decrement

Some examples:
class OperatorExample
{
public static void main(String args[])
{
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}
}
class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=10;
System.out.println(a++ + ++a);//10+12=22
System.out.println(b++ + b++);//10+11=21
}
}

class OperatorExample
{
public static void main(String args[])
{
boolean c=true;
boolean d=false;
System.out.println(!c);//false (opposite of boolean value)
System.out.println(!d);//true
}
}

Java Arithmetic Operators


Java arithmatic operators are used to perform addition, subtraction, multiplication, and division.
They act as basic mathematical operations.

class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}
}
Java Arithmetic Operator Example: Expression
class OperatorExample
{
public static void main(String args[])
{
System.out.println(10*10/5+3-1*4/2);
}
}
OUTPUT
21
Java Left Shift Operator
The Java left shift operator << is used to shift all of the bits in a value to the left side of a
specified number of times.
Java Left Shift Operator Example
Class OperatorExample
{
public static void main(String args[])
{
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
System.out.println(20<<2);//20*2^2=20*4=80
System.out.println(15<<4);//15*2^4=15*16=240
}
}
OUTPUT
40
80
80
240
Java Right Shift Operator
The Java right shift operator >> is used to move left operands value to right by the number of
bits specified by the right operand.
Java Right Shift Operator Example
class OperatorExample
{
public static void main(String args[])
{
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}
}
OUTPUT
2
5
2

Java Shift Operator Example: >> vs >>>


class OperatorExample
{
public static void main(String args[])
{
//For positive number, >> and >>> works same
System.out.println(20>>2);
System.out.println(20>>>2);
//For negative number, >>> changes parity bit (MSB) to 0
System.out.println(-20>>2);
System.out.println(-20>>>2);
}
}
OUTPUT
5
5
-5
1073741819
Java AND Operator Example: Logical && and Bitwise &
The logical && operator doesn't check second condition if first condition is false. It checks
second condition only if first one is true.

The bitwise & operator always checks both conditions whether first condition is true or false.
class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c);//false && true = false
System.out.println(a<b&a<c);//false & true = false
}
}
OUTPUT
false
false
Java AND Operator Example: Logical && vs Bitwise &
class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a++<c);//false && true = false
System.out.println(a);//10 because second condition is not checked
System.out.println(a<b&a++<c);//false && true = false
System.out.println(a);//11 because second condition is checked
}
}

OUTPUT
false
10
false
11

Java OR Operator Example: Logical || and Bitwise |


The logical || operator doesn't check second condition if first condition is true. It checks second
condition only if first one is false.
The bitwise | operator always checks both conditions whether first condition is true or false.
class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
System.out.println(a>b||a<c);//true || true = true
System.out.println(a>b|a<c);//true | true = true
//|| vs |
System.out.println(a>b||a++<c);//true || true = true
System.out.println(a);//10 because second condition is not checked
System.out.println(a>b|a++<c);//true | true = true
System.out.println(a);//11 because second condition is checked
}
}
OUTPUT
true
true
true
10
true
11

Overview of the Bitwise Operators


Java defines several bitwise operators, which can be applied to the integer types, long, int, short,
char, and byte.
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b = 13;
now in binary format they will be as follows −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011

Java Ternary Operator


Java Ternary operator is used as one liner replacement for if-then-else statement and used a lot in
Java programming. it is the only conditional operator which takes three operands.
Java Ternary Operator Example
class OperatorExample
{
public static void main(String args[])
{
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}
}
OUTPUT
2

Another Example:
class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}
}
OUTPUT
5
Java Assignment Operator
Java assignment operator is one of the most common operators. It is used to assign the value on
its right to the operand on its left.
int a=10,b=20;
a=b;
System.out.println(a+”\t”+b);
OUTPUT  20 20
In JAVA ‘b=a’ means, value of ‘a’ gets overlapped on ‘b’, while ‘a=b’ means, value of ‘b’ gets
overlapped on the variable ‘a’.
Difference between ‘= =’ & ‘=’
"= =" or equality operator in Java is a binary operator provided by Java programming language
and used to compare primitives and objects. ... so "= =" operator will return true only if two
object reference it is comparing represent exactly same object otherwise "= =" will return false.
Where as ‘=’ simple assignment operator. Assigns values from right side operands to left side
operand.
Java Assignment Operator Example
class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}
}
OUTPUT
14
16
Java Assignment Operator Example
class OperatorExample
{
public static void main(String[] args)
{
int a=10;
a+=3;//10+3
System.out.println(a);
a-=4;//13-4
System.out.println(a);
a*=2;//9*2
System.out.println(a);
a/=2;//18/2
System.out.println(a);
}
}
OUTPUT
13
9
18
9

Java Assignment Operator Example: Adding short


class OperatorExample
{
public static void main(String args[])
{
short a=10;
short b=10;
//a+=b;//a=a+b internally so fine
a=a+b;//Compile time error because 10+10=20 now int
System.out.println(a);
}
}
OUTPUT
Compile time error
After type cast:
class OperatorExample
{
public static void main(String args[])
{
short a=10;
short b=10;
a=(short)(a+b);//20 which is int now converted to short
System.out.println(a);
}
}
OUTPUT
20

MATHEMATICAL FUNCTIONS IN JAVA


Basic Math 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 sections.
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.
Here are two Math.abs() method examples:
int abs1 = Math.abs(10); // abs1 = 10
int abs2 = Math.abs(-20); // abs2 = 20
The absolute value of 10 is 10. The absolute value of -20 is 20.
The Math.abs() method is overloaded in 4 versions:

Math.abs(int)
Math.abs(long)
Math.abs(float)
Math.abs(double)
Which of these methods are called depends on the type of the parameter passed to
the Math.abs() method.
Math.ceil()
The Math.ceil() function rounds a floating point value up to the nearest integer value. The
rounded value is returned as a double. Here is a Math.ceil() Java example:

double ceil = Math.ceil(7.343); // ceil = 8.0


After executing this Java code the ceil variable will contain the value 8.0 .

Math.floor()

The Math.floor() function rounds a floating point value down to the nearest integer value. The
rounded value is returned as a double. Here is a Math.floor() Java example:

double floor = Math.floor(7.343); // floor = 7.0


After executing this Java code the ceil variable will contain the value 8.0.

Math.min()

The Math.min() method returns the smallest of two values passed to it as parameter. Here is
a Math.min() Java example:
int min = Math.min(10, 20);
After executing this code the min variable will contain the value 10.

Math.max()

The Math.max() method returns the largest of two values passed to it as parameter. Here is
a Math.max() Java example:
int max = Math.max(10, 20);
After executing this code the max variable will contain the value 20.

Math.round()

The Math.round() method rounds a float or double to the nearest integer using normal math
round rules (either up or down). Here is a Java Math.round() example:
double roundedDown = Math.round(23.445);
double roundedUp = Math.round(23.545);
After executing these two Java statements the roundedDown variable will contain the
value 23.0 , and the roundedUp variable will contain the value 24.0.
Math.random()

The Math.random() method returns a random floating point number between 0 and 1. Of course
the number is not fully random, but the result of some calculation which is supposed to make it
as unpredictable as possible. Here is a Java Math.random() example:
double random = Math.random();
To get a random value between 0 and e.g. 100, multiply the value returned
by Math.random() with the maximum number (e.g. 100). Here is an example of how that might
look:
double random = Math.random() * 100D;
If you need an integer value, use the round(), floor() or ceil() method.

Exponential and Logarithmic Math Functions


The Java Math class also contains a set of functions intended for exponential and logarithmic
calculations. I will cover some of these math functions in the following sections.
Math.exp()
The Math.exp() function returns e (Euler's number) raised to the power of the value provided as
parameter. Here is a Java Math.exp() example:
double exp1 = Math.exp(1);
System.out.println("exp1 = " + exp1);
double exp2 = Math.exp(2);
System.out.println("exp2 = " + exp2);
When this Java math code is executed it will print this output:
Output:
exp1 = 2.718281828459045
exp2 = 7.38905609893065

Math.log()
The Math.log() method provides the logarithm of the given parameter. The base for the
logarithm is i (Euler's number). Thus, Math.log() provides the reverse function of Math.exp().
Here is a Java Math.log() example:
double log1 = Math.log(1);
System.out.println("log1 = " + log1);
double log10 = Math.log(10);
System.out.println("log10 = " + log10);
The output from this Math.log() example is:
Output:
log1 = 0.0
log10 = 2.302585092994046
Math.log10()
The Math.log10 method works like the Math.log() method except is uses 10 as is base for
calculating the logarithm instead of e (Euler's Number). Here is a Math.log10() Java example:
double log10_1 = Math.log10(1);
System.out.println("log10_1 = " + log10_1);
double log10_100 = Math.log10(100);
System.out.println("log10_100 = " + log10_100);
The output printed from this Java Math.log10() example would be:
log10_1 = 0.0
log10_100 = 2.0
Math.pow()
The Math.pow() function takes two parameters. The method returns the value of the first
parameter raised to the power of the second parameter. Here is a Math.pow() Java example:
double pow2 = Math.pow(2,2);
System.out.println("pow2 = " + pow2);
double pow8 = Math.pow(2,8);
System.out.println("pow8 = " + pow8);
The output from this Math.pow() example would be:
Output:
pow2 = 4.0
pow8 = 256.0
In other words, the Math.pow() example calculate the values of 22 and 28 which are 4 and 256.

Math.sqrt()

The Math.sqrt() method calculates the square root of the parameter given to it. Here are a few
Java Math.sqrt() example:
double sqrt4 = Math.sqrt(4);
System.out.println("sqrt4 = " + sqrt4);
double sqrt9 = Math.sqrt(9);
System.out.println("sqrt9 = " + sqrt9);
The output printed from these Java Math.sqrt() examples would be:
Output:
sqrt4 = 2.0
sqrt9 = 3.0
Trigonometric Math Functions
The Java Math class contains a set of trigonometric functions. These functions can calculate
values used in trigonometry, like sine, cosine, tangens etc. I will cover the most used
trigonometry functions in the following sections. If you are looking for a trigonometric function
and you cannot find it here, check the JavaDoc for the Java Math class. The Math class just
might have the function you are looking for, even if I have not described it here.
Math.PI
The Math.PI constant is a double with a value that is very close to the value of PI - the
mathematical definition of PI. You will often need the Math.PI field when making trigonometric
calculations.
Math.sin()
The Math.sin() method calculates the sine value of some angle value in radians. Here is a
Java Math.sin() example:
double sin = Math.sin(Math.PI);
System.out.println("sin = " + sin);

To print Sin table from 00 to 900


class sinTable
{
public static void main(String ss[])
{
int i;
double x,y;
System.out.println("Angle\tSin Values");
for(i=0;i<=90;i++)
{
x=(Math.PI * i)/180.0;
y=Math.sin(x);
System.out.println(x+"\t"+y);
}
}
}

Alternate method
class sinTable
{
public static void main(String ss[])
{
int i;
double x,y;
System.out.println("Angle\tSin Values");
for(i=0;i<=90;i++)
{
x=Math.toRadians(i);
y=Math.sin(x);
System.out.println(x+"\t"+y);
}
}
}
Math.cos()
The Math.cos() method calculates the cosine value of some angle value in radians. Here is a
Java Math.cos() example:
double cos = Math.cos(Math.PI);
System.out.println("cos = " + cos);

Math.tan()
The Math.tan() method calculates the tangens value of some angle value in radians. Here is a
Java Math.tan() example:

double tan = Math.tan(Math.PI);


System.out.println("tan = " + tan);

Math.asin()
The Math.asin() method calculates the arc sine value of a value between 1 and -1. Here is a
Java Math.asin() example:
double asin = Math.asin(1.0);
System.out.println("asin = " + asin);

Math.acos()
The Math.acos() method calculates the arc cosine value of a value between 1 and -1. Here is a
Java Math.acos() example:
double acos = Math.acos(1.0);
System.out.println("acos = " + acos);

Math.atan()
The Math.atan() method calculates the arc tangens value of a value between 1 and -1. Here is a
Java Math.atan() example:
double atan = Math.atan(1.0);
System.out.println("atan = " + atan);

Math.toRadians()
The Math.toRadians() method converts an angle in degrees to radians. Here is a
Java Math.toRadians() example:
double radians = Math.toRadians(180);
System.out.println("radians = " + radians);

Java - Strings Class


Creating Strings
The most direct way to create a string is to write –
String greeting = "Hello world!";
Whenever it encounters a string literal in your code, the compiler creates a String object with its
value in this case, "Hello world!'
As with any other object, you can create String objects by using the new keyword and a
constructor. The String class has 11 constructors that allow you to provide the initial value of the
string using different sources, such as an array of characters.
Example
public class StringDemo
{
public static void main(String args[])
{
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String helloString = new String(helloArray);
System.out.println( helloString );
}
}
This will produce the following result −
Output
hello.

The String class is immutable, so that once it is created a String object cannot be changed. If
there is a necessity to make a lot of modifications to Strings of characters, then you should use
String Buffer class.

length() method, which returns the number of characters contained in the string object.
public class StringDemo
{
public static void main(String args[])
{
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
System.out.println( "String Length is : " + len );
}
}
Output
String length is : 17

The java string charAt() method returns a char value at the given index number.
The index number starts from 0 and goes to n-1, where n is length of the string. It returns
StringIndexOutOfBoundsException if given index number is greater than or equal to this string
length or a negative number.
public char charAt(int index)
{
if ((index < 0) || (index >= value.length))
{
throw new StringIndexOutOfBoundsException(index);
}
return value[index];
}
charAt() method example
public class CharAtExample
{
public static void main(String args[])
{
String name="javatpoint";
char ch=name.charAt(4);//returns the char value at the 4th index
System.out.println(ch);
}
}
Output:
t

StringIndexOutOfBoundsException with charAt()


Let's see the example of charAt() method where we are passing greater index value. In such case,
it throws StringIndexOutOfBoundsException at run time.
public class CharAtExample
{
public static void main(String args[])
{
String name="javatpoint";
char ch=name.charAt(10);//returns the char value at the 10th index
System.out.println(ch);
}
}
Output:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 10
at java.lang.String.charAt(String.java:658)
at CharAtExample.main(CharAtExample.java:4)

You might also like