java operators

Java Operators-: Java has a lot of operators, simple and composed. Most Java operators are the ones we know from maths but because programming involves types other than numeric, extra operators with specific purposes were added.  Like any other programming language Java support many types operator these are..

  • Assignment operator
  • Numerical Operators
  • Binary Operators
  • Relation Operators
  • Bitwise Operators
  • Logical Operators
  • Shift operators
  • Elvis operators

 

 

Assignment Operators in java-: This operator is the most used in programming, as nothing can be done without it. Any variable that we create, regardless of the type, primitive or reference has to be given a value at some point in the program. Setting of a value using the assignment operator(=) is quite simple: on the left side of the operator we have the variable name and on the right it is a value. The only condition for an assignment to work is that the value matches the type of the variable.

class OperatorExample{ 
public static void main(String args[]){ 
int a=20; 
int b=30; 
a+=4;//a=a+4 (a=20+4) 
b-=4;//b=b-4 (b=30-4) 
System.out.println(a); 
System.out.println(b); 
}} 

Output of this programme

24
26

Numerical Operators In java-: This section groups all operators that are mostly used on numerical types. The numerical operators we know from maths as like +, -, *,/. Comparators are found in programming too but they can be combined to obtain different effects.

Unary operators -: It require only one operand and they affect the variable they are applied to.

Increment and decrements-: In Java(and some other programming languages) there are unary operator called incrementors (++) and decrementors (–) . These operators are placed before or after a variable to increase or decrease its value by 1. They are usually used in loops as counters to condition the termination of the loop. When they are placed before the variable, they are called prefixed and when are placed after it they are called postfixed.

When they are prefixed the operation is executed on the variable, before the variable is used in the next statement. Example…

class OperatorExample{  
public static void main(String args[]){  
int x=20;  
System.out.println(x++);//20 (11)  
System.out.println(++x);//22  
System.out.println(x--);//22 (11)  
System.out.println(--x);//20  
}} 

Output of this programme

20
22
22
20

 

Sign Operators-: Mathematical operator + is used on a single operator to indicate that a number is positive(redundant and mostly never used).

Negation Operator-: There are two more unary operators and their role is to negate variables. Operator ! applies to Boolean variables and it is used to negate them. So, true becomes false and false becomes true.

 

 

Binary Operators in java-:  For understanding the binary operator we take a example.    + adds two variables

[jshell> int i = 4
i ==> 4
| created variable i : int
[jshell> int j = 6
j ==> 6
| created variable j : int
[jshell> int k = i + j
k ==> 10
| created variable k : int
[jshell> int i = i + 2
i ==> 6
| modified variable i : int
| update overwrote variable i : int

The last statement int i = i + 2 has the effect of incrementing the value of i with 2 and there is a little redundancy there. That statement can be written without mentioning i twice, because its effect is to increase the value of i with 2. This can be done by using the += operator, which is composed of the assignment and the addition operator. The optimal statement is i += 2.

The + operator can also be used to concatenate String instances, or String instances with other types. The JVM decides how to use the + operator depending on the context.

Relation Operators in Java-: We need to introduce conditions to drive and control the execution flow. Conditions require the evaluation of a comparison between two terms using a comparison operator. In this section all comparison operators used in java is described and code samples is provided.

== tests equality of terms. Because in Java a single equals (=) sign assigns values and a solution needed to be find to test equality so the developers just duplicated the “=” operator. We have used for loops before to depict how to use certain types or statements.

!= tests inequality of terms. It is the opposite of the == operator.

< and <= have the same purpose as the one we probably learned in maths class. The first one (<) tests if the item on the left of the operator is less than the one on the right. The next one (<=) tests if the item on the left of the operator is less or equal to the one on the right. This operator cannot be used on reference types.

> and >= have the same purpose as the one we probably learned in maths class. The first one (>) tests if the item on the left of the operator is greater than the one on the right. The next one (>=) tests if the item on the left of the operator is greater or equal to the one on the right. This operator cannot be used on reference types.

Bitwise Operators in java-:In Java there are a few operators that are used at bit level to manipulate variables of numerical types. Bitwise operators are used to change individual bits in an operand. Bitwise operations are faster and usually use less power because of the reduced use of resources. They are most useful in programming visual applications, games, where colour, mouse clicks, and movements can be quickly determined using Bitwise applications.

Bitwise Not-: The ~ operator is sort of a binary negator. It performs a bit-by-bit reversal of an integer value. Of course, this affects all bits used to represent the value. So, if we declare

byte b1 = 10;

the binary representation is 00001010. The Integer class provides a method named toBinaryString that can print the binary representation of the previously defined variable but it does not print all the bits, because the method doesn’t know on how many bits we want the representation on. So, we need to use a special String function to format the output.

 Bitwise AND operator-:  It is represented by & and what is does is to compare two numbers bit by bit and if the bits on each position have the value of 1 the bit in the result is 1.

The Bitwise OR operator-:  It is represented by | and what is does is to compare two numbers bit by bit and if at least one of the bits is 1, the bit in the result is 1.

The Bitwise XOR operator-: It is represented by ^ and what is does is to compare two numbers bit by bit and if the values are different, the bit in the result is 1.

Logical Operator in Java-:When we designing conditions for controlling the flow of the execution of a program  sometimes there is need for complex conditions to be written, composed conditions constructed from multiple expressions.

There are four operators that are used to construct complex conditions; two of them are Bitwise operations that can be reused: &(AND) and |(OR); but they require evaluation of all the parts of the condition. The operators &&(AND) and ||(OR) have the same effect as the other ones, but the difference is they do not require evaluation of all the expression, which is why they are also called shortcut operators.

To explain the difficult behaviour of these operators, there is a typical example. Normally we declare a list of ten terms (some of them null) and a method to generate a random index, used to select an item from the list. Then we test the selected element from the list to see if it is not null and equal to an expected value. If both conditions are true, then a message is printed in the console.  Example here ..

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class LogicalDemo {
    static List terms = new ArrayList<>() {{
        add("Rose");
        add(null);
        add("River");
        add("Clara");
        add("Vastra");
        add("Psi");
        add("Cas");
        add(null);
        add("Nardhole");
        add("Strax");
    }};
    public static void main(String... args) {
        for (int i = 0; i < 20; ++i) {
            int rnd = getRandomNumber();
            String term = terms.get(rnd);
            System.out.println("Generated index: " + rnd);
            if (term != null & term.equals("Rose")) { \\(*)
                System.out.println("Rose  was  found");
            }
        }
    }
    private static int getRandomNumber() {
        Random r = new Random();
        return r.nextInt(10);
    }
}

 

Shift operators In java -: These operators  are working at bit level. Because moving bits around is a sensitive operation, the only requirement of these operands is for arguments to be integers. The operand to the left of the operator is the number that is shifted and the operand to the right of the operator is the number of bits that is shifted. There are three shift operators in Java and each of them can be composed with the assignment operator to do the shifting and assign the result to the original variable on the spot. The shift operators are here..

  1. << shift left. Given a number represented in binary, this operator shifts bits to the left.
  2. >> shift right. Given a number represented in binary, this operator shifts bits to the right.
  3. >>> unsigned shift right. Also called logical shift. Given a number represented in binary this operator shifts bits to the right, together with the sign bit and the remaining positions are replaced with zero.

 

Shift left example-:

class OperatorExample{  
public static void main(String args[]){  
System.out.println(10<<2);//10*2^2=10*4=40  
System.out.println(10<<3);//10*2^3=10*8=80  
System.out.println(20<<2);//20*2^2=20*4=80  
System.out.println(15<<4);//15*2^4=15*16=240  
}} 

Output of this programme

40
80
80
240

Right Shift example -:

class OperatorExample{ 
public static void main(String args[]){ 
System.out.println(10>>2);//20/2^2=20/4=5
System.out.println(20>>2);//40/2^2=40/4=10
System.out.println(20>>3);//20/2^3=20/8=2 
}}

 Output of this programme

5
10
2

 

Elvis operator In Java-:  This is the only ternary operator in Java. Its function is equivalent to a java method that tests a condition and depending of the outcome returns a value. The following is a template for the Elvis operator.

variable = (condition) ? val1 : val2
The following if statement is equivalent.
variable = methodName(..)
type methodName(..) {
if (condition) {
return val1;
} else {
return val2;
}
}

The reason this operator is called the Elvis operator is because the question mark resembles Elvis Presley’s hair, and the column resembles the eyes.

 

 

 

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *