Operators in Java
Operators in Java
Example:
num1 = 10;
num2 = 20;
res=(num1>num2) ? (num1+num2):(num1-num2)
Since num1<num2,
the second operation is performed
res = num1-num2 = -10
import java.io.*;
class Ternary {
public static void main(String[] args)
{
// variable declaration
int n1 = 5, n2 = 10, max;
Output
First num: 5
Second num: 10
Maximum is = 10
import java.io.*;
class Ternary {
public static void main(String[] args)
{
// variable declaration
int n1 = 5, n2 = 10, res;
Output
First num: 5
Second num: 10
Result = -5
// Driver Class
public class TernaryOperatorExample {
// main function
public static void main(String[] args)
{
boolean condition = true;
String result = (condition) ? "True" : "False";
System.out.println(result);
}
}
Output
True
Bitwise Operators
Bitwise operators are used to performing the manipulation of individual bits of a
number. They can be used with any integral type (char, short, int, etc.). They are
used when performing update and query operations of the Binary indexed trees.
Now let’s look at each one of the bitwise operators in Java:
1. Bitwise OR (|)
This operator is a binary operator, denoted by ‘|’. It returns bit by bit OR of input
values, i.e., if either of the bits is 1, it gives 1, else it shows 0.
Example:
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)
~ 0101
________
1010 = 10 (In decimal)
Note: Compiler will give 2’s complement of that number, i.e., 2’s complement of
10 will be -6.
Java
Explain
// bitwise and
// 0101 & 0111=0101 = 5
System.out.println("a&b = " + (a & b));
// bitwise or
// 0101 | 0111=0111 = 7
System.out.println("a|b = " + (a | b));
// bitwise xor
// 0101 ^ 0111=0010 = 2
System.out.println("a^b = " + (a ^ b));
// bitwise not
// ~00000000 00000000 00000000 00000101=11111111 11111111
11111111 11111010
// will give 2's complement (32 bit) of 5 = -6
System.out.println("~a = " + ~a);
Output
a&b = 5
a|b = 7
a^b = 2
~a = -6
a= 5
Auxiliary space:O(1)
Time complexity:O(1)
Java
Explain
class GFG {
public static void main (String[] args) {
String binary[]={
"0000","0001","0010","0011","0100","0101",
"0110","0111","1000","1001","1010",
"1011","1100","1101","1110","1111"
};
// bitwise and
int d= a & b;
// bitwise xor
int e= a ^ b;
// bitwise not
int f= (~a & b)|(a &~b);
int g= ~a & 0x0f;
System.out.println(" a= "+binary[a]);
System.out.println(" b= "+binary[b]);
System.out.println(" a|b= "+binary[c]);
System.out.println(" a&b= "+binary[d]);
System.out.println(" a^b= "+binary[e]);
System.out.println("~a & b|a&~b= "+binary[f]);
System.out.println("~a= "+binary[g]);
}
}
Output
a= 0011
b= 0110
a|b= 0111
a&b= 0010
a^b= 0101
~a & b|a&~b= 0101
~a= 1100
Bit-Shift Operators (Shift Operators)
Shift operators are used to shift the bits of a number left or right, thereby
multiplying or dividing the number by two, respectively. They can be used when
we have to multiply or divide a number by two.
Syntax:
number shift_op number_of_places_to_shift;
Types of Shift Operators:
Shift Operators are further divided into 4 types. These are:
1. Signed Right shift operator (>>)
2. Unsigned Right shift operator (>>>)
3. Left shift operator(<<)
4. Unsigned Left shift operator (<<<)
Note: For more detail about the Shift Operators in Java, refer Shift Operator in
Java.
program to implement all Bitwise operators in java for user input
Java
Explain
import java.util.Scanner;
input.close();
}
}
Input
Enter first number: 4
Enter second number: 8
Output
Bitwise AND: 0
Bitwise OR: 12
Bitwise XOR: 12
Bitwise NOT: -5
Bitwise Left Shift: 16
Bitwise Right Shift: 1
Bitwise Unsigned Right Shift: 1
Explanation
This program prompts the user to enter two numbers, num1 and num2. It then
performs the following bitwise operations using the &, |, ^, ~, <<, >>, and >>>
operators:
Bitwise AND
Bitwise OR
Bitwise XOR
Bitwise NOT
Bitwise Left Shift
Bitwise Right Shift
Bitwise Zero Fill Right Shift
Advantages
The advantages of using Bitwise Operators in Java are:
1. Speed: Bitwise operations are much faster than arithmetic operations as they
operate directly on binary representations of numbers.
2. Space Optimization: Bitwise operations can be used to store multiple values in
a single variable, which can be useful when working with limited memory.
3. Bit Manipulation: Bitwise operators allow for precise control over individual
bits of a number, which can be useful in various applications such as
cryptography, error detection, and compression.
4. Code Simplification: Bitwise operations can simplify the code by reducing the
number of conditional statements and loops required to perform certain tasks.
In summary, Bitwise Operators are an important tool for optimizing performance,
improving code readability, and reducing code complexity in Java applications.
Signed Left The left shift operator moves all bits by a given number of
<<
Shift bits to the left.
Signed Right The right shift operator moves all bits by a given number of
>>
Shift bits to the right.
Unsigned It is the same as the signed right shift, but the vacant
>>>
Right Shift leftmost position is filled with 0 instead of the sign bit.
class GFG {
byte a = 64, b;
int i;
i = a << 2;
import java.io.*;
// Main class
class GFG {
int number = 2;
System.out.println(Ans);
}
Output
8
2. Signed Right Shift Operator in Java
The Right Shift Operator moves the bits of a number in a given
number of places to the right. The >> sign represents the right
shift operator, which is understood as double greater than. When
you type x>>n, you tell the computer to move the bits x to the
right n places.
When we shift a number to the right, the least significant bits
(rightmost) are deleted, and the sign bit is filled in the most
considerable place (leftmost).
Syntax:
left_operand >> number
Illustration:
Calculate the value of number>>2 if number=8.
When the value of a number is shifted to the right two places, the
rightmost two bits are lost. The number has a value of eight. 1000
is the binary representation of the number 8. The following is an
example of how to perform the right shift:
In the example above, the binary number 1000 (in decimal 8)
becomes 0010 after shifting the bits to the right (in decimal 2).
Example:
Java
import java.io.*;
class GFG
int number = 8;
System.out.println(Ans);
Java
class GFG {
char hex[]={
'0','1','2','3','4','5',
'6','7','8','9','a','b','c',
'd','e','f'
};
Java
import java.io.*;
class GFG
{
byte num1 = 8;
Output
2
1073741822
Note: For negative bits, the signed and unsigned right shift
operators provide different results.
4. Unsigned Left Shift Operator in Java
Unlike unsigned Right Shift, there is no “<<<” operator in Java
because the logical (<<) and arithmetic left-shift (<<<)
operations are identical.
import java.io.*;
// Main class
class GFG {
// Returning instanceof
Output
true
// Class 1
// Parent class
class Parent {
// Class 2
// Child class
// Class 3
// Main class
class GFG {
// A simple case
else
System.out.println(
System.out.println(
else
System.out.println(
System.out.println(
else
System.out.println(
Output
cobj is instance of Child
cobj is instance of Parent
cobj is instance of Object
class Main {
// A simple case
else
System.out.println(
Output
tobj is NOT instance of Test
class Parent {
// Driver Class
class Test {
// main function
else
System.out.println(
}
}
Output
pobj is NOT instance of Child
class Parent {
// Driver class
class Test {
// main function
else
System.out.println(
Output
cobj is instance of Child
class Parent {
// Driver class
class Test {
System.out.println(
+ ((Child)par).value);
Output
Value accessed through parent reference with typecasting is 10
Mechanism of System.out.print()
Java System.out.println() is used to print an argument that is passed
to it.
Parts of System.out.println()
The statement can be broken into 3 parts which can be understood
separately:
1. System: It is a final class defined in the java.lang package.
2. out: This is an instance of PrintStream type, which is a public and
static member field of the System class.
3. println(): As all instances of the PrintStream class have a public
method println(), we can invoke the same on out as well. This is an
upgraded version of print(). It prints any argument passed to it and
adds a new line to the output. We can assume that System.out
represents the Standard Output Stream.
Syntax:
System.out.println(parameter)
Parameters: The parameter might be anything that the user
wishes to print on the output screen.
Example of Java System.out.println()
Example 1:
Below is the implementation of System.out.println :
Java
// System.out.println();
import java.io.*;
// Driver Class
class GFG {
// main function
System.out.println("Welcome");
System.out.println("To");
System.out.println("GeeksforGeeks");
Output
Welcome
To
GeeksforGeeks
Example 2:
Below is the implementation of System.out.println :
Java
// System.out.println();
import java.io.*;
// Driver Class
class GFG {
// main function
// Declaring variable
System.out.print(
System.out.println(num1 + num2);
Output
The addition of 10 and 20 is: 30
Just like System.out, Java provides us with two other standard or
default input-output streams:
1. System.in: This is the standard input stream that is used to
read characters from the keyboard or any other standard input
device. Example:
InputStreamReader inp = new InputStreamReader(System.in);
2. System.err: This is the standard error stream that is used to
output all the error data that a program might throw, on a
computer screen or any standard output device.
Example:
System.err.print("Error");
Overloads of println() method
As we know, Method Overloading in Java allows different methods
to have the same name, but different signatures or parameters
where each signature can differ by the number of input
parameters or type of input parameters or both. From the use of
println() we observed that it is a single method of PrintStream
class that allows the users to print various types of elements by
accepting different type and number of parameters.
For example:
System.out.println(),
System.out.println(int),
System.out.println(double),
System.out.println(string),
System.out.println(character),
etc.
PrintStream has around 10 different overloads of println()
method that are invoked based on the type of parameters
passed by the user.
Example:
Java
// overloading in println()
import java.io.*;
// Driver Class
class PrintLN {
// main function
char ch = 'G';
double d = 10.2;
float f = 13.5f;
System.out.println();
System.out.println(num);
System.out.println(ch);
System.out.println(str);
System.out.println(d);
System.out.println(f);
System.out.println(bool);
System.out.println("Hello");
Output
10
G
GeeksforGeeks
10.2
13.5
true
Hello
import java.io.*;
// Driver Class
class Demo_print {
// main function
public static void main(String[] args)
System.out.println("Using print()");
// using print()
// same line
System.out.print("GfG! ");
System.out.print("GfG! ");
System.out.print("GfG! ");
System.out.println();
System.out.println();
System.out.println("Using println()");
// using println()
// different line
System.out.println("GfG! ");
System.out.println("GfG! ");
System.out.println("GfG! ");
Output:
Using print()
GfG! GfG! GfG!
Using println()
GfG!
GfG!
GfG!
Performance Analysis of System.out.println()
println() is a method that helps display output on a console. This
might be dependent on various factors that drives the
performance of this method. The message passed using println()
is passed to the server’s console where kernel time is required
to execute the task. Kernel time refers to the CPU time. Since
println() is a synchronized method, so when multiple threads are
passed could lead to the low-performance issue.
System.out.println() is a slow operation as it incurs heavy
overhead on the machine compared to most IO operations. There
is an alternative way of performing output operations by
invoking PrintWriter or the BufferedWriter class. They are fast
as compared to the println() of the PrintStream class.
Explain
Output
a+b/d = 20
a+b*d-e/f = 219
2. Be a Compiler:
The compiler in our systems uses a lex tool to match the greatest
match when generating tokens. This creates a bit of a problem if
overlooked. For example, consider the statement a=b+++c; too many
of the readers might seem to create a compiler error. But this
statement is absolutely correct as the token created by lex is a, =, b, +
+, +, c. Therefore, this statement has a similar effect of first assigning
b+c to a and then incrementing b. Similarly, a=b+++++c; would
generate an error as the tokens generated are a, =, b, ++, ++, +, c.
which is actually an error as there is no operand after the second
unary operand.
Java
Explain
// a=b+++c is compiled as
// b++ +c
// a=b+c then b=b+1
a = b++ + c;
System.out.println("Value of a(b+c), "
+ " b(b+1), c = " + a + ", " + b
+ ", " + c);
// a=b+++++c is compiled as
// b++ ++ +c
// which gives error.
// a=b+++++c;
// System.out.println(b+++++c);
}
}
Output
Value of a(b+c), b(b+1), c = 10, 11, 0
3. Using + over ():
When using the + operator inside system.out.println() make sure to do
addition using parenthesis. If we write something before doing
addition, then string addition takes place, that is, associativity of
addition is left to right, and hence integers are added to a string first
producing a string, and string objects concatenate when using +.
Therefore it can create unwanted results.
Java
Explain
// concatenates x and y as
// first x is added to "concatenation (x+y) = "
// producing "concatenation (x+y) = 5"
// and then 8 is further concatenated.
System.out.println("Concatenation (x+y)= " + x + y);
// addition of x and y
System.out.println("Addition (x+y) = " + (x + y));
}
}
Output
Concatenation (x+y)= 58
Addition (x+y) = 13
Advantages of Operators in Java
The advantages of using operators in Java are mentioned below:
1. Expressiveness: Operators in Java provide a concise and readable
way to perform complex calculations and logical operations.
2. Time-Saving: Operators in Java save time by reducing the amount
of code required to perform certain tasks.
3. Improved Performance: Using operators can improve performance
because they are often implemented at the hardware level, making
them faster than equivalent Java code.
Disadvantages of Operators in Java
The disadvantages of Operators in Java are mentioned below:
1. Operator Precedence: Operators in Java have a defined
precedence, which can lead to unexpected results if not used
properly.
2. Type Coercion: Java performs implicit type conversions when
using operators, which can lead to unexpected results or errors if
not used properly.