Category: Java Tutorial

  • Java – Object-Oriented Programming concept

    Object-oriented programming:

    It is the concept of using objects in programming. It is a paradigm that uses objects and classes that aim to implement real-world entities. The entities such as inheritance, abstraction, polymorphism, etc that are used in programming.

    The main goal of an OOP is to tie together the data and its method in a single object so that no other block of code can access that data but only that function. And thus, it also makes it easier to work with.

    The main principle of OOP are:

    • Inheritance. 
    • Encapsulation. 
    • Abstraction. 
    • Polymorphism

    Inheritance:

    It is one of the main features of Object-Oriented Programming (OOP). Inheritance is one of the processes or mechanisms in OOP in which one class(sub-class) acquires the properties(data members) and functionalities(methods) of another class(parent-class).

    Super Class: The class whose properties and functionalities are inherited by the Subclass is known as the superclass(a parent class or a base class).

    Sub Class: The class that inherits the property and behavior of the other class(Superclass) is known as subclass( a derived class, extended class, or child class).

    Syntax:

     class Super
     {
      //field and methods
     }
     class sub extends Super 
     {
      //its own field and methods
     } 

    Also Learn Types of Inheritance with Diagram and Example:


    Encapsulation:

    Encapsulation is one of the four fundamental OOP concepts. Encapsulation in Java is defined as the wrapping up of data(variable) under a single unit. The use of Encapsulation is to make sure that implementation detail or we can say sensitive data is hidden from the users.

    For this, Encapsulation is also known as data hiding.

    Benefits of Encapsulation:

    • Data- hiding in Java.
    • The class field can be made read-only or write-only.
    • It provides the class the total control over the data.

    Syntax Example:

    public class Student
      {
        private String name; // private
    
        // Getter
        public String getName() 
        {
        return name;
        }
    
        // Setter
        public void setName(String newName) 
        {
        this.name = newName;
        }
      }

    Abstraction:

    Data abstraction is the process of hiding the details but only displaying the relevant information to the users, which is hiding the implementation details and displaying only its functionalities. This is one of the main advantages of using abstraction.

    Abstraction is one of the four major concepts behind object-oriented programming (OOP).

    In java, abstraction can be achieved in two ways.

    • Abstraction class.
    • Interfaces.

    1. Abstraction class.

    • An abstract class is a class that is declared with an abstract keyword.
    • An abstract class may or may not have abstract methods.
    • This class cannot create objects, to access this class, it must be inherited.
    abstract class ClassName {
      }

    2. Interfaces

    An Interface in Java is the same as class, like any other class, an interface can have methods and Variables.

    interface interface_name 
     {
        
      // declare constant fields, abstract methods
    
     }

    Polymorphism:

    Polymorphism means having many forms. The word “poly” means many and “morphs” means forms. In java, it is a concept that allows the user to perform a single action in different ways.

    In Java polymorphism is mainly divided into two types:

    1. Compile-time Polymorphism: 

    It is also known as static polymorphism. In this type of program, the flow of control is decided at compile time itself and if any error found, they are resolved at compile time. This can be achieved by method overloading.

    2. Runtime Polymorphism:

    It is also known as Dynamic Method Dispatch. It is a process in which a call to an overridden method is resolved at runtime. This type of polymorphism is achieved by Method Overriding.


  • Java – Inheritance

    It is one of the main features of Object-Oriented Programming (OOP). Inheritance is one of the processes or mechanisms in OOP in which one class(sub-class) acquires the properties(data members) and functionalities(methods) of another class(parent-class).

    Importance of Inheritance:

    • For Code Reusability.
    • For Method Overriding (to achieve runtime polymorphism).

    Important terms:

    • Super Class: The class whose properties and functionalities are inherited by the Subclass is known as superclass(a parent class or a base class).
    • Sub Class: The class that inherits the property and behavior of the other class(Superclass) is known as subclass( a derived class, extended class, or child class). The subclass can have its own fields and methods along with the fields and methods of the superclass.
    • Reusability: Inheritance supports the concept of “reusability”. This feature allows us to use the methods in the sub-class that is already present in the superclass, saving the time to rewrite the code.
    • extends: extends is the keyword that’s used by the base class so that it can inherit the properties of the superclass.

    Syntax:

     class Super
     {
      //field and methods
     }
     class sub extends Super 
     {
      //its own field and methods
     }

    Basic Example for Inheritance:

    class Dog 
     {
      void dogName() 
      {
       System.out.println("My Name is Bruno");
      }
     }
    
     class Breed extends Dog 
     {
       void myBreed() 
       {
        System.out.println("German Shepard");
       }
     }
    
     public class Main 
     {
      public static void main(String args[]) 
      {
      Breed d = new Breed();
      d.dogName();
      d.myBreed();
      }
     }

    Output:

    My Name is Bruno
    German Shepard

    In the above example, the Breed class inherits the method ‘dogName()‘ from the superclass with the help of a keyword ‘extends’.

    Note: The Object is created for only the Breed class but not for the Dog class. That is we can access the methods without creating the object of the superclass.
    Although there are some concepts you need to know before inheriting the superclass, the method that the user wishes to inherit from the superclass cannot be private and also the superclass itself should not be declared private otherwise it cannot be inherited. ‘protected’ methods can be inherited.


    Types of Inheritance:

    There are three types of inheritance in java on the basis of class. They are :

    • single inheritance
    • multi level inheritance
    • hierarchical inheritance
    Inheritance(OOP)

    Java does not support Multiple and Hybrid Inheritance but can be achieved by Interfaces.

    Inheritance

    1. Single Inheritance:

    It refers to an inheritance where a child inherits or extends a single-parent class.
    Here class B extends class A.

    single inheritance

    2. Multilevel inheritance:

    It refers to an inheritance where one class inherits from the derived class and making that derived class the superclass for the new class.

    Here class C inherits from class B and class B inherits from class A.

    Multiple Inheritance

    3. Hierarchical Inheritance:

    It refers to a relationship where more than one class can inherit or extends the same class.
    Here class B and class C inherit class A.

    Hierarchical Inheritance

    4. Multiple Inheritance:

    In this relationship, one class(derived class) can inherit from more than one superclass. Java doesn’t support multiple inheritance.
    check the diagram above.


    5. Hybrid Inheritance:

    A combination of more than one type of inheritance in a program is called Hybrid Inheritance. It is also not supported by Java.
    check the diagram above.

    Click here to learn about each of the inheritances with examples.


    Constructors and super Keyword in Inheritance.

    In Inheritance, a subclass inherits all the members that are its fields, methods, and nested classes from its superclass. But Constructors are not members, so they cannot be inherited by subclasses, but the constructor of the superclass can be invoked from the subclass with the help of a super keyword.
    super Keyword refers directly to the superclass in its hierarchy. It is similar to this Keyword.

    super is used to invoke the superclass constructor from a subclass. And also used when the members having the same name in the superclass and subclass and therefore need to differentiate between them.

    Syntax of super Keyword:

    class SuperclassTest
    {
      int num1, num2;
    
      SuperclassTest(int num1, int num2)
      {
        this.num1 = num1;
        this.num2 = num2;
      }
    
      public void getNum()
      {
        System.out.println("Numbers in super class are: " + num1 + " and: " + num2);
      }
    }
    
    public class Subclass extends SuperclassTest
    {
      Subclass(int num1, int num2)
      {
        super(num1, num2);	//use of super
      }
    
      public static void main(String argd[])
      {
        Subclass s = new Subclass(24, 30);
        s.getNum();
      }
    }

    Output:

    Numbers in super class are: 24 and: 30


    Java Program for Super keyword

    Example of a super keyword to differentiate the members of the superclass from a subclass.

    class SuperClass
    {
      int id = 20;
      public void display()
      {
        System.out.println("Super Class display method");
      }
    }
    
    public class SubClass extends SuperClass
    {
      int id = 10;
      public void display()
      {
        System.out.println("Sub Class display method");
      }
    
      public void myMethods()
      {
        // Instantiating subclass
        SubClass s = new SubClass();
    
        // display method and value of sub class
        s.display();
        System.out.println("Sub Class id:" + s.id);
    
        // display method and value of super class using super
        super.display();
        System.out.println("Super Class id::" + super.id);
      }
    
      public static void main(String args[])
      {
        SubClass sub = new SubClass();
        sub.myMethods();
      }
    }

    Output:

    Base Class display method
    Sub Class id:10
    Super Class display method
    Super Class id::20


  • Java – call by value and call by reference

    call by value in Java:

    If a method is to be called by passing a parameter as a value then it is said to be Call by Value. Here the changes made to the passed parameter do not affect the called method.

    Example of call by value:

      class CallByValue
      {
       void meth(int x, int y)
       {
         x = x + 10;
         y = y - 20;
        
         System.out.println("The result after the operation performed:");
         System.out.println("a = " + x + "\t b = " + y);
       }
      }
      
      public class JavaMain
      {   
       public static void main(String args[])
       {
        
        CallByValue obj = new CallByValue();
        
        int a =50, b = 100;
        
        System.out.println("The value of a and b before the call :");
        System.out.println("a = " + a + "\t b = " + b);
        
        obj.meth(a, b);
        
        System.out.println("The value of a and b after the call : ");
        System.out.println("a = " + a + "\t b = " + b);
          
       }
      }   

    Output:

     a = 50	 b = 100
     The result after the operation performed:
     a = 60	 b = 80
     The value of a and b after the call : 
     a = 50	 b = 100

    call by reference in Java:

    If a method is to be called by passing a parameter (not the value) as a reference then it is said to be Call by Reference. Here the changes are made to the passed parameter effect on the called method.

    Example of call by reference:

    class CallByRef 
      {
        int x, y;
        
        CallByRef(int i, int j)
        {
            x = i;
            y = j;
        }
        
        /* pass an object */
        void method(CallByRef p)
        {
            p.x = p.x + 2;
            p.y = p.y + 2;
        }
      }
      
      public class JavaMain 
      {   
       public static void main(String args[])
       {
          
        CallByRef obj = new CallByRef(10, 20);
        
        int x = 10, y = 20;
        
        System.out.println("The value of a and b before the call :");
        System.out.println("a = " + obj.x + "\t b = " + obj.y);
        
        obj.method(obj);
        
        System.out.println("The value of a and b after the call : ");
        System.out.println("a = " + obj.x + "\t b = " + obj.y);
           
       }
      } 

    Output:

     The value of a and b before the call :
     a = 10	 b = 20
     The value of a and b after the call : 
     a = 12	 b = 22

  • Java Keywords & Identifiers

    Keywords:

    Keywords in Java are also known as reserved words, are already defined in Java with a predefined meaning. These words cannot be used with variables or object name.

    Example of using integer Keyword:

    int number = 5;

    List of Keywords used in Java are shown in the table:

    Keywords
    abstract assert boolean break
    byte case catch char
    do double else enum
    extends final finally float
    for goto if implements
    import instanceof int interface
    long native new package
    short static strictfp super
    volatile while this throw
    private protected public return
    throws transient try void

    Identifiers:

    Identifier is the symbolic name given to the variables name, class name, method name, etc for identification reason so that the program can identify them throughout the program. The name is given by the user with their choice but by following naming rules.

    These rules are:

    • An identifier cannot be a Java keyword.
    • Identifiers are case sensitive, that temp and Temp are different identifiers.
    • Identifiers must begin with a sequence of letters(A-Z, a-z) and digits(0-9), $ or _. Note that an identifier cannot have the first letter as a digit.
    • Whitespaces are not allowed.
    • Also symbol like @, #, and so on cannot be used.

    Example of some valid identifiers are:

     marks
     level
     highestMark
     num5 

    Here are some invalid identifiers:

     class
     float
     5num
     highest Mark
     @web       

  • Java – Type conversion/Type Casting

    Type Casting is assigning a value of one data-type to a variable of another data-type.

    When a value is assigned to another variable, their types might not be compatible with each other to store that value. For this situation, they need to be cast or converted explicitly. But if they are compatible then java converts the values automatically which is known as Automatic Type Conversion.

    In Java, there are two types of casting:

    • Widening Casting (Implicit)
    • Narrowing Casting (Explicitly)

    1. Widening Casting (Implicit):

    Converting a data-type of smaller size to a type of larger size. It is also known as Automatic Type Conversion.
    byte -> short -> char -> int -> long -> float -> double

    Example of Widening or Implicit Casting:

     public class WideCast
     {
      public static void main(String[] args)
      {
       int i = 10;
       long l = i;	//converted automatically
       float f = l; //converted automatically
    
       System.out.println("Int value "+i);
       System.out.println("Long value "+l);
       System.out.println("Float value "+f);
      }
     }  

    Output:

    Int value 10
    Long value 10
    Float value 10.0

    2. Narrowing Casting (Explicit):

    Converting a data-type of larger size (occupying larger space) to a type of smaller size. For this type of conversion programmer itself to perform the task. Here, unlike Widening Casting,  JVM(Java Virtual Machine) does not take part.
    double -> float -> long -> int -> char -> short -> byte

    Example of Narrowing or Explicit Casting:

     public class NarrowCast
     {
      public static void main(String[] args)
      {  
        double d = 200.04;
        
        long l = (long)d;  //converted manually
        int i = (int)l;	//converted manually
    
        System.out.println("Double value "+d);
        System.out.println("Long value "+l);
        System.out.println("Int value "+i);
      }
     }

    Output:

    Double value 200.04
    Long value 200
    Int value 200

  • Java – Data Types

    What are Data Types in Java?

    Data types specify the varying sizes and values in the variables that can be stored. That is every variable is assigned by data-types according to the need. And based on their respective data-types, the operating system allocates memory to that data-types.

    There are two data types in Java:

    • Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double.
    • Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.

    1. Primitive data types:

    These are the most basic data types available in the Java language.
    There are eight primitive data-types available by Java:

    Data type Size Description
    byte 1 byte Stores whole numbers from -128 to 127
    short 2 bytes Stores whole numbers from -128 to 127
    char 2 bytes Stores whole numbers from -32,768 to 32,767
    int 4 bytes Stores a single character/letter or ASCII values
    long 8 bytesStores whole numbers from -2,147,483,648 to 2,147,483,647
    float 4 bytes Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
    double 8 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits
    boolean 1 bit Stores true or false values

    These are put into four group:

    • Integers: This group includes byte, short, int, and long, which are for whole-valued signed numbers.
    • Floating-point numbers: This group includes float and double, which represent numbers with fractional precision.
    • Characters: This group includes char, which represents symbols in a character set, like letters and numbers.
    • Boolean: This group includes boolean, which is a special type for representing true/false values.

    Integers:

    • byte:
      It is an 8-bit signed two’s complement integer. The byte data type is used to save memory in large arrays.
      Its minimum value is -128 and the maximum value is 127. Its default value is 0.
      Example:
      byte x = 15;
      byte y = -12;
    • Short:
      The short data type is a 16-bit signed two’s complement integer. A short is 2 times smaller than an integer. Its minimum value is -32,768 and the maximum value is 32,767. Its default value is 0. And is also used to save memory.
      Example:
      short x = 1500;
      short y = -1200;
    • int:
      The int data type is a 32-bit signed two’s complement integer. It is a default data-type for integral values.Its minimum value is – 2,147,483,648 and maximum value is 2,147,483,647. Its default value is 0.
      Example:
      int x = 25;
      int y = -35;
    • long:
      The long data type is a 64-bit two’s complement integer. Its value-range lies between -9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807 (2^63 -1) (inclusive). Its default value is 0. long is used when int is not large enough to store the value.
      Example:
      long
      x = 200000L;
      long y = -300000L;

    Floating Point Types:

    • float:
      The float data type is a single-precision 32-bit IEEE 754 floating-point. It is used when the user needs to save memory in large arrays of floating-point numbers. float is never used for precise values such as for currency. Its default value is 0.0d.
      Example:
      float x = 234.5f;
    • double:
      The double data type is a double-precision 64-bit IEEE 754 floating-point. The double is generally used for decimal values just like float. The double also should never be used for precise values, such as currency. Its default value is 0.0d.
      Example:
      double x = 13.99d;

    Characters:

    The char data type is a single 16-bit Unicode character. The size of a character is 2 bytes. It is used to store single characters and must be enclosed within single quotes as shown in the example. Example:

     char alphabet = 'A';

    Boolean:

    A boolean keyword is used to declare with the boolean data-type and represents one bit of information that is either true or false.
    Example:

    boolean fun = true;
    boolean bored = false;

    2. Non-Primitive Data Types:

    The non-primitive data types include Strings, Classes, Interfaces, and Arrays. These are also known as reference types because they refer to objects.
    Non-primitive types are created by the user/programmer and are not predefined by Java except one that is String and can have null values whereas primitive data types are predefined in Java and always has a value.

    To learn about Non-Primitive Data Types click on the following:
    Strings, Classes, Interfaces, Arrays.


  • Java – Scope of a Variable

    What is scope of a variables in Java?

    Scope refers to the visibility of variables. In other words, a scope is a section of a program, and the scope of variables refers to the section of the program where the variables are visible.

    Variables are declared and used within that region. Also variable declared within the block cannot be accessed outside that block.

    Before understanding the variable’s scope, lets us see some certain rules to declare the variables:

    • The first character must be a letter.
    • A variable name can consist of letters A-Z, a-z, digits 0-9, and two special characters such as underscore(_) and the dollar sign($).
    • Blank spaces cannot be used in variable names.
    • Java keywords cannot be used as variable names.
    • Variable names are case-sensitive.

    Types of Variables in Java:

    • local variable
    • instance variable
    • static variable

    Let’s learn the scope of these each variable with an example:

    1. Local Variable:

    A variable that is declared within the body of the method or constructor is called a local variable. This variable is used only within that block or method where it was created other classes cannot access it. And is destroyed after exiting the method or block.

    Initialization of Local Variables is necessary.

    Example of local variable:

      public class Employees
      { 
        public void EmployeeInfo() 
        { 
          // local variable age 
          int age = 0;
          String name = "Prashant";
            
          age = age + 30; 
          System.out.println("Employee age is : " + age); 
          System.out.println("Employee name is : " + name ); 
        } 
      
        public static void main(String args[]) 
        { 
          Employees emp = new Employees(); 
          emp.EmployeeInfo(); 
        } 
      }

    Output:

     Employee age is : 30
     Employee name is : Prashant

    2. Instance Variable:

    These are the non-static variable that is declared within the class but outside the method or constructor. With the creation of Objects, Instance Variable is created and destruction of an object destroys the variables.

    And can be accessed only by creating objects. Initialization of Instance Variable is not necessary as it is 0 by default.

    Example of Instance variable:

     public class Employees
     {
        // this instance variable  
        String name;
        int age;
    
        public Employees (String EmployeeName)
        {
          name = EmployeeName;
        }
    
        public void EmpAge(int EmployeeAge)
        {
          age = EmployeeAge;
        }
    
        public void Display()
        {
          System.out.println("Employee name: " + name ); 
          System.out.println("Employee  age :" + age); 
        }
    
        public static void main(String args[])
        {
          Employees r = new Employees("Prashant");
          r.EmpAge(20);
          r.Display();
        }
     }

    Output:

    Employee name: Prashant
    Employee  age :20

    3. Static variable:

    These variables are also known as class Variables. These are declared just like Instance Variable that within the class but outside the constructor or method but the difference is that static variable is declared using static keyword.

    Unlike the Instance variable, only one static variable is created its value remains the same for all objects no matter how many objects the user creates. Here initialization is not mandatory, it is 0 by default.

    Example of Static variable:

     public class Employees
     {
        //static variable
        static int id = 1101;
    
      public static void main(String[] args)
      {
        
        Employees emp = new Employees();
    
       // Call static variable using object reference variable
        int a = emp.id;
    
        
        System.out.println("Employee ID: ");
        System.out.println(Employees.id);
      }
     }

    Output:

    Employee ID: 
    1101

  • Java – Operator & Expression

    Operators are used to perform operations on variables and values or to manipulate them. The operation is performed with two operand and operators to provide what action need to perform.

    Example:

    int a = 10 + 5;

    In the above example, 10 and 5 are operands and + is the operation performed between these two operands.

    Java provides numbers of operation and these are grouped into the following:

    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Logical Operators
    • Relational (comparison) operators
    • Bitwise Operators
    • Ternary Operator

    1. Arithmetic Operators: 

    They are used to perform basic arithmetic operations. They perform on primitive data types.
    They are:

    * : Multiplication
    Multiplies two values
    Example: x * y;

    / : Division
    Divides one value from another
    Example: x / y;

    % : Modulo
    Returns the division remainder
    Example: x % y;

    + : Addition
    Adds together two values
    Example: x + y;

    – : Subtraction
    Subtracts one value from another
    Example: x - y;

    Example: Click Here


    2. Assignment Operators: 

    The assignment operator is used to assigning a value to any variable. This operator assigns the value of the right-hand side of an operator to the left-hand side. Various assignment operator in Java:

    These are the short version formed by combining the two operators.

    For example Instead of writing, int a = a+3, we can write a+= 5.

    • Assignment operator: ‘=’ This operator assigns the value on the right to the variable on the left.
      a = 20; B = 30; Ch = 'cha';
    • Add AND assignment operator: ‘+=’ This operator first adds the current value of the variable on the left to the value on the right and then assigns the result to the variable on the left.
      c+=7; a+=b;
    • Subtract AND assignment operator: ‘-=’ This operator first subtracts the current value of the variable on the left from the value on the right and then assigns the result to the variable on the left.
      c-=7; a-=b;
    • Multiply AND assignment operator: ‘*=’ This operator first multiplies the current value of the variable on the left to the value on the right and then assigns the result to the variable on the left.
      c*=7; a*=b;
    • Divide AND assignment operator: ‘/=’ This operator first divides the current value of the variable on the left by the value on the right and then assigns the result to the variable on the left.
      c/=7; a/=b;
    • Modulus AND assignment operator: ‘%=’ It takes modulus using two operands and assigns the result to the left operand.
      C %= A is equivalent to C = C % A ;
    • Right shift AND assignment operator: ‘>>=’ This operator is used for Right shift Operation.
      C >>= 2 ;
    • Left shift AND assignment operator: ‘<<=’ This operator is used for Left shift Operation.
      C <<= 2 ;
    • Bitwise AND assignment operator: ‘&=’ This operator is used for Bitwise AND Operations.
      C &= 2;
    • Bitwise exclusive OR and assignment operator: ‘^=’ This operator is used for Bitwise exclusive OR Operations.
      C ^= 2;
    • Bitwise inclusive OR and assignment operator: ‘|=’ This operator is used for Bitwise inclusive OR.
      C |= 2;

    Example: Click Here


    3. Increment and Decrement Operators: 

    The ++ and the – – are Java’s increment and decrement operators. ++ is used to increase the value by 1 and — is used to decrease the value by 1. There are two kinds of Increment and Decrement Operators.

    They are:

    • Post-Increment or Post-Decrement:
      First, the value is used for operation and then incremented or decremented. Represented like a++ or a–.
    • Pre-Increment Pre-Decrement:
      Here First the value is incremented or decremented then used for the operation. Represented like ++a or –a.

    Example: Click Here


    4. Logical Operators:

    Logical Operators are used in conditional statements and loops for evaluating a condition with binary values. All of the binary logical operators combine two boolean values that are true and false to form a result value.

    Logical Operators with their description:

    Operator Description Example
    && (logical AND) If both the operands are non-zero, then the condition becomes true. (X && Y) is false
    || (logical OR) If any of the two operands are non-zero, then the condition becomes true. (X || Y) is true
    ! (logical NOT)Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(X && Y) is true

    Example: Click Here


    5. Relational (comparison) operators:

    Comparison operators are used to comparing two values and return boolean results. These operators are used to check for relations like equality, greater than, less than between two values. They are used with a loop statement and also with if-else statements.

    Following are the relational operators in Java:

    OperatorNameExample
    ==Equal to.A == B
    !=Not equal.A != B
    >Greater than.A > B
    <Less than.A < B
    >=Greater than or equal to.A >= B
    <=Less than or equal to.A <= B

    Example: Click Here


    6. Bitwise operators: 

    Bitwise operator works on bits and performs a bit-by-bit operation. There are six Bitwise Operators and can be applied to the integer types, long, int, short, char, and byte.

    • Bitwise AND: ‘&’
      Binary AND Operator copies a bit to the result if it exists in both operands.
    • Bitwise OR: ‘|’
      Binary OR Operator copies a bit if it exists in either operand.
    • Bitwise XOR: ‘^’
      Binary XOR Operator copies the bit if it is set in one operand but not both.
    • Binary Left Shift: ‘<<’
      The left operands value is moved left by the number of bits specified by the right operand.
    • Binary Right Shift: ‘>>’
      The left operand’s value is moved right by the number of bits specified by the right operand.
    • Bitwise complement: ‘~’
      Binary Ones Complement Operator is unary and has the effect of ‘flipping’ bits.
    • zero-fill right shift: ‘>>>’
      The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros.

    Example: Click Here


    7. Ternary operators: 

    Ternary Operator is also known as the Conditional operator. It is used to evaluate Boolean expressions. We can say that it is a short version of the if-else statement. But here instead of operating on to operand, it operates on three operands, and therefore the name ternary.

    Syntax:

    variable num1 = (expression) ? value if true : value if false;

    Example: Click Here


    What are Precedence and Associativity?

    Precedence and Associativity are the rules that are used to determine the operators with the highest priority in evaluating an equation that contains different operations.

    For example:

     x = 10 + 5 * 2;   

    In this example, x is assigned as 20, not 30 that’s because operator * has higher precedence than +, and hence it first gets multiplied (5*2) and then the multiplied value is added to 10.

    In the following table, the precedence of an operator decreases from top to down:

    CategoryOperatorAssociativity
    Postfix>() [] . (dot operator)Left to right
    Unary>++ – – ! ~Right to left
    Additive>+ –Left to right
    Relational>> >= < <=Left to right
    Equality>== !=Left to right
    Bitwise AND>&Left to right
    Bitwise OR>|Left to right
    Bitwise XOR>^Left to right
    Logical AND>&&Left to right
    Logical OR>||Left to right
    Conditional?:Right to left
    Assignment>= += -= *= /= %= >>= <<= &= ^= |=Right to left

  • Java – Operator Precedence and Associativity

    What are Precedence and Associativity?

    Precedence and Associativity are the rules that are used to determine the operators with the highest priority in evaluating an equation that contains different operations.

    For example:

     x = 10 + 5 * 2;   

    In this example, x is assigned as 20, not 30 that’s because operator * has higher precedence than +, and hence it first gets multiplied (5*2) and then multiplied value is added to 10.


    In the following table, the precedence of an operator decreases from top to down:

    CategoryOperatorAssociativity
    Postfix>() [] . (dot operator)Left to right
    Unary>++ – – ! ~Right to left
    Additive>+ –Left to right
    Relational>> >= < <=Left to right
    Equality>== !=Left to right
    Bitwise AND>&Left to right
    Bitwise OR>|Left to right
    Bitwise XOR>^Left to right
    Logical AND>&&Left to right
    Logical OR>||Left to right
    Conditional?:Right to left
    Assignment>= += -= *= /= %= >>= <<= &= ^= |=Right to left

  • Java Variables

    What is Variable in Java?

    The variable is the basic unit of storage which holds the value while the program is executed. We can also say that it is a name given to the memory location. A variable is defined by data-types provided by Java.

    It may be string, int, float, char, and boolean.

    Declaring a Variable in Java:

    Certain rules are needed to be followed before declaring the variables:

    • The first character must be a letter.
    • A variable name can consist of letters A-Z, a-z, digits 0-9, and two special characters such as underscore(_) and dollar Sign($).
    • Blank spaces cannot be used in variable names.
    • Java keywords cannot be used as variable names.
    • Variable names are case-sensitive.

    Syntax to declare Variables:

    data_type variable_name = value;

    Here, data_type means one of the Java data-types mentioned above. variable_name is the name that must be assigned to it, you can give any name suitable for it. The equal sign(=) is an assignment Operator used to assign the value of R.H.S. to L.H.S.

    Example: Demonstration of assigning value to different data-types

     int num = 20;
     String name = "Daniel";
     float floatNum = 7.98f;
     char alphabet = 'D';
     boolean bool = true;

    Types of Variables in Java:

    • local variable
    • instance variable
    • static variable

    Following declaration help us to understand the position of each of these three variables:

     class Example
     {  
      int Num1 = 30;//instance variable  
    
      static int Num2 = 40;//static variable 
      
      void method_Name()
      {  
      int num3 = 60;//local variable  
      }  
     }

    1. Local Variable:

    A variable that is declared within the body of the method or constructor is called a local variable. This variable is used only within that block or method where it was created other classes cannot access it. And is destroyed after exiting the method or block. Initialization of Local Variables is necessary.

    Example of Local variable in Java:

      public class Employees
      { 
        public void EmployeeInfo() 
        { 
          // local variable age 
          int age = 0;
          String name = "Prashant";
            
          age = age + 30; 
          System.out.println("Employee age is : " + age); 
          System.out.println("Employee name is : " + name ); 
        } 
      
        public static void main(String args[]) 
        { 
          Employees emp = new Employees(); 
          emp.EmployeeInfo(); 
        } 
      }

    Output of local variable in Java:

     Employee age is : 30
     Employee name is : Prashant

    2. Instance Variable:

    These are the non-static variable that is declared within the class but outside the method or constructor. With the creation of Objects, Instance Variable is created and destruction of an object destroys the variables. And can be accessed only by creating objects. Initialization of Instance Variable is not necessary as it is 0 by default.

    Example of Instance variable in Java:

     public class Employees
     {
        // this instance variable  
        String name;
        int age;
    
        public Employees (String EmployeeName)
        {
          name = EmployeeName;
        }
    
        public void EmpAge(int EmployeeAge)
        {
          age = EmployeeAge;
        }
    
        public void Display()
        {
          System.out.println("Employee name: " + name ); 
          System.out.println("Employee  age :" + age); 
        }
    
        public static void main(String args[])
        {
          Employees r = new Employees("Prashant");
          r.EmpAge(20);
          r.Display();
        }
     }

    Output of Instance variable in Java:

    Employee name: Prashant
    Employee  age :20

    3. Static variable:

    These variables are also known as class Variables. These are declared just like Instance Variable that within the class but outside the constructor or method but the difference is that static variable is declared using static keyword. Unlike Instance variable, only one static variable is created its value remains the same for all objects no matter how many objects user creates. Here initialization is not mandatory, it is 0 by default.

    Example of Static variable in Java:

     public class Employees
     {
        //static variable
        static int id = 1101;
    
      public static void main(String[] args)
      {
        
        Employees emp = new Employees();
    
       // Call static variable using object reference variable
        int a = emp.id;
    
        
        System.out.println("Employee ID: ");
        System.out.println(Employees.id);
      }
     }

    Output of Static variable in Java:

    Employee ID: 
    1101