×

Misc Operators in Java

In this article, we are going to learn about the misc operators in Java. Misc operators are nothing but the miscellaneous operators. The java programming language supports some of the miscellaneous operators in Java.

Introduction

The very first operand will always be examined first in the conditional operator known as the misc operator, which has three operands. If the result is nonzero, the next operand is evaluated to determine its value. If not, the result's value is determined by evaluating the third operand.

There are many miscellaneous operators. They are:

  • Ternary or conditional operator
  • Member access operator
  • Comma operator
  • Array Index operator
  • New operator
  • Instanceof Operator

Let us know about each operator discussed above.

Ternary or Conditional operator

The ternary or otherwise conditional operator is a unique operator that Java offers. The pair of symbols that make up this operator are ‘?’ and ‘: ‘. Together, the two symbols make up the conditional operator. If we need to initialize or allocate a variable based on a condition, we can use this operator. It uses the syntax listed below.

expr-1 ? expr-2 : expr-3;

Any expression that produces a Boolean value can be used in the syntax above as expr-1. If expr-1 returns true, expr-2 is then processed; if not, expr-3 is. It should be noted that expr-2 and expr-3 cannot return void values and must both return same type of value. The use of the Java ternary operator is demonstrated in the following line of code.

Let us understand it with a simple example program

File name: Ternary.java

public class Ternary
{
    public static void main(String[] args)
    {
        int n = 10;
        boolean flag = (n % 2 == 0 ? true : false ); 
        System.out.println(n + " is even? " + flag);
    }
}

Output

10 is even? True

Member Access Operator

Dot (.) symbols are employed as the Java member accessibility operators to allow objects to access a class's instance variables and member methods.

Let us understand it with an example

File name: Maccess.java

public class Maccess {
    public static void main(String[] args) {
        Position p = new Position(0,0);
        int a = p.x; // example of member access
    }
}


class Position {
    public int x;
    public int y;


    public Position(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

Output

12
dash: 2: 12: not found

Comma Operator

The "," symbol, known as the comma operator in Java, is used to demarcate function parameters and to define multiple variables of the same type in a single statement.

Let us understand it with an example

File name: Comma.java

class Comma
 { 
             public static void main(String args[] ) 
             { 
                         int i,j; 
                         for(i=1,j=20;j>=10;i++,j-=2) 
                         { 
                                     System.out.println(i+"  "+j); 
                         } 
             } 
 }

Output

1  20
2  18
3  16
4  14
5  12
6  10

Array Index Operator

The square bracketed ([]) Java array search operator is used to define and retrieve array elements.

Let us understand it with a simple example program.

File name: Aindex.java

// A Java program that creates an array of integers, inserts some values into the array, and //outputs each value to serial monitor is used to demonstrate the concept.
class Aindex {
public static void main(String[] args)
{
// establishes an integer array.
int[] arr;
arr = new int[5];
 
arr[0] = 11;
arr[1] = 21;
arr[2] = 31;
arr[3] = 41;
arr[4] = 51;
// generally referring to the array's specified elements
for (int i = 0; i < arr.length; i++)
System.out.println("component at index " + i+ " : " + arr[i]);
}
}

Output

component at index 0 : 11
component at index 1 : 21
component at index 2 : 31
component at index 3 : 41
component at index 4 : 51

New Operator

To establish a new object in Java, use the new operator. Java's operator new keyword. A call to the constructor, which initializes the new object, comes next. Keep in mind that creating an object and declaring an object seem to be two distinct processes. An object cannot be created by merely declaring a reference variable. We must employ the new operator in order to do that. By allocating memory for an object, the new operator constructs it and then returns a handle to that main memory. A call to a constructor is the only postfix parameter required for the Java new operator. The identity of a class to initialize is provided by the constructor’s name. The use of the new operator is demonstrated in the following line of code.

Let us understand it with an example

File name: New.java

class New
{
  public Universe() {}
  public void myUniverse()
  {
    System.out.println("This Universe is limitless.");
  }
}
  public static void main(String[] args)
  {
// A new instance of type Universe is created by the new operator and assigned to    //reference  n
    Universe n = new Universe();
    n.myUniverse();
  }
}

Output

This universe is limitless.

Instanceof Operator

An object is compared to a certain type using the Java instanceof operator, commonly known as the type comparison operator. It uses the objRef instanceof type syntax. Here, the type seems to be the name of the object type to which the object named objRef will be compared. Java's equals() function is a good illustration of how the instanceof operator can be used to figure out whether two objects be equal. The use of the Java instanceof operator is demonstrated in the example code below (InstanceOfDemo.java).

Let us understand it with an example program

File name: Instanceof.java

class Instanceof
{
  public Universe() {}
  public void myUniverse()
  {
    System.out.println("This Universe is limitless.");
  }
}
{
  public static void main(String[] args)
  {
    Universe n = new Universe();
    n.myUniverse();
    System.out.println("Is n an object of Universe? " + (n instanceof Universe));
    System.out.println("Does n inherit Object? " + (n instanceof Object));
  }
}

Output

This Universe is limitless.
Is n an object of Universe? True
Does n inherit Object? True

Conclusion

The operator library in Java is extensive. However, Java somehow doesn't support operator overloading, just like C and C++ do. Additionally, you may have noticed that the majority of Java's operators only apply to fundamental types, not objects. Because Java takes an object-oriented approach to problem solving, it argues that member methods should be used to perform any activity on objects.


Related Topics

Logger class in Java

Logging is a crucial component of Java that aids developers in tracking down mistakes. The logging technique is included with the computer language Java. The possibility of collect the log...

7 minutes read.

Tribonacci series in Java

The Fibonacci series and the Tribonacci sequence are linked. The Fibonacci sequence, each element summates the three preceding terms, is expanded into the Tribonacci series in Java. Through specific examples,...

3 minutes read.

Java Primitive Data Types

Primitive data types are the simplest data types in a programming language. They’re predefined in the language. The names of the primitive types are quite descriptive of the values that...

2 minutes read.

Java Math toDegrees() Method

The toDegrees() method of Java Math class converts a radian angle to an approximately equivalent angle measured in degrees. Syntax: public static double toDegrees(double angrad) Parameters: The parameter ‘angrad ‘represents an angle measured in...

2 minutes read.

Java Integer compareUnsigned() method

The compareUnsigned() method of Integer class compares two int objects numerically by treating the values as unsigned. Syntax public static int compareUnsigned(int x , int y) Parameters The parameters ‘x’ and ‘y’ represent the...

1 minute read.

Java Math.multiplyExact() method

In java, we are provided with multiplyExact method in the Math module. This Math module belongs to the java.lang package. In general, this method returns the product of the provided...

2 minutes read.

Java FileOutputStream

What is FileOutputStream?When we need raw stream data written into a file, we need to look for another option: FileOutputStream. It is used when the file's data is byte-oriented. It comes under...

4 minutes read.

URLConnection Class

What is the URL? URL stands for Uniform Resource Locator, is used to specify addresses on the World Wide Web. A URL relates to the identification of any resource connected to the web. URL syntax: Protocol://hostname/other_information(files...

6 minutes read.

Stone Game in Java

In this tutorial, we will learn to design a stone game in Java. First of all, we will understand what is this game all about. We will grasp it through...

9 minutes read.

Java String Reader

StreamReaderClass: This class is present in the java.io package. It is a character stream in which string act as a source.This method provides to read characters from a string. Character Stream: This class...

3 minutes read.

Buffer reader to read string in Java

The Buffered Reader class of Java is used to read the stream of characters from the input stream. Program to read string using Buffer reader import java.io.*; class  Demo {   public static void main(String...

3 minutes read.

Internal Working of ArrayList in Java

Java's version of a resizable array is called ArrayList. The dynamic growth of an array list ensures that there is always room for new elements. ArrayList's backing data structure is...

8 minutes read.

Arithmetic exception in Java

Exception Handling is one of the most potent ways of handling runtime faults and preserving the application's normal flow. In Java, an exception is an out-of-the-ordinary state, and exceptions are...

3 minutes read.

Java Math copySign() Method

The copySign() method of Math class returns the first floating-point argument with the sign of the second argument. Syntax: public static float copySign(float magnitude, float sign)public static double copySign(double magnitude, double sign) Parameters: The...

1 minute read.

Bully Algorithm code in Java

Election algorithms include the bully algorithm, mainly used to select a coordinate. To find a coordinator in a distributed system that can carry out the tasks required by other processes,...

4 minutes read.

Java Integer class

The Integer class wraps a primitive int type value in an object. Its object contains only a single field whose type is int. Methods: The java.lang.Integer class provides several different methods for...

4 minutes read.

Swastika Pattern in Java

This part teaches us how to create the Swastika Pattern in Java utilizing user-defined columns and rows as well as stars or other special characters.A Java pattern application that is...

2 minutes read.

Transient variable in Java

In this article, you will be acknowledged about transient variable along with its functions. We would conclude by understanding an example program about it. Transient variable By introducing the transitory keyword, we...

3 minutes read.

Loose Coupling in Java

Loosely coupling mechanism in java means one reference of a variable capable of holding multiple implementation class memory is called loosely coupling. Or in other words, one interface reference variable...

3 minutes read.

Cosmic Superclass in Java

The parent class of all Java classes is the Object class. The Java Object class is the parent of all Java classes, whether directly or indirectly. The Object class is...

6 minutes read.