Operator – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Sat, 25 Nov 2023 05:39:12 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 Operator – Java2Blog https://java2blog.com 32 32 Question mark operator in java https://java2blog.com/question-mark-operator-in-java/?utm_source=rss&utm_medium=rss&utm_campaign=question-mark-operator-in-java https://java2blog.com/question-mark-operator-in-java/#respond Wed, 19 May 2021 19:48:41 +0000 https://java2blog.com/?p=14685 Java is one of the most popular programming languages out there, and much like all the other programming languages, Java allows the use of conditional statements as well.

Conditional statements make the very basic fundamentals of any programming language. Conditional statements use logical conditions from mathematics, to perform distinct actions in a code for different decisions. The if else statement is an example of a very popularly used conditional statement.

In this tutorial, we will discuss one such conditional statement, that is the Question mark operator or the ternary operator in java.

Use of the Question mark colon Operator in java

The question mark and the colon operators, when used together, can be known as a ternary operator.

It consists of three operands, and is therefore also known as a short-hand if...else operator. The only advantage it has that unlike multiple lines of code written in if...else statement, ternary operator can be written in a single line of code.

The Question mark and colon operator is made up of three segments. The first segment is a boolean expression that returns either true or false. The second and third segments are the values that are assigned if the expression returns the boolean value true or false respectively. The second and third segments are separated by the use of a : sign.

The question mark operator has the syntax as follows:

var = condition ? value_if_true : value_if_false

Here is an example of a simple code that uses the ternary operator.

Let’s say you want to write a program to check whether number is even or odd.

If you have to do it using traditional if else statement, you have to write lot of line of code.

package org.arpit.java2blog;

public class QuestionMarkOperatorMain {

    public static void main(String[] args){
            int a=22;
            boolean res;
            res = isNumberEven(a);
            System.out.println("22 is even:"+res);
    }

    private static boolean isNumberEven(int a) {
        if(a%2==0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

Output:

22 is even:true

You can write same logic using question mark operator in java with one line.

package org.arpit.java2blog;

public class QuestionMarkOperatorMain {

    public static void main(String[] args){
            int a=22;
            boolean res;
            res = a%2==0? true : false;
            System.out.println("22 is even:"+res);
    }
}

Output:

22 is even:true

As you can see, we are able to write logic to check even odd number with just one line.

The ternary operator can return a value of any type. If we want to get a string value returned instead of a boolean value, we can do it by making very simple changes to the above program in the following way:

package org.arpit.java2blog;

public class QuestionMarkOperatorMain {

    public static void main(String[] args){
            int a=23;
            String result = a%2==0? "Even" : "Odd";
            System.out.println("23 is "+result);
    }
}

Output:

23 is Odd

In many case, question mark colon operator or ternary operator is used for null checking to avoid NullPointerException.

For example:
If String is not null, then you want to return String in uppercase. If String is null, then you can return null.

Here is simple logic:

package org.arpit.java2blog.entry;

public class QuestionMarkOperatorMain {

    public static void main(String[] args){
        String str1 = "java2blog";
        String result1 = toUpperCase(str1);
        System.out.println(result1);

        String str2 = null;
        String result2 = toUpperCase(str2);
        System.out.println(result2);
    }

    public static String toUpperCase(String input)
    {
        return input!=null?input.toUpperCase():null;
    }
}

Output:

JAVA2BLOG
null

As easy as the ternary operator may be, we should note that every code that uses the if...else operator cannot possibly be replicated with the ternary operator.

Use of the nested Question Mark colon Operator

A ternary operator can be used inside another ternary operator.This is called nesting of ternary operator. The nesting of ternary operator to any number of levels is possible in a Java program.

Braces () are used wherever necessary in the syntax of the ternary operator to improve the readability of the program.

The following program shows the nesting of the ternary operator.

public class test1{
        public static void main(String[] args){
        int x = 4;
        int y = 5;
        int z = 8;
        int larger = (x >= y) ? ((x >= z) ? x : z) : ((y >= z) ? y : z);
        System.out.println("The largest one is : " + larger);
        }
    }

Output:

The largest one is : 8

In the above code, the first test condition (x >= y) checks whether x is greater than y. Then if this condition is true, then the second that is the (x >= z) condition is executed. If the first condition is false, then the third condition which is (y >= z) is executed.

The nesting of ternary operators makes the code very complex and difficult to maintain, so you should be careful while using ternary operator for very complex logic.

That’s all about question mark in java.

]]>
https://java2blog.com/question-mark-operator-in-java/feed/ 0
what does += mean in java https://java2blog.com/addition-assignment-operator-java/?utm_source=rss&utm_medium=rss&utm_campaign=addition-assignment-operator-java https://java2blog.com/addition-assignment-operator-java/#respond Sat, 26 Dec 2020 18:49:33 +0000 https://java2blog.com/?p=11408 In this post, we will see what does += mean in java.

Java += operator

+= is compound addition assignment operator which adds value of right operand to variable and assign the result to variable. Types of two operands determine the behavior of += in java.

In the case of number, += is used for addition and concatenation is done in case of String.

a+=b is similar to a=a+b with one difference which we will discuss later in the article.

Let’s see with the help of example:

int i = 4;
i += 2;
System.out.println(i)

Output: // Prints 6

2

Using += in loops

You can use += in for loop when you want to increment value of variable by more than 1. In general, you might have used i++, but if you want to increment it by 2, then you can use i+=2.

Let’s understand with the help of example:
If you want to print even number from 0 to 10, then you could use += operator as below:

package org.arpit.java2blog;

public class PrintEvenNumberMain {

    public static void main(String[] args) {
        for (int i=0;i<=10;i+=2)
        {
            System.out.print(i+" ");
        }
    }
}

Output:

0 2 4 6 8 10

Difference between a+=b and a=a+b

If a and b are of different types, the behavior of a+=b and a=a+b will differ due to rule of java language.

Let’s understand with the help of example:

int x = 2;
x += 3.2;    // compile fine; will cast 3.2 to 3 internally
x = x + 3.2; // won't compile! 'cannot convert from double to int'

Here, += does implicit cast, where as + operator requires explicit cast for second operand, otherwise it won’t compile.

As per oracle docs for compound assignment expression:

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

So,

int x = 2;
x += 3.2;

is equivalent to:

int x = 2;
x = (int)(x + 3.2);
System.out.println(x)  // prints 5

Using += for String concatenation

You can use += operator for String concatenation as well.

package org.arpit.java2blog;

public class StringConcatenationWithAddition {

    public static void main(String[] args) {
        String blogName = "java";
        blogName += "2blog";
        System.out.println(blogName);
    }
}

Output:

java2blog

That’s all about what does += mean in java.

]]>
https://java2blog.com/addition-assignment-operator-java/feed/ 0
Modulo operator in java https://java2blog.com/modulo-operator-java/?utm_source=rss&utm_medium=rss&utm_campaign=modulo-operator-java https://java2blog.com/modulo-operator-java/#respond Sat, 28 Mar 2020 19:51:28 +0000 https://java2blog.com/?p=9074 In this post, we will see about modulo or modulus operator in java.

Modulo operator(%) is used to find the remainder when one integer is divided by another integer.

Modulo operator Syntax

int remainder = int % int;

We can’t use modulo with any other data type other than int. If we use it with other data types, it will give compilation error.

For example:

// compiles successfully
int rem = 10%3;

// won't compile
int rem = 10%3.0;

Let’s see a simple example of modulo operator.

package org.arpit.java2blog;

public class ModuloOperatorMain {

    public static void main(String[] args) {
        int a= 15;
        int b = 4;

        int rem = a%b;
        System.out.println("15%4 = "+rem);
    }
}

Output:

15%4 = 3

When we divide 15 with 4, remainder is 3.

Modulo operator usages

Even odd program

Modulo operator is used to check if number is even or odd.
If number%2 is 0, then number is even else odd.
Let’s see program with the help of example:

package org.arpit.java2blog;

public class ModuloOperatorMain {

    public static void main(String[] args) {
        int num =23;

        if(num%2 ==0)
        {
            System.out.println("Number is even");
        }
        else
        {
            System.out.println("Number is odd");
        }   
    }
}

When you run above program, you will get below output:

Number is odd

Prime number program

Modulo operator is used to check if number is divisible by another number or not in prime number program.

package org.arpit.java2blog;

public class ModuloOperatorMain {

    public static void main(String[] args) {

        System.out.println("is 91 Prime: "+isPrime(91));
        System.out.println("is 43 Prime: "+isPrime(43));
        System.out.println("is 61 Prime: "+isPrime(61));
    }

    public static boolean isPrime(int num) {
           if (num <= 1) {
               return false;
           }
           for (int i = 2; i <= Math.sqrt(num); i++) {
               if (num % i == 0) {
                   return false;
               }
           }
           return true;
    }
}

Output:

is 91 Prime: false
is 43 Prime: true
is 61 Prime: true

I have highlighted the line where we are using modolu operator to check if number is divisible by another number.

Modulo operator behaviour with negative integer

When we use modulo operator with negative integer, it takes sign from dividend.

package org.arpit.java2blog;

public class ModuloOperatorMain {

    public static void main(String[] args) {

        System.out.println("-15%4 ="+(-15%4));
        System.out.println("15%-4 ="+(15%-4));
    }
}

Output:

-15%4 =-3
15%-4 =3

As you can clearly see, remainder got sign from dividend.

That’s all about Modulo operator in java.

]]>
https://java2blog.com/modulo-operator-java/feed/ 0
XOR operator in java https://java2blog.com/xor-operator-java/?utm_source=rss&utm_medium=rss&utm_campaign=xor-operator-java https://java2blog.com/xor-operator-java/#respond Sun, 22 Mar 2020 08:15:59 +0000 https://java2blog.com/?p=8932 In this tutorial, we will see about XOR operator in java.

XOR operator or exclusive OR takes two boolean operands and returns true if two boolean operands are different.

XOR operator can be used when both the boolean conditions can’t be true simultaneously.

Here is truth table for XOR operator.
PQP XOR Q
truetruefalse
truefalsetrue
falsetruetrue
falsefalsefalse


Let’s say you have Person class and you want to filter persons who is either Male or Adult but not both from list of persons.

package org.arpit.java2blog;

public class Person {

    String name;
    int age;
    String gender;

    public Person(String name, int age, String gender) {
        super();
        this.name = name;
        this.age = age;
        this.gender = gender;
    };

    // getters and setters

    public boolean isMale()
    {
        if(gender.equalsIgnoreCase("Male"))
        {
            return true;
        }
        return false;
    }

    public boolean isAdult()
    {
        if(age>=18)
        {
            return true;
        }
        return false;
    }

    public String toString()
    {
        return "Name:"+name+" Age:"+age+" Gender:"+gender;
    }
}

Create Main classed named PersonXORMain.java

package org.arpit.java2blog;

import java.util.ArrayList;
import java.util.List;

public class PersonXORMain {

  public static void main(String[] args) {
    // Filter list with if person is either male or greater than 18 but not both

    List<Person> personList = getPersonList();
    List<Person> filteredList = new ArrayList<>();
    for(Person p :personList)
    {
      if((p.isMale() && !p.isAdult()) || (!p.isMale() && p.isAdult()))
      {
        filteredList.add(p);
      }
    }
    System.out.println(filteredList);
  }

  public static List<Person> getPersonList()
  {
    List<Person> personList=new ArrayList<>();
    Person p1 = new Person("John",21,"Male");
    Person p2 = new Person("Martin",17,"Male");
    Person p3 = new Person("Mary",16,"Female");
    Person p4 = new Person("Amy",25,"Female");

    personList.add(p1);
    personList.add(p2);
    personList.add(p3);
    personList.add(p4);

    return personList;
  }
}

Output:

[Name:Martin Age:17 Gender:Male, Name:Amy Age:25 Gender:Female]

As you can see we are able to achieve the condition with help of && and || operators but if statement looks quite verbose.

if((p.isMale() && !p.isAdult()) || (!p.isMale() && p.isAdult()))

You can use XOR operator to achieve the same.

if((p.isMale() ^ p.isAdult()))

Replace if((p.isMale() && !p.isAdult()) || (!p.isMale() && p.isAdult())) with if((p.isMale() ^ p.isAdult())) and you should be able to achieve same results.

BitWise XOR operator

XOR operator works with primitive type as well. Bitwise XOR operator will always return output as 1 if either of its input 1 but not both.
Here is truth table for BitWise XOR operator.
PQP XOR Q
110
101
011
000

Let’s see this with the help of example.

package org.arpit.java2blog;

public class BitWiseXORMain {

    public static void main(String[] args) {
        int i1 = 2;
        int i2 = 3;

        System.out.println("XOR of 2 and 3: " + (i1 ^ i2));
    }

}

Output:

XOR of 2 and 3: 1

Let’s understand how XOR of 2 and 3 is 1.
XORBItWise
As you can see, XOR operator returns output as 1 if either of its input 1 but not both.

That’s all about XOR operator in java.

]]>
https://java2blog.com/xor-operator-java/feed/ 0