Open In App

Left Shift Operator in Java

Last Updated : 20 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The decimal representation of a number is a base-10 number system having only ten states 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. For example, 4, 10, 16, etc.

The Binary representation of a number is a base-2 number system having only two states 0 and 1. For example, the binary representation of 4, a base-9 decimal number system is given by 100, 10 as 1010, 16 as 1000, etc.

Left Shift

The left shift means that shift each of the bits is in binary representation toward the left.

Logical Left Shift

Logical Left Shift

For example, when we say left shift 5 or 101 by one position. We will shift each of the bits by one position towards the left. So after shifting the number 5 towards the left by one position, the number obtained is 10 or 1010. Now let us again left shift 10 by two positions. Again, we will shift each of the bits by two positions towards the left. The number obtained is 40 or 101000.

Note: Left shifting a number by certain positions is equivalent to multiplying the number by two raised to the power of the specified positions. That is,

left shift x by n positions <=> x * 2n 

Left Shift Operator in Java

Most of the languages provide left shift operators using which we can left shift a number by certain positions and Java is one of them. The syntax of the left-shift operator in Java is given below,

Syntax:

x << n

Here,
x: an integer
n: a non-negative integer 

Return type: An integer after shifting x by n positions toward left

Exception: When n is negative the output is undefined

Below is the program to illustrate how we can use the left shift operator in Java.

Example 1:

Java




// Java program to illustrate the
// working of left shift operator
 
import java.io.*;
 
class GFG {
   
      // Main method
    public static void main (String[] args) {
         
        // Number to be shifted
        int x = 5;
           
        // Number of positions
        int n = 1;
         
        // Shifting x by n positions towards left using left shift operator
        int answer = x << n;
         
        // Print the number obtained after shifting x by n positions towards left
        System.out.println("Left shift " + x + " by " + n + " positions : " + answer);
         
        // Number to be shifted
        x = answer;
           
        // Number of positions
        n = 2;
         
        // Shifting x by n positions towards left using left shift operator
        answer = answer << n;
           
        // Print the number obtained after shifting x by n positions towards left
        System.out.println("Left shift " + x + " by " + n + " positions : " + answer);
         
    }
}


Output

Left shift 5 by 1 positions : 10
Left shift 10 by 2 positions : 40

Example 2:

Java




// Java program to illustrate the
// working of left shift operator
 
import java.io.*;
 
class GFG {
   
      // Main method
    public static void main (String[] args) {
         
        // Number to be shifted
        int x = -2;
           
        // Number of positions
        int n = 1;
         
        // Shifting x by n positions towards
        // left using left shift operator
        int answer = x << n;
         
        // Print the number obtained after shifting x by n positions towards left
        System.out.println("Left shift " + x + " by " + n + " positions : " + answer);
         
        // Number to be shifted
        x = answer;
           
        // Number of positions
        n = 2;
         
        // Shifting x by n positions towards
        // left using left shift operator
        answer = answer << n;
           
        // Print the number obtained after shifting x by n positions towards left
        System.out.println("Left shift " + x + " by " + n + " positions : " + answer);
         
    }
}


Output

Left shift -2 by 1 positions : -4
Left shift -4 by 2 positions : -16

Time complexity: O(1)

Space complexity: O(1)

Note: For arithmetic left shift, since filling the right-most vacant bits with 0s will not affect the sign of the number, the vacant bits will always be filled with 0s, and the sign bit is not considered. Thus, it behaves in a way identical to the logical (unsigned) left shift. So there is no need for a separate unsigned left sift operator.



Similar Reads

Shift Operator in Java
Operators in Java are used to performing operations on variables and values. Examples of operators: +, -, *, /, &gt;&gt;, &lt;&lt;. Types of operators: Arithmetic Operator,Shift Operator,Relational Operator,Bitwise Operator,Logical Operator,Ternary Operator andAssignment Operator. In this article, we will mainly focus on the Shift Operators in Java
4 min read
Bitwise Right Shift Operators in Java
In C/C++ there is only one right shift operator '&gt;&gt;' which should be used only for positive integers or unsigned integers. Use of the right shift operator for negative numbers is not recommended in C/C++, and when used for negative numbers, the output is compiler dependent. Unlike C++, Java supports following two right shift operators. Here w
2 min read
Double colon (::) operator in Java
The double colon (::) operator, also known as method reference operator in Java, is used to call a method by referring to it with the help of its class directly. They behave exactly as the lambda expressions. The only difference it has from lambda expressions is that this uses direct reference to the method by name instead of providing a delegate t
4 min read
Difference between concat() and + operator in Java
Strings are defined as an array of characters. The difference between a character array and a string is the string is terminated with a special character ‘\0’. Since arrays are immutable(cannot grow), Strings are immutable as well. Whenever a change to a String is made, an entirely new String is created. Concatenation is the process of joining end-
6 min read
&amp;&amp; operator in Java with Examples
&amp;&amp; is a type of Logical Operator and is read as "AND AND" or "Logical AND". This operator is used to perform "logical AND" operation, i.e. the function similar to AND gate in digital electronics. One thing to keep in mind is the second condition is not evaluated if the first one is false, i.e. it has a short-circuiting effect. Used extensiv
1 min read
|| operator in Java
|| is a type of Logical Operator and is read as "OR OR" or "Logical OR". This operator is used to perform "logical OR" operation, i.e. the function similar to OR gate in digital electronics. One thing to keep in mind is the second condition is not evaluated if the first one is true, i.e. it has a short-circuiting effect. Used extensively to test fo
1 min read
&amp; Operator in Java with Examples
The &amp; operator in Java has two definite functions: As a Relational Operator: &amp; is used as a relational operator to check a conditional statement just like &amp;&amp; operator. Both even give the same result, i.e. true if all conditions are true, false if any one condition is false. However, there is a slight difference between them, which h
2 min read
Diamond operator for Anonymous Inner Class with Examples in Java
Prerequisite: Anonymous Inner Class Diamond Operator: Diamond operator was introduced in Java 7 as a new feature.The main purpose of the diamond operator is to simplify the use of generics when creating an object. It avoids unchecked warnings in a program and makes the program more readable. The diamond operator could not be used with Anonymous inn
2 min read
Addition and Concatenation Using + Operator in Java
Till now in Java, we were playing with the integral part where we witnessed that the + operator behaves the same way as it was supposed to because the decimal system was getting added up deep down at binary level and the resultant binary number is thrown up at console in the generic decimal system. But geeks even wondered what if we play this + ope
2 min read
new Operator vs newInstance() Method in Java
In Java, new is an operator where newInstance() is a method where both are used for object creation. If we know the type of object to be created then we can use a new operator but if we do not know the type of object to be created in beginning and is passed at runtime, in that case, the newInstance() method is used.In general, the new operator is u
3 min read
instanceof operator vs isInstance() Method in Java
The instanceof operator and isInstance() method both are used for checking the class of the object. But the main difference comes when we want to check the class of objects dynamically then isInstance() method will work. There is no way we can do this by instanceof operator. The isInstance method is equivalent to instanceof operator. The method is
3 min read
new operator in Java
When you are declaring a class in java, you are just creating a new data type. A class provides the blueprint for objects. You can create an object from a class. However obtaining objects of a class is a two-step process : Declaration : First, you must declare a variable of the class type. This variable does not define an object. Instead, it is sim
5 min read
Java Ternary Operator Puzzle
Find the output of the program public class GFG { public static void main(String[] args) { char x = 'X'; int i = 0; System.out.print(true ? x : 0); System.out.print(false ? i : x); } } Solution: If you run the program,you found that it prints X88. The first print statement prints X and the second prints 88. The rules for determining the result type
2 min read
Java Ternary Operator with Examples
Operators constitute the basic building block of any programming language. Java provides many types of operators that can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they provide. Here are a few types:  Arithmetic OperatorsUna
4 min read
dot(.) Operator in Java
The dot (.) operator is one of the most frequently used operators in Java. It is essential for accessing members of classes and objects, such as methods, fields, and inner classes. This article provides an in-depth look at the dot operator, its uses, and its importance in Java programming. Dot(.) Operator in Java The dot operator is used to access
4 min read
Java Unary Operator with Examples
Operators constitute the basic building block to any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions be it logical, arithmetic, relational, etc. They are classified based on the functionality they provide. Here are a few types: Arithmetic Operators
8 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Print all palindromic paths from top left to bottom right in a matrix
Given a m*n matrix mat[][] containing only lowercase alphabetical characters, the task is to print all palindromic paths from the top-left cell to the bottom-right cell. A path is defined as a sequence of cells starting from the top-left and ending at the bottom-right, and we can only move right or down from any cell. Example: Input: mat = [['a', '
7 min read
C++ | Nested Ternary Operator
Ternary operator also known as conditional operator uses three operands to perform operation. Syntax : op1 ? op2 : op3; Nested Ternary operator: Ternary operator can be nested. A nested ternary operator can have many forms like : a ? b : ca ? b: c ? d : e ? f : g ? h : ia ? b ? c : d : e Let us understand the syntaxes one by one : a ? b : c =&gt; T
5 min read
How can we use Comma operator in place of curly braces?
In C and C++, comma (, ) can be used in two contexts: Comma as an operator Comma as a separator But in this article, we will discuss how a comma can be used as curly braces. The curly braces are used to define the body of function and scope of control statements. The opening curly brace ({) indicates starting scope and closing curly brace (}) indic
3 min read
Understanding RxJava Create and fromCallable Operator
In this article, we will learn about the RxJava Create and fromCallable Operators. We can choose between the required function based on what is required skillset is needed. We frequently make mistakes when utilizing RxJava Operators. Let's get this straight so we don't make a mistake. With examples, we shall study the following operations. Createfr
2 min read
RxJava Operator - Concat and Merge
RxJava is the most significant library, and it is widely used by Android developers. It simplifies our lives. RxJava is used for multithreading, managing background processes, and eliminating callback hells. RxJava allows us to address a wide range of complicated use-cases. It allows us to accomplish complex things in a very easy way. It gives us t
3 min read
Multiples of 3 and 5 without using % operator
Write a short program that prints each number from 1 to n on a new line. For each multiple of 3, print "Multiple of 3" instead of the number.For each multiple of 5, print "Multiple of 5" instead of the number.For numbers which are multiples of both 3 and 5, print "Multiple of 3. Multiple of 5." instead of the number. Examples: Input : 15 Output : 1
6 min read
Bitwise Complement Operator (~ tilde)
Pre-requisite:Bitwise Operators in C/ C++Bitwise Operators in Java The bitwise complement operator is a unary operator (works on only one operand). It takes one number and inverts all bits of it. When bitwise operator is applied on bits then, all the 1's become 0's and vice versa. The operator for the bitwise complement is ~ (Tilde). Example: Input
3 min read
Java AWT vs Java Swing vs Java FX
Java's UI frameworks include Java AWT, Java Swing, and JavaFX. This plays a very important role in creating the user experience of Java applications. These frameworks provide a range of tools and components for creating graphical user interfaces (GUIs) that are not only functional but also visually appealing. As a Java developer, selecting the righ
11 min read
Java.io.ObjectInputStream Class in Java | Set 2
Java.io.ObjectInputStream Class in Java | Set 1 Note : Java codes mentioned in this article won't run on Online IDE as the file used in the code doesn't exists online. So, to verify the working of the codes, you can copy them to your System and can run it over there. More Methods of ObjectInputStream Class : defaultReadObject() : java.io.ObjectInpu
6 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.lang.StrictMath class in Java | Set 2
Java.lang.StrictMath Class in Java | Set 1More methods of java.lang.StrictMath class 13. exp() : java.lang.StrictMath.exp(double arg) method returns the Euler’s number raised to the power of double argument. Important cases: Result is NaN, if argument is NaN.Result is +ve infinity, if the argument is +ve infinity.Result is +ve zero, if argument is
6 min read
java.lang.instrument.ClassDefinition Class in Java
This class is used to bind together the supplied class and class file bytes in a single ClassDefinition object. These class provide methods to extract information about the type of class and class file bytes of an object. This class is a subclass of java.lang.Object class. Class declaration: public final class ClassDefinition extends ObjectConstruc
2 min read
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap also contains functions that support retrieval and deletion at both, high and low end of values and hence give a lot of flexibility in applicability and daily use. This function is poll() and has 2 variants discussed in this article. 1. pollFirstEntry() : It removes and retrieves a key-value pair with the least key value in the ma
4 min read
Article Tags :
Practice Tags :