Showing posts with label Java operator. Show all posts
Showing posts with label Java operator. Show all posts

Friday, January 20, 2023

Ternary Operator in Java With Examples

Java includes a conditional operator known as ternary operator (?:), which can be thought of as a shorthand for an if-else statement. This operator is known as the ternary operator because it uses three operands.

General form of ternary operator in Java

boolean-exp ? expression2 : expression3

If boolean expression evaluates to true then expression2 is evaluated and its value becomes the result of the operator; otherwise (if boolean expression is false) expression3 is evaluated and its value becomes the result of the operator.

For example if you have this statement-

int result = someCondition ? value1 : value2;

The statement should be read as: "If someCondition is true, assign the value of value1 to result. Otherwise, assign the value of value2 to result."

Note that in Java Ternary operator both expression2 and expression3 should return the value of same (or compatible) type.

Usage of Java ternary operator

Though switch-case statement in Java provides performance improvement over if-else statement there is no performance improvement if ternary operator is used over an if-else statement but it makes the code more readable and terse.

Ternary operator example-

int val = (i > 10) ? i * 5 : i * 10;

Here val is assigned the value (i * 5) if i is greater than 10 otherwise val is assigned the value (i * 10).

Writing the same thing using if-else will be a multiple line affair.

 
if(i > 10){
  val = i * 5;
}else{
  val = i * 10;
}

If you were to write a method where value is returned using the same logic, with ternary operator the method will look like-

 
public int getValue(int i){
 return (i > 10) ? i * 5 : i * 10;
}

In this case if-else statement can also be made more compact-

 
public static int getValue(int i){
  if(i > 10)
    return i * 5;
  return i * 10;
}

Not its up to you to decide what looks more readable. I feel once you get a grip over ternary operator it will always be more readable.

Another example– This Java ternary operator example uses String expression and prints a message based on the value of the string.

 
String day = "saturday";
System.out.println(((day.equalsIgnoreCase("saturday") || day.equalsIgnoreCase("sunday"))
    ? "weekend! time to party!" : "Working day"));

Output

weekend! time to party!

Nested ternary operator

Ternary operator in Java can be nested but doing that considerably decreases the readability.

As example if you have the logic that number of transactions in a week is-

upto 5 means ok, 
more than 5 and less than 10 means notify the user 
more than 10 means alarm!!

Then you can use the nested ternary operator

String noOfTransactions = (i < 5) ? "ok" : (i > 5 && i < 10) ? "notify" : "alarm";

Generally it is not advisable to use nested ternary operator as it defeats the purpose of making the code more readable in contrast it makes it look more complex and confusing in most of the cases.

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

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Switch-Case Statement in Java With Examples
  2. instanceof Operator in Java With Examples
  3. Arithmetic And Unary Operators in Java
  4. String in Java Tutorial
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. Java Pass by Value or Pass by Reference
  2. Inheritance in Java
  3. Abstraction in Java
  4. Difference between Encapsulation and Abstraction in Java
  5. Initializer block in Java
  6. HashMap Vs LinkedHashMap Vs TreeMap in Java
  7. Difference Between ArrayList And LinkedList in Java
  8. Difference Between CountDownLatch And CyclicBarrier in Java
  9. Lambda Expressions in Java 8

Tuesday, January 17, 2023

Difference Between equals() Method And equality Operator == in Java

Difference between equals() method and equality operator “==” in Java is a frequently asked Java 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 “==” in Java and where does it make sense to use what.

Java equality operator “==”

equality operator “==” in Java 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 in Java

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. Default implementation of equals() in the Object class compares using == operator, 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 “==” in Java

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.

Java example using “==” operator and equals()

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 = new String("Test");
    String str2 = new String("Test");
    
    System.out.println(str1 + " == " + str2 + " - " + (str1 == str2));
    
    System.out.println(str1 + ".equals(" + str2 + ") - " + str1.equals(str2));
 }
}

Output

Test == Test - false
Test.equals(Test) - true

Here two string objects, having the same content, are created. Now comparison of these two strings is done using equality “==” operator and .equals() method.

It can be seen that “==” returns false even though the content of both the string is same. That is because references of both the strings are different. Where as comparison using .equals() returns true.

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.

Integer class equals method example

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!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Equality and Relational Operators in Java
  2. Conditional Operators in Java With Examples
  3. Ternary Operator in Java With Examples
  4. String Comparison in Java equals(), compareTo(), startsWith() Methods
  5. equals() And hashCode() Methods in Java

You may also like-

  1. Java Pass by Value or Pass by Reference
  2. Access Modifiers in Java - Public, Private, Protected and Default
  3. How HashMap Works Internally in Java
  4. Fail-Fast Vs Fail-Safe Iterator in Java
  5. Nested Try Statements in Java Exception Handling
  6. Marker Interface in Java
  7. Java Multithreading Interview Questions And Answers
  8. Lambda Expressions in Java 8

Tuesday, April 12, 2022

Conditional Operators in Java With Examples

The conditional operators in Java- 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 does Java Conditional operator work

Conditional-AND– If any of the two boolean expressions is false then the result is false. For example in condition (A && B), if 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. For example in condition (A || B), if 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

Java conditional operator example

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 of Java conditional operators

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.

Short-circuiting behavior Java example

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 we 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 first part of the condition verifies if val1’s value is zero or not. If val1's value 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 With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

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

You may also like-

  1. BigDecimal in Java With Examples
  2. StringBuilder Class in Java With Examples
  3. try-catch Block in Java Exception Handling
  4. Type Casting in Java With Conversion Examples
  5. Access Modifiers in Java - Public, Private, Protected and Default
  6. How HashSet Works Internally in Java
  7. Callable and Future in Java With Examples
  8. Autowiring in Spring Using @Autowired and @Inject Annotations

Tuesday, April 5, 2022

instanceof Operator in Java With Examples

In your application sometimes you may have a situation where you would like to check the type of an object during run time. For that you can use instanceof operator in Java.

Syntax of Java instanceof operator is as follows.

obj instanceof type;

Here obj is refrence to an object and type is a class type. This check will return true if obj is of the class type given on the right hand side of the instanceof operator or can be cast into that type safely.

When to use Java instanceof operator

An object can only be cast to its own class or one of its super-type, if you try to cast to any other object you may either get a compile-time error or a class-cast exception (run-time).

In order to avoid that error it is better to check whether the object can be cast to that type safely or not. For that you can use instanceof operator.

It is evidently important to use instanceof operator when you have a parent-child relationship, an inheritance hierarchy with a parent class and more than one child classes.

A super type can hold reference to an object of itself or the sub-types. But doing the opposite, when you want a conversion from super-type to sub-type, you will need type casting.

As example, if there is class A and two child classes class B and class C, then object of type A can refer to object of type B or to an object of type C.

A a;
B b = new B();
C c = new C();
a = b; // permitted
a = c; // permitted
b = a; // results in compile-time error (Type mismatch)

This (a = b) or (a = c) can be done with out any need of casting.
But doing the opposite (b = a;) will need casting. What you will have to do is-

b = (B) a;
a = c;

and for class C object c = (C)a;

Now, in your application if you have a hierarchy where there are many child classes, type casting may cause problem as you may not be knowing the actual type of the object. In this case you need instanceof operator to check the type of the object before doing the casting.

Java instanceof operator Example

In the example there is an interface Shape which is implemented by two classes Triangle and Rectangle. Using the references of these classes type checks are performed with the help of Java instanceof operator.

interface Shape{
  public void area();
}

class Triangle implements Shape{
  // area method implementation for Triangle class
  public void area(){
   System.out.println("In area method of Triangle");
  }
}

class Rectangle implements Shape{
  // area method implementation for Rectangle class
  public void area(){
   System.out.println("In area method of Rectangle");
  }
}

public class InstanceOfExample {

 public static void main(String[] args) {
  Triangle t = new Triangle();
  Rectangle r = new Rectangle();
  Shape s = t;
  // returns true
  if(t instanceof Shape){
   System.out.println("Triangle is of type Shape");
  }
  // returns true
  if(r instanceof Shape){
   System.out.println("Rectangle is of type Shape");
  }
  // returns false
  if(s instanceof Rectangle){
   System.out.println("Triangle is of type Rectangle");
  }
 }
}

Output

Triangle is of type Shape
Rectangle is of type Shape

Java example using instanceof operator and casting

Here I have a class hierarchy where Payment is an interface and there are two classes CashPayment and CardPayment implementing the Payment interface.

Payment interface

public interface Payment {
 public boolean proceessPayment(double amount);
}

CashPayment class

import org.netjs.examples.interfaces.Payment;

public class CashPayment implements Payment {
 @Override
 public boolean proceessPayment(double amount) {
  System.out.println("Cash payment done for Rs. " + amount);
  return true;
 }
}

CardPayment class

import org.netjs.examples.interfaces.Payment;

public class CardPayment implements Payment {

 @Override
 public boolean proceessPayment(double amount) {
  System.out.println("Card Payment done for Rs. " + amount);
  return true;
 }
 
 public void printSlip(){
  System.out.println("Printing slip for payment" );
 }
}

Note that in CardPayment class there is an extra method printSlip().

As a good programmer you are trying to write a good, object-oriented principles following code and want to have proper polymorphism. In order to achieve that you will refer the instances of child classes CardPayment and CashPayment through the super type instance Payment. Only to call printSlip() method you will need downcasting to the child class. Something similar to what is written below.

import org.netjs.examples.interfaces.Payment;

public class PaymentDemo {

 public static void main(String[] args) {
  PaymentDemo pd = new PaymentDemo();
  Payment payment = new CashPayment();
  pd.doPayment(payment, 100);
  payment = new CardPayment();
  pd.doPayment(payment, 300);
 }
 
 public void doPayment(Payment pd, int amt){
  pd.proceessPayment(amt);
  //downcasting
  CardPayment cardPay = (CardPayment)pd;
  cardPay.printSlip();
 }
}

But running this will throw ClassCastException at run time -

Cash payment done for Rs. 100.0
Exception in thread "main" java.lang.ClassCastException: org.netjs.examples.impl.CashPayment cannot be cast to org.netjs.examples.impl.CardPayment
 at org.netjs.examples.impl.PaymentDemo.doPayment(PaymentDemo.java:17)
 at org.netjs.examples.impl.PaymentDemo.main(PaymentDemo.java:10)

What went wrong here is that you want to call printSlip() method only if the instance is of type CardPayment. But doPayment() method of the PaymentDemo class is having Payment (Super class) as the argument which can refer to instances of CardPayment as well as CashPayment.

Here you can use instanceof operator to check if passed reference is actually of type CardPayment, if yes, then only call the printSlip() method.

Code after including instanceof operator

public class PaymentDemo {

 public static void main(String[] args) {
  PaymentDemo pd = new PaymentDemo();
  Payment payment = new CashPayment();
  pd.doPayment(payment, 100);
  payment = new CardPayment();
  pd.doPayment(payment, 300);
 }
 
 public void doPayment(Payment pd, int amt){
  pd.proceessPayment(amt);
  if (pd instanceof CardPayment){
   CardPayment cardPay = (CardPayment)pd;
   cardPay.printSlip();
  }
 }
}

Output

Cash payment done for Rs. 100.0
Card Payment done for Rs. 300.0
Printing slip for payment

Here note how instanceof operator is used to check the type and if appropriate type is there then only condition gets fulfilled.

Points to remember

  1. An object can only be cast to its own class or one of its super-type.
  2. instanceof operator in Java provides you a way to get run time information about the type of the object.
  3. instanceof operator, if used, should be used sporadically. If you are compelled to use instanceof operator a lot that would mean some inherent flaw in the design of your application.
  4. A use case where use of instanceof operator makes sense is trying to write a generalized logic for a class hierarchy, so that your logic can work for any object of the class hierarchy.

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

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Package in Java
  2. Access Modifiers in Java - Public, Private, Protected and Default
  3. Encapsulation in Java
  4. Polymorphism in Java
  5. Ternary operator in Java With Examples

You may also like-

  1. Association, Aggregation and Composition in Java
  2. Initializer Block in Java
  3. Array in Java With Examples
  4. String Vs StringBuffer Vs StringBuilder in Java
  5. How and Why to Synchronize ArrayList in Java
  6. Difference between HashMap and ConcurrentHashMap in Java
  7. Java ThreadLocal Class With Examples
  8. Spring Bean Life Cycle

Saturday, January 8, 2022

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 in Java

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.

Java equality and relational operators example

Following example shows the Java equality and relational operators in action.

public class RelationalDemo {
  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!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Arithmetic And Unary Operators in Java
  2. Conditional Operators in Java
  3. Array in Java
  4. String in Java Tutorial
  5. this Keyword in Java With Examples

You may also like-

  1. What are JVM, JRE and JDK in Java
  2. Java Automatic Numeric Type Promotion
  3. Why main Method static in Java
  4. Java Pass by Value or Pass by Reference
  5. Access Modifiers in Java - Public, Private, Protected and Default
  6. ArrayList in Java With Examples
  7. ConcurrentHashMap in Java With Examples
  8. Lambda Expressions in Java 8

Friday, January 7, 2022

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).

In this post we'll see what all arithmetic operators are available in Java. Apart from that we'll also learn about Compound assignment operators, Unary operators and Increment and decrement operators in Java.


Arithmetic operators in Java

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

Java arithmetic operators example

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 operators in Java

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

Java Compound assignment operators example

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 in Java

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

Java Unary operators example

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 operators in Java

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.

Java Increment and decrement operators example

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!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Conditional Operators in Java With Examples
  2. Ternary Operator in Java With Examples
  3. instanceof Operator in Java With Examples
  4. BigDecimal in Java With Examples
  5. Switch-Case Statement in Java With Examples

You may also like-

  1. Association, Aggregation and Composition in Java
  2. Initializer block in Java
  3. Array in Java
  4. Nested class and Inner class in Java
  5. Serialization and Deserialization in Java
  6. Race Condition in Java Multi-Threading
  7. How HashSet Works Internally in Java
  8. Spring Bean Life Cycle