What are Java Modifiers and Operators?

1. Java Modifiers

Mo
difiers are Java keywords that are used to declare features in applications. They affect either the lifetime or the accessibility of a feature. A feature may be a class, a method, or a variable.

Modifiers that affect the visibility of a feature are called access modifiers or visibility modifiers. The remaining modifiers do not fall into any clear categorization and may be called storage and lifetime modifiers.

Java modifiers are of two types :

  • Access Modifier 
  • Non-Access Modifier


1.1. Access Control Modifiers

Java provides a number of access modifiers to set access levels for classes, variables, methods, and constructors. 

The four access levels are:

  • Default
  • Public
  • Private
  • Protected

1.1.1. Default

Accessible within the same package only. No modifiers are needed.
In the sample code below, you can see that no access modifier is used with the 'class' keyword which makes it default. Now this class is only visible/accessible to the other classes which are present in the same package along with this class. The same goes for default variables and methods.


class MyClass {

  public static void main(String[] args) {
    System.out.println("Java World");
  }

}


1.2.1. Public

Accessible to the whole project (global)
In the sample code, 'public' is used before the 'class' keyword which makes this class public. It means this class is visible/accessible to all the other classes of the project.


public class Main {

  public static void main(String[] args) {
    System.
out.println("Hello World");
  }

}


1.3.1. Private: 

Accessible within the same class only.
In the sample code, the 'private' keyword is used with different variables. It means these variables can be used/accessed only within this class. 

Important Tip: One very important point to note here is that a top-level class can't be private. But we can declare the inner class as private. If we declare a class as private, the Java compiler will complain that 'private' is not allowed here.


public class Main {

  private String fname = "John";
  private String lname = "Deer";
  private String email = "[email protected]";
  private int age = 24;

  public static void main(String[] args) {
    Main myObj = new Main();
    System.out.println("Name: " + myObj.fname + " " + myObj.lname);

    System.out.println("Email: " + myObj.email);
    System.out.println("Age: " + myObj.age);
  }
}


1.4.1. Protected

Accessible within the same package and all subclasses
In sample code, 'protected' is used with some variables which means these variables can only be accessed/visible in the subclass/child class of the 'Person' class. The same applies to methods also. Inheritance comes into the picture here.

Important Tip: Class cannot be made protected. A class can either be default or public.


class Person {

  protected String fname = "John";
  protected String lname = "Doe";
  protected String email = "[email protected]";
  protected int age = 24;

}

class Student extends Person {

  private int graduationYear = 2018;

  public static void main(String[] args) {
    Student myObj = new Student();
    System.out.println("Name: " + myObj.fname + " " + myObj.lname);

    System.out.println("Email: " + myObj.email);

    System.out.println("Age: " + myObj.age);
    System.out.println("Graduation Year: " + myObj.graduationYear);

  }
}

2. Non-Access Modifiers

Java provides a number of non-access modifiers to achieve many other functionality.

·      The static modifier for creating class methods and variables.

·      The final modifier for finalizing the implementations of classes, methods, and variables.

·      The abstract modifier for creating abstract classes and methods.

·      The synchronized and volatile modifiers, which are used for threads.


2. Java Operators

Java Operators are symbols that perform operations on variables and values. Java provides many types of operators which can be used according to our usage. They are classified into the following types:
  1. Arithmetic Operators
  2. Assignment Operators
  3. Relational Operators
  4. Logical Operators
  5. Unary Operators
  6. Bitwise Operators

2.1. Arithmetic Operators

Arithmetic operators are used to perform mathematic operations on variables and data. They operate on numeric values. In simple words, they can be used to perform the mathematical operations of addition, subtraction, multiplication, and division.

Operator Description:
  • +             Performs addition
  •             Performs subtraction
  • *             Performs multiplication
  • /             Performs division
  • %             Returns the remainder of the division

Sample Code:


class Arithmetic {
  public static void main(String[] args) {
    
    // variables
    int a = 10, b = 5;

    // Print sum using addition operator
    System.out.println("a + b = " + (a + b));

    // Print difference of a and b using subtraction operator
    System.out.println("a - b = " + (a - b));

    // Print product using multiplication operator
    System.out.println("a * b = " + (a * b));

    // Print result of division
    System.out.println("a / b = " + (a / b));

  }
}


2.2. Assignment Operators

The assignment operator is a special operator that assigns a value to a variable. It is represented by the “=” sign.

Example:

String name;
name = "Daniel Johnson"

In the above expression, = is the assignment operator. It assigns the value "Daniel Johnson" on its right to the variable name on its left.

Operator Description:
  • += Combines addition with the assignment. So a += 10  is the same as a=a+10
  • -= Combines subtraction with the assignment. So a -= 10  is the same as a=a-10
  • *= Combines multiplication with the assignment. So a *= 10  is the same as a=a*10
  • /= Combines division with the assignment. So a /= 10  is the same as a=a/10
  • %= Combines modulus with the assignment. So a %= 10  is the same as a=a%10


Sample Code:


class AssignmentOperator { 
    public static void main(String[] args) 
    { 
        // Declare variable
        int number; 
	// Assign value
        number = 5;

	// Or declare and assign value in same step
        String name = "John"; 
  
        // Print the assigned values 
        System.out.println("number is assigned: " + number); 
        System.out.println("name is assigned: " + name); 
    } 
} 


2.3. Relational Operators

Relational Operators are used to compare/check the relation between two values. They always return a boolean value which is either true or false, by comparing the two values.

Operator Description:
  • < Performs Less Than Comparison
  • <= Performs Less Than or Equal To Comparison
  • > Performs Greater Than Comparison
  • >= Performs Greater Than or Equal To Comparison
  • == Performs Equal To Comparison
  • != Performs Not Equal To Comparison

Sample Code:


class RelationalOperators {
  public static void main(String[] args) {
    
    // Declare variables
    int a = 10, b = 5;

    // Print value of a and b
    System.out.println("a is " + a + " and b is " + b);

    // Equality operator (==) Check if a equals to b or not
    System.out.println(a == b);

    // Not Equal Operator (!=)
    System.out.println(a != b);

    // Greater than (>) operator
    System.out.println(a > b);

    // Less than (<) operator
    System.out.println(a < b);

    // Greater than or equals to (>=) operator
    System.out.println(a >= b);

    // Less than or equals to (<=) operator
    System.out.println(a <= b);
  }
}

2.4. Logical Operators

Logical operators are very important in decision-making. They are used to check whether a condition(IF/ELSE) is true or false. They operate on boolean values and return a boolean. These operators are used to perform logical “AND”, “OR” and “NOT” operations.

Example:

int a = 5;
int b = 10;
boolean condition1 = a < b;
boolean condition2 = b > a;

if condition1 && condition2:
	System.out.println("Both condition1 and condition2 are true");


Operator Description:
  • || (OR)      - Returns true if any one of its operands is true, otherwise returns false
  • && (AND) - Returns true if both  its operands are true, otherwise returns false
  • ! (NOT) - It is a unary operation. It returns the inverse of the operand.

Sample Code:


class LogicalOperator {
  public static void main(String[] args) {

    // AND (&&) operator
    System.out.println((10 > 5) && (8 < 10));
	System.out.println((10 > 5) && (8 > 10));

    // OR (||) operator
    System.out.println((10 < 5) || (8 > 5));
    System.out.println((10 < 3) || (8 < 5));

    // NOT (!) operator
    System.out.println(!(10 == 5));
    System.out.println(!(10 > 5));
  }
}


2.5. Unary Operators

Unary operators in Java are used with only one operand. They are used for increment, decrement, and negation. For e.g., ++ is a unary operator that increases the value of a variable by 1. It means ++10 will return 11.

Operator Description:
  • ++ Increments its operand by 1
  • Decrements its operand by 1

There are two types of increment/decrement operators, pre and post. Let's understand it from the below example:

Sample Code:


class UnaryOperator {
 
    public static void main(String[] args) 
    { 
        // Initialize variable
        int num = 10; 
  
        // First 10 gets printed as it's a post-increment operator
        // Then it get incremented to 11
        System.out.println("Post " + "increment = " + num++); 
  
        // Now num is 11 and get incremented to 12, as it's a pre-increment operator 
        // Then 12 will be printed 
        System.out.println("Pre " + "increment = " + ++num); 
    } 
} 


The same is applied to the decrement operator but in reverse.

2.6. Bitwise Operators

Java provides several bitwise operators that are only applied to the integer types: long, int, short, and char. These operators act upon the individual bits of their operands. These are mostly not used in Java rather they are mostly used in microprocessors or electronic circuits etc.

Operator Description:
  • ~ Bitwise Complement
  • << Left Shift
  • >> Right Shift
  • >>> Unsigned Right Shift
  • & Bitwise AND
  • ^ Bitwise exclusive OR

You can find the complete tutorial here - Java Tutorials Series


Java Data Types   << Previous     ||     Next >>  Java Class and Object


Author
Vaneesh Behl

Passionately writing and working in Tech Space for more than a decade.

Comments

Popular posts from this blog

Top 7 Web Development Trends in the Market

What's New in Selenium-Automated Testing

Java Date Format Validation with Regular Expressions: A Step-by-Step Guide

Find Broken Links on Webpage with Selenium Automation

Automate GoDaddy.com Features with Selenium WebDriver

Selenium IDE Tutorial: How to Automate Web Testing with Easy-to-Use Interface

Artificial Intelligence in Self-Driving Cars: Navigating the Future of Transportation

Top Mobile Test Automation Tools for Efficient App Testing: Features and Cons

Applications of Artificial Intelligence in Healthcare

Top 10 Highly Paid Indian CEOs in the USA