Wednesday, 21 June 2017

Matrix Addition - Java Program

When you add two matrices addition is done index wise you add the element at (0, 0) in the first matrix with the element at (0, 0) in the second matrix, element at (0, 1) in the first matrix with the element at (0, 1) in the second matrix and so on.

As example – If you are adding two matrices of order 3X3

Thus the resultant matrix is -

Also remember these points when adding one matrix with another -

  1. Both of the matrix have to be of same size.
  2. Resultant matrix will also have the same order for the elements. Element at (0, 0) in the first matrix added with (0, 0) of the second matrix becomes the element at index (0, 0) in the resultant matrix too.

Matrix addition Java program

 
import java.util.Scanner;

public class MatrixAddition {

    public static void main(String[] args) {
        int rowM, colM;
        Scanner in = new Scanner(System.in);
        
        System.out.print("Enter Number of Rows and Columns of Matrix : ");
        rowM = in.nextInt();
        colM = in.nextInt();
        
        int M1[][] = new int[rowM][colM];
        int M2[][] = new int[rowM][colM];
        int resMatrix[][] = new int[rowM][colM];
        
        System.out.print("Enter elements of First Matrix : ");
        
        for(int i = 0; i < rowM; i++){
            for(int j = 0; j < colM; j++){
                M1[i][j] = in.nextInt();
            }
        }
        System.out.println("First Matrix : " );
        for(int i = 0; i < rowM; i++){
            for(int j = 0; j < colM; j++){
                System.out.print(" " +M1[i][j]+"\t");
            }
            System.out.println();
        }
        
        System.out.print("Enter elements of Second Matrix : ");
        
        for(int i = 0; i < rowM; i++){
            for(int j = 0; j < colM; j++){
                M2[i][j] = in.nextInt();
            }
        }
        System.out.println("Second Matrix : " );
        for(int i = 0; i < rowM; i++){
            for(int j = 0; j < colM; j++){
                System.out.print(" " +M2[i][j] + "\t");
            }
            System.out.println();
        }
        
        // Addition logic 
        for(int i = 0; i < rowM; i++){
            for(int j = 0; j < colM; j++){
                resMatrix[i][j] = M1[i][j] + M2[i][j];
            }
        }
        
        // Printing the result matrix 
        System.out.println("Result Matrix : " );
        for(int i = 0; i < resMatrix.length; i++){
            for(int j = 0; j < colM; j++){
                System.out.print(" " +resMatrix[i][j]+"\t");
            }
            System.out.println();
        }

    }

}

Output

Enter Number of Rows and Columns of Matrix :  3 3

Enter elements of First Matrix : 1 3 4 2 5 6 4 3 2

First Matrix : 
 1  3  4 
 2  5  6 
 4  3  2
 
Enter elements of Second Matrix : 2 7 1 0 4 6 9 8 1

Second Matrix : 
 2  7  1 
 0  4  6 
 9  8  1

Result Matrix : 
 3  10  5 
 2  9  12 
 13  11  3 

That's all for this topic Matrix Addition - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Matrix Multiplication Java Program
  2. Array in Java
  3. How to remove duplicate elements from an array - Java Program
  4. How to swap or exchange two numbers without using any temporary variable - Java Program

You may also like -

>>>Go to Java Programs page

Monday, 19 June 2017

Object class in Java

Object class is root class of all classes in Java. All classes descend from object directly or indirectly. It is implicitly extended by a class if it is not extending any other class. In case, a class is extending any other class then also it extends object as a multi-level hierarchy inheritance.

As example if we have a class Employee

public class Employee {

}

It is same as

public class Employee extends Object {

}

Since it is implicitly extended by a class so you don’t need to write explicitly that your class is extending Object class.

Methods in Object class

Every class you use or write inherits the instance methods of Object. In your class you may not need to use any of these methods. In case you need to use methods inherited from the Object class you may need to override them with code that is specific to your class.

Method Description
clone()Creates and returns a copy of this object.
boolean equals(Object obj)Indicates whether some other object is "equal to" this one.
protected void finalize()Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
Class<?> getClass()Returns the runtime class of this Object.
int hashCode()Returns a hash code value for the object.
void notify()Wakes up a single thread that is waiting on this object's monitor.
void notifyAll()Wakes up all threads that are waiting on this object's monitor.
String toString()Returns a string representation of the object.
void wait()Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.
void wait(long timeout)Causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.
void wait(long timeout, int nanos)Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.

The clone() Method

If a class, or one of its superclasses, implements the Cloneable interface, you can use the clone() method to create a copy from an existing object. To create a clone, you write:

cloneableObject.clone();

The equals() and hashCode() Method

The equals() method compares two objects for equality and returns true if they are equal.

The value returned by hashCode() is the object's hash code, which is the object's memory address in hexadecimal. If you override the equals() method, you must also override the hashCode() method as well.

The finalize() Method

The Object class provides a callback method, finalize(), that may be invoked on an object when it becomes garbage. Though Object's implementation of finalize() does nothing and you have to override finalize() to do cleanup, such as freeing resources.

The getClass() Method

The getClass() method returns a Class object, which has methods you can use to get information about the class, such as its name (getSimpleName()), its superclass (getSuperclass()), and the interfaces it implements (getInterfaces()).

Note that you cannot override getClass method.

The toString() Method

The Object's toString() method returns a String representation of the object, which is very useful for debugging.

You should always consider overriding the toString() method in your classes. IN your class. You can use toString() along with System.out.println() to display a text representation of an object. In System.out.println() you can provide fields of an object to get all the values and verify those values.

wait() and notify() methods

wait() method causes the currently executing thread to wait.

notify() method wakes up a single thread waiting on this object’s monitor.

Advantages of Object class

  • Since Object class is the super class for all the classes so Object class can be used as a parameter or reference for any class object which helps in making your code more generic and following object oriented principles like polymorphism and dynamic method dispatch.
  • Though with introduction of Generics in Java 5, Object class has lost some of its sheen and now it is not that ubiquitous in code as it used to be. Before generics all collection were storing objects inherently as Object and we needed to typecast them (by downcasting from Object class reference to your class object) to the custom object while retrieving them.
  • Object class also provides some methods that are applicable to all classes and provides basic implementation too which can be overridden by the class wanting to use those methods.

That's all for this topic Object class in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. instanceof Operator in Java
  2. String in Java
  3. Type erasure in Java Generics
  4. Why wait(), notify() and notifyAll() must be called inside a synchronized method or block?
  5. final Vs finally Vs finalize

You may also like -

>>>Go to Java Basics page

Friday, 16 June 2017

How to remove duplicate elements from an array - Java Program

How to remove duplicate elements from an array is a frequently asked interview question and you may be asked to do it without using any of the collection data structure like List or Set or you may be asked to do it using Collection API classes first and then without using any of those classes.

In this post we’ll see code for removal of duplicate elements in an array using Collection API classes and without it.

Using Collection API

One way to remove duplicate elements from an array is to copy your array elements to a HashSet. As you know HashSet only stores unique elements so any repetition of an element will be discarded. Using this property of HashSet once you copy all the array elements to a HashSet you’ll have a Set with only unique elements. Now you can again copy the elements from your Set to create an array which will be your array with duplicate elements removed.

Example code with HashSet

 
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class DuplicateRemoval {

    public static void main(String[] args) {
        int[] intArr = {1, 2, 2, 5, 1, 6, 12, 7, 12, 12, 3, 8};
        int[] outArr = removeDuplicatesUsingSet(intArr);
        System.out.println("Original array");
        for(int i : intArr){
            System.out.print(i+" ");
        }
        System.out.println("");
        System.out.println("after removal");
        for(int i : outArr){
            System.out.print(i+" ");
        }
    }
    
    /**
     * 
     * @param input
     * @return
     */
     public static int[] removeDuplicatesUsingSet(int[] input){
      // Adding array elements to a list
      List<Integer> tempList = new ArrayList<Integer>();
      for(int i : input){
          tempList.add(i);
      }
      // creating a set using list     
      Set<Integer> set = new HashSet<Integer>(tempList);
      Integer[] output = new Integer[set.size()];
      int[] arrOut = new int[output.length];
      set.toArray(output);
      int j =0;
      for(Integer i : output){
       arrOut[j++] = i;
      }
      return arrOut;
    }
}

Output

Original array
1 2 2 5 1 6 12 7 12 12 3 8 
after removal
1 2 3 5 6 7 8 12 

Few things to note here are -

  1. If you are using Set then ordering with in the array doesn’t matter i.e. Array doesn’t have to be sorted.
  2. Ordering of the original array will not be retained once elements are stored in the Set.
  3. In the above code I have used int[] array (array of primitives) that’s why there are some extra steps like creating Array of Integer[] (Integer objects) as toArray() method of the Set works only with objects. If you have an array of objects then you don’t need these extra steps.

Example code with LinkedHashSet

In the above code with HashSet ordering of the array elements is not retained, if you want ordering to be retained then use LinkedHashSet instead.

 
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

public class DuplicateRemoval {

    public static void main(String[] args) {
        int[] intArr = {1, 2, 2, 5, 1, 6, 12, 7, 12, 12, 3, 8};
        int[] outArr = removeDuplicatesUsingSet(intArr);
        System.out.println("Original array");
        for(int i : intArr){
            System.out.print(i+" ");
        }
        System.out.println("");
        System.out.println("after removal");
        for(int i : outArr){
            System.out.print(i+" ");
        }
    }
    
    /**
     * 
     * @param input
     * @return
     */
     public static int[] removeDuplicatesUsingSet(int[] input){
      // Adding array elements to a list
      List<Integer> tempList = new ArrayList<Integer>();
      for(int i : input){
          tempList.add(i);
      }
      // creating a set using list     
      Set<Integer> set = new LinkedHashSet<Integer>(tempList);
      Integer[] output = new Integer[set.size()];
      int[] arrOut = new int[output.length];
      set.toArray(output);
      int j =0;
      for(Integer i : output){
       arrOut[j++] = i;
      }
      return arrOut;
    }
}

Output

Original array
1 2 2 5 1 6 12 7 12 12 3 8 
after removal
1 2 5 6 12 7 3 8 

Now you can see ordering of the array elements is retained. For duplicate elements first occurrence of the element is retained.

Example code without using Collection

If you have to remove duplicate elements of the array without using any of the Collection API classes then you can use the following code.

public class DuplicateRemoval1 {
    /**
     * 
     * @param input
     * @return
     */
    public static int[] removeDuplicates(int[] intArr){
        int i = 1;
        int j = 0;
        Arrays.sort(intArr);
        System.out.println("Sorted array");
        for(int x : intArr){
            System.out.print(x+" ");
        }
        while(i < intArr.length){
            if(intArr[i] == intArr[j]){
                i++;
            }else{
                intArr[++j] = intArr[i++];
            }   
        }
        // This is required to truncate the size of the array
        // otherwise array will retain its original size
        int[] output = Arrays.copyOf(intArr, j+1);
        return output;
    }

    public static void main(String[] args) {
        int[] intArr = {1, 2, 2, 5, 1, 6, 12, 7, 12, 12, 3, 8};
        int[] outArr = removeDuplicates(intArr);
        System.out.println("");
        System.out.println("after removal");
        for(int i : outArr){
            System.out.print(i+" ");
        }
    }

}

Output

Sorted array
1 1 2 2 3 5 6 7 8 12 12 12 
after removal
1 2 3 5 6 7 8 12 

Few things to note here are -

  1. Array has to be sorted in order for this code to work properly that is why array is sorted using Arrays.sort() method.
  2. Once an array is created it will have a fixed size that is why Arrays.copyOf() method is used which can truncate the array to given size. That is required as array size may reduce after removing duplicates.

Time and space complexity

As per the description of the Arrays.sort() method its time complexity is O(n log(n)). Then array is traversed in the while loop and then array is copied. That time complexity will be O(2n) thus the time complexity of the above code is O(n log(n))+O(2n). While the space complexity is O(1).

Using Java Stream

Java Stream API (From Java 8) also provides an option to remove duplicate elements from an array.

int[] intArr = {1, 2, 2, 5, 1, 6, 12, 7, 12, 12, 3, 8};
int tempArr[] = Arrays.stream(intArr).distinct().toArray();
       
System.out.println("");
System.out.println("after removal");
for(int i : tempArr){
 System.out.print(i+" ");
}

Output

after removal
1 2 5 6 12 7 3 8

That's all for this topic How to remove duplicate elements from an array. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to remove duplicate elements from an ArrayList in Java
  2. Matrix Multiplication Java Program
  3. How to Sort elements in different order in TreeSet
  4. Array in Java

You may also like -

>>>Go to Java Programs page

Wednesday, 14 June 2017

How to swap or exchange two numbers without using any temporary variable - Java Program

How to swap or exchange two numbers without using any temporary variable is asked quite frequently in Java interview questions.

This post shows one way to solve this -

public class Swap {
 public static void main(String[] args) {
  int a = 7;
  int b = 8;
  
  System.out.println("value of a - " + a);
  System.out.println("value of b - " + b);
  
  // Swapping logic
  a = a + b;
  b = a - b;
  a = a - b;
  System.out.println("After swap value of a - " + a);
  System.out.println("After swap value of b - " + b);
  
 }
}

Output

value of a - 7
value of b - 8
After swap value of a - 8
After swap value of b - 7

That's all for this topic How to swap or exchange two numbers without using any temporary variable. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Print odd-even numbers using threads and wait-notify
  2. Factorial program in Java
  3. Fibonacci series program in Java
  4. Displaying prime numbers - Java program
  5. How to reverse number - Java Program

You may also like -

>>>Go to Java Programs page

Monday, 12 June 2017

Difference between equals() method and equality operator == in Java

Difference between equals() method and equality operator “==” is a frequently asked interview question. At the same time it may be a bit confusing for the first-time Java programmer to get the subtle differences between equals and “==”.

So in this post let’s try to find the exact differences between the equals() method and equality operator “==” and where does it make sense to use what.

Equality operator “==”

equality operator “==” can be used to compare primitive values as well as objects. Though it works just fine with primitive values but in case of objects “==” will compare the references of the objects not the content of the objects.

equals() method

If you want to compare the actual contents of the objects then you will have to override equals method, which is present in Object class so available to all the other classes. Though the implementation in the Object class is to compare using == operators so default implementation will compare references.

You will have to override equals method in order to compare your custom class objects.

Difference between equals and “==”

Based on what we have seen so far we can surely list some difference between equals and equality operator “==”.

  1. “==” is an operator where as equals is a method.
  2. “==” can be used with primitive values as well as with objects. Equals method can only be used with objects.
  3. When “==” is used for comparing objects it will compare their references not the actual content. Equals method can compare the actual content of the object but you will have to provide your own implementation for determining the equality of two objects.

Example code

Let’s move on to see some hands-on code to test the theory stated so far.

public class EqualsMethodDemo {

 public static void main(String[] args) {
  String str1 = "Test";
  String str2 = new String("Test");
  
  System.out.println(str1 + " == " + str2 + " - " + (str1 == str2));
  
  System.out.println(str1 + " != " + str2 + " - " + (str1 != str2));

 }
}

Output

Test == Test - false
Test != Test – true

Here two strings are created; first one as a string literal and second using new operator so that reference for both the strings are different. Now comparison of these two strings is done using equality “==” operator and not equal (“!=”) operator.

It can be seen that equal returns false even though the content of both the string is same. That is because references of both the strings are different.

Code using equals method

Now if you use equals method to compare the strings then the class used above can be rewritten as -

public class EqualsMethodDemo {

 public static void main(String[] args) {
  String str1 = "Test";
  String str2 = new String("Test");
  
  System.out.println(str1 + " == " + str2 + " - " + str1.equals(str2));
 }
}

Output

Test == Test - true

Now the output is true as equals method is comparing the content of both the strings.

Here note that String class as well as wrapper classes like Integer, Long provide implementation of equals method which compares the content. Same way for your own classes you will have to provide your own implementation of equals method.

Code with Integer

As mentioned above Integer class provides implementation of equals method so that too will compare the content when equal method is used.

public class EqualsMethodDemo {

 public static void main(String[] args) {
  Integer num1 = new Integer(7);
  
  Integer num2 = new Integer(7);
  
  System.out.println(num1 + " == " + num2 + " - " + (num1 == num2));
  
  System.out.println(num1 + " == " + num2 + " - " + num1.equals(num2));
 }
}

Output

7 == 7 - false
7 == 7 - true

That's all for this topic Difference between equals() method and equality operator == in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Equality and Relational Operators in Java
  2. Conditional Operators in Java
  3. String comparison in Java
  4. Overriding hashCode() and equals() method in Java

You may also like -

>>>Go to Java Basics page

Thursday, 8 June 2017

Conditional Operators in Java

The conditional operators Conditional-AND (&&) and Conditional-OR (||) perform operations on two boolean expressions. Result is also a boolean value of true or false based on whether condition is satisfied or not.

How Conditional operator works

Conditional-AND – If any of the two boolean expressions is false then the result is false.

As example - If in condition (A && B), expression A evaluates to false then result is false even if expression B evaluates to true. Let’s make it clear with a table.

A B A&&B
FalseFalseFalse
TrueFalseFalse
TrueTrueTrue
TrueFalseFalse

Conditional-OR - If any of the two boolean expressions is true then the result is true.

As example - If in condition (A || B), expression A evaluates to true then result is true even if expression B evaluates to false. Let’s make it clear with a table.

A B A||B
FalseFalseFalse
TrueFalseTrue
TrueTrueTrue
TrueFalseTrue

Example code

public class ConditionalDemo {

    public static void main(String[] args) {
        int a = 7;
        int b = 8;
        int c = 5;
        
        // This condition evaluates to true
        if((a > c) && (b > c)){
            System.out.println("a and b both are greater than c");
        }
        
        // This condition evaluates to false
        if((a < c) && (b > c)){
            System.out.println("a and b both are greater than c");
        }
        
        // This condition evaluates to true
        if((a < c) || (b > c)){
            System.out.println("OR Condition (a < c) OR (b > c) ");
        }
        
        // This condition evaluates to true
        if(((a > c) && (b > c)) || (c < 3)){
            System.out.println("Both AND and OR used - First 
            expression (a > c) && (b > c) is true so OR 
            condition is true ");
        }
    }
}

Output

a and b both are greater than c
OR Condition (a < c) OR (b > c) 
Both AND and OR used - First expression (a > c) && (b > c) is 
true so OR condition is true 

Short-circuiting behavior

These conditional operators (&&, ||) exhibit "short-circuiting" behavior, which means that the second operand is evaluated only if needed.

As explained above Conditional-AND evaluates to false if any of the two expressions is false. In that case if first expression evaluates to false there is no need to evaluate the second expression as result is going to be false anyway.

Same way for Conditional-OR if the first expression evaluates to true there is no need to evaluate the second expression because result is going to be true anyway.

Example code

Let us try to understand this short circuiting behavior with few examples.

In this example class there are two methods getCompValue1() and getCompValue2() and a conditional expression if(getCompValue1(7) && getCompValue2(5)) which is evaluated.

public class SCDemo {

    public static void main(String[] args) {
        if(getCompValue1(7) && getCompValue2(5)){
            System.out.println("Conditional expression evaluates to true");
        }else{
            System.out.println("Conditional expression evaluates to false");
        }

    }
    
    static boolean getCompValue1(int num){
        System.out.println("In getCompValue1 with value " + num);
        return num > 6;
    }
    
    static boolean getCompValue2(int num){
        System.out.println("In getCompValue2 with value " + num);
        return num > 6;
    }
}

Output

In getCompValue1 with value 7
In getCompValue2 with value 5
Conditional expression evaluates to false

Here note that return value of method getCompValue1() is true (7 > 6). That is why second expression (getCompValue2(5)) is also evaluated which evaluates to false (5 > 6). Thus the conditional expression evaluates to false.

Now if expression is changed in the getCompValue1 in such a way that this method returns false then notice what happens.

Class with getCompValue1() method changed

public class SCDemo {

    public static void main(String[] args) {
        if(getCompValue1(7) && getCompValue2(5)){
            System.out.println("Conditional expression evaluates to true");
        }else{
            System.out.println("Conditional expression evaluates to false");
        }

    }
    
    static boolean getCompValue1(int num){
        System.out.println("In getCompValue1 with value " + num);
        return num > 8;
    }
    
    static boolean getCompValue2(int num){
        System.out.println("In getCompValue2 with value " + num);
        return num > 6;
    }
}

Output

In getCompValue1 with value 7
Conditional expression evaluates to false

Now see the output, second expression is not even evaluated, where getCompValue2() method is called. Because first expression itself is false now (7 > 8). That’s what is "short-circuiting" behavior, where second operand is evaluated only if needed.

Another Short-circuiting example

Let us see another example, many times it happens that check for null or zero and we go on to evaluate expression only if value is not zero or null.

As example

 
if(val1 != 0 && (val2/val1 > 5))

Here it is verified if val1’s value is zero or not. If it is zero expression val1 != 0 itself becomes false so the second expression is not evaluated. That saves you from a run-time exception in case val1 is zero.

That's all for this topic Conditional Operators in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Arithmetic and Unary Operators in Java
  2. Equality and Relational Operators in Java
  3. Ternary operator in Java
  4. instanceof Operator in Java
  5. Switch-Case statement in Java

You may also like -

>>>Go to Java Basics page

Tuesday, 6 June 2017

Equality and Relational Operators in Java

The equality and relational operators evaluate the relationship between the values of the operands. These operators determine if one operand is greater than, less than, equal to, or not equal to another operand.

The equality and relational operators generate a boolean result. If the relationship is true then the result is true if relationship is untrue the result is false.

Equality and Relational operators description

Operator Description
==equal to
!=not equal to
>greater than
>=greater than or equal to
<less than
<=less than or equal to

Note that you must use "==" when testing two primitive values for equality, not "=" which is assignment operator.

Example code

public class RealationalDemo {

    public static void main(String[] args) {
        int a = 7;
        int b = 5;
        int c = 7;
        
        // This should get printed
        if(a == c){
            System.out.println("Values of a and c are equal");
        }
        
        // This won't be printed
        if(a == b){
            System.out.println("Values of a and b are equal");
        }
        
        if(a != b){
            System.out.println("Values of and b are not equal");
        }
        
        if(a > b){
            System.out.println("a is greater than b");
        }
        
        if(a >= c){
            System.out.println("a is greater than or equal to c");
        }
        
        // This won't be printed
        if(a < b){
            System.out.println("a is less than b");
        }
        
        if(b < a){
            System.out.println("b is less than a");
        }
    }

}

Output

Values of a and c are equal
Values of and b are not equal
a is greater than b
a is greater than or equal to c
b is less than a

That's all for this topic Equality and Relational Operators in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Arithmetic and Unary Operators in Java
  2. Conditional Operators in Java
  3. Ternary operator in Java
  4. instanceof Operator in Java
  5. BigDecimal in Java

You may also like -

>>>Go to Java Basics page

Thursday, 1 June 2017

Arithmetic and Unary Operators in Java

For basic mathematical operation the Java programming language provides arithmetic operators like addition (+), subtraction (-), division (/), multiplication(*) and modulus (%, which divides one operand by another and returns the remainder as its result).

Arithmetic operators

Operator Description
+Additive operator (also used for String concatenation)
-Subtraction operator
*Multiplication operator
/Division operator
%Remainder operator

Example code for arithmetic operators

public class ArithmeticDemo {

 public static void main(String[] args) {
  int num1 = 3;
  int num2 = 4;
  int result = num1 + num2;
  System.out.println("Addition result - " + result);
  // Subtraction
  result = result - 3;
  System.out.println("Subtraction result - " + result);
  // Division
  result = result/2;
  System.out.println("Division result - " + result);
  // Multiplication
  result = result * 6;
  System.out.println("Multiplication result - " + result);
  // Modulo division
  result = result % 8;
  System.out.println("Modulo division result - " + result);
  
  // overloaded + operator for string concatenation
  String str1 = "This is ";
  String str2 = "a string";
  String concatString = str1 + str2;
  System.out.println("Concatenated String " + concatString);
 }
}

Output

Addition result - 7
Subtraction result - 4
Division result - 2
Multiplication result - 12
Modulo division result - 4
Concatenated String This is a string

Compound assignment operator

You can also combine the arithmetic operator with the assignment operator to create compound assignments. For example x = x + 7; can also be written as x += 7;

Operator Description
+=Addition assignment
–=Subtraction assignment
*=Multiplication assignment
/=Division assignment
%=Modulus assignment

Compound assignment operator example code

public class OperatorDemo {

 public static void main(String[] args) {
  int x = 5;
  int y = 6;
  int z = 7;
  int p = 4;
  int q = 16;
  
  x += 4;
  System.out.println("x - " + x);
  
  y -= 2;
  System.out.println("y - " + y);
  
  z *= 3;
  System.out.println("z - " + z);
  
  p /= 2;
  System.out.println("p - " + p);
  
  q %= 3;
  System.out.println("q - " + q);

 }
}

Output

x - 9
y - 4
z - 21
p - 2
q – 1

Unary operators

Operator Description
+Unary plus operator; indicates positive value (numbers are positive by default though)
-Unary minus operator; negates an expression
++Increment operator; increments a value by 1
--Decrement operator; decrements a value by 1
!Logical complement operator; inverts the value of a boolean

Example code

Let’s see an example where unary plus operator, unary minus operator and logical component operator are used.

public class OperatorDemo {

 public static void main(String[] args) {
  // unary plus operator
  int x = +5;
  System.out.println("x = " + x);
  
  // unary minus operator
  x = -x;
  System.out.println("x = " + x);
  
  boolean flag = false;
  System.out.println("flag = " + flag);
  // logical component operator
  System.out.println("flag = " + !flag);

 }

}

Output

x = 5
x = -5
flag = false
flag = true

Increment and decrement operator

The increment operator increases its operand value by 1. For example x = x + 1; can be written as x++; using increment operator.

Same way decrement operator decreases its operand value by 1. For example x = x – 1; can be written as x--; using decrement operator.

The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. For example prefix code ++x; or the postfix code x++; both will result in x incremented by one.

Difference between prefix and postfix is that in prefix version operand is incremented/decremented and that value is used in the expression. Whereas in postfix version original value is used in the expression and then the operand is incremented/decremented.

As example -

x = 7;
y = ++x;

Here y has the value 8 because the operand is incremented before using it in expression.

X = 7;
y = x++;

Here y has the value 7 because the original value is used in the expression and then the operand is incremented. So x is 8 but y has the original value of x which was 7.

Example code

public class OperatorDemo {

 public static void main(String[] args) {
  // prefix
  int x = 5;
  int y = ++x;
  System.out.println("x - " + x);
  System.out.println("y - " + y);
  
  // postfix
  int a = 8;
  int b = a++;
  System.out.println("a - " + a);
  System.out.println("b - " + b);
  
  y = --x;
  System.out.println("x - " + x);
  System.out.println("y - " + y);
  
  b = a--;
  System.out.println("a - " + a);
  System.out.println("b - " + b);
  
 }

}

Output

x - 6
y - 6
a - 9
b - 8
x - 5
y - 5
a - 8
b - 9

That's all for this topic Arithmetic and Unary Operators in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Conditional Operators in Java
  2. Ternary operator in Java
  3. instanceof Operator in Java
  4. BigDecimal in Java
  5. Switch-Case statement in Java

You may also like -

>>>Go to Java Basics page