0% found this document useful (0 votes)
20 views

Operators in Java

Uploaded by

soumilmustafi739
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Operators in Java

Uploaded by

soumilmustafi739
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

Ternary Operator

Ternary Operator in Java


Java ternary operator is the only conditional operator that takes
three operands. It’s a one-liner replacement for the if-then-else
statement and is used a lot in Java programming. We can use the
ternary operator in place of if-else conditions or even switch
conditions using nested ternary operators. Although it follows
the same algorithm as of if-else statement, the conditional
operator takes less space and helps to write the if-else
statements in the shortest way possible.
Syntax:
variable = Expression1 ? Expression2: Expression3

If operates similarly to that of the if-else statement as


in Exression2 is executed if Expression1 is true
else Expression3 is executed.
if(Expression1)
{
variable = Expression2;
}
else
{
variable = Expression3;
}

Example:
num1 = 10;
num2 = 20;

res=(num1>num2) ? (num1+num2):(num1-num2)

Since num1<num2,
the second operation is performed
res = num1-num2 = -10

Flowchart of Ternary Operation


Examples of Ternary Operators in Java
Example 1:
Below is the implementation of the Ternary Operator:
Java
Explain

// Java program to find largest among two


// numbers using ternary operator

import java.io.*;

class Ternary {
public static void main(String[] args)
{

// variable declaration
int n1 = 5, n2 = 10, max;

System.out.println("First num: " + n1);


System.out.println("Second num: " + n2);
// Largest among n1 and n2
max = (n1 > n2) ? n1 : n2;

// Print the largest number


System.out.println("Maximum is = " + max);
}
}

Output
First num: 5
Second num: 10
Maximum is = 10

Complexity of the above method:


Time Complexity: O(1)
Auxiliary Space: O(1)
Example 2:
Below is the implementation of the above method:
Java
Explain

// Java code to illustrate ternary operator

import java.io.*;

class Ternary {
public static void main(String[] args)
{

// variable declaration
int n1 = 5, n2 = 10, res;

System.out.println("First num: " + n1);


System.out.println("Second num: " + n2);

// Performing ternary operation


res = (n1 > n2) ? (n1 + n2) : (n1 - n2);

// Print the largest number


System.out.println("Result = " + res);
}
}

Output
First num: 5
Second num: 10
Result = -5

Complexity of the above method:


Time Complexity: O(1)
Auxiliary Space: O(1)
Example 3:
Implementing ternary operator on Boolean values:
Java
Explain

// Java Program for Implementing


// Ternary operator on Boolean values

// Driver Class
public class TernaryOperatorExample {
// main function
public static void main(String[] args)
{
boolean condition = true;
String result = (condition) ? "True" : "False";

System.out.println(result);
}
}

Output
True

Explanation of the above method:


In this program, a Boolean variable condition is declared and
assigned the value true. Then, the ternary operator is used to
determine the value of the result string. If the condition is true,
the value of result will be “True”, otherwise it will be “False”.
Finally, the value of result is printed to the console.
Advantages of Java Ternary Operator
 Compactness: The ternary operator allows you to write simple
if-else statements in a much more concise way, making the
code easier to read and maintain.
 Improved readability: When used correctly, the ternary
operator can make the code more readable by making it easier
to understand the intent behind the code.
 Increased performance: Since the ternary operator
evaluates a single expression instead of executing an entire
block of code, it can be faster than an equivalent if-else
statement.
 Simplification of nested if-else statements: The ternary
operator can simplify complex logic by providing a clean and
concise way to perform conditional assignments.
 Easy to debug: If a problem occurs with the code, the ternary
operator can make it easier to identify the cause of the
problem because it reduces the amount of code that needs to
be examined.
It’s worth noting that the ternary operator is not a replacement
for all if-else statements. For complex conditions or logic, it’s
usually better to use an if-else statement to avoid making the
code more difficult to understand.

Bitwise Operators
Bitwise operators are used to performing the manipulation of individual bits of a
number. They can be used with any integral type (char, short, int, etc.). They are
used when performing update and query operations of the Binary indexed trees.
Now let’s look at each one of the bitwise operators in Java:
1. Bitwise OR (|)
This operator is a binary operator, denoted by ‘|’. It returns bit by bit OR of input
values, i.e., if either of the bits is 1, it gives 1, else it shows 0.
Example:
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)

Bitwise OR Operation of 5 and 7


0101
| 0111
________
0111 = 7 (In decimal)
2. Bitwise AND (&)
This operator is a binary operator, denoted by ‘&.’ It returns bit by bit AND of
input values, i.e., if both bits are 1, it gives 1, else it shows 0.
Example:
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)

Bitwise AND Operation of 5 and 7


0101
& 0111
________
0101 = 5 (In decimal)
3. Bitwise XOR (^)
This operator is a binary operator, denoted by ‘^.’ It returns bit by bit XOR of input
values, i.e., if corresponding bits are different, it gives 1, else it shows 0.
Example:
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)

Bitwise XOR Operation of 5 and 7


0101
^ 0111
________
0010 = 2 (In decimal)
4. Bitwise Complement (~)
This operator is a unary operator, denoted by ‘~.’ It returns the one’s complement
representation of the input value, i.e., with all bits inverted, which means it makes
every 0 to 1, and every 1 to 0.
Example:
a = 5 = 0101 (In Binary)

Bitwise Complement Operation of 5

~ 0101
________
1010 = 10 (In decimal)
Note: Compiler will give 2’s complement of that number, i.e., 2’s complement of
10 will be -6.
Java

Explain

// Java program to illustrate


// bitwise operators

public class operators {


public static void main(String[] args)
{
// Initial values
int a = 5;
int b = 7;

// bitwise and
// 0101 & 0111=0101 = 5
System.out.println("a&b = " + (a & b));

// bitwise or
// 0101 | 0111=0111 = 7
System.out.println("a|b = " + (a | b));
// bitwise xor
// 0101 ^ 0111=0010 = 2
System.out.println("a^b = " + (a ^ b));

// bitwise not
// ~00000000 00000000 00000000 00000101=11111111 11111111
11111111 11111010
// will give 2's complement (32 bit) of 5 = -6
System.out.println("~a = " + ~a);

// can also be combined with


// assignment operator to provide shorthand
// assignment
// a=a&b
a &= b;
System.out.println("a= " + a);
}
}

Output
a&b = 5
a|b = 7
a^b = 2
~a = -6
a= 5
Auxiliary space:O(1)
Time complexity:O(1)
Java

Explain

// Demonstrating the bitwise logical operators

class GFG {
public static void main (String[] args) {

String binary[]={
"0000","0001","0010","0011","0100","0101",
"0110","0111","1000","1001","1010",
"1011","1100","1101","1110","1111"
};

// initializing the values of a and b


int a=3; // 0+2+1 or 0011 in binary
int b=6; // 4+2+0 or 0110 in binary
// bitwise or
int c= a | b;

// bitwise and
int d= a & b;

// bitwise xor
int e= a ^ b;

// bitwise not
int f= (~a & b)|(a &~b);
int g= ~a & 0x0f;

System.out.println(" a= "+binary[a]);
System.out.println(" b= "+binary[b]);
System.out.println(" a|b= "+binary[c]);
System.out.println(" a&b= "+binary[d]);
System.out.println(" a^b= "+binary[e]);
System.out.println("~a & b|a&~b= "+binary[f]);
System.out.println("~a= "+binary[g]);
}
}

Output
a= 0011
b= 0110
a|b= 0111
a&b= 0010
a^b= 0101
~a & b|a&~b= 0101
~a= 1100
Bit-Shift Operators (Shift Operators)
Shift operators are used to shift the bits of a number left or right, thereby
multiplying or dividing the number by two, respectively. They can be used when
we have to multiply or divide a number by two.
Syntax:
number shift_op number_of_places_to_shift;
Types of Shift Operators:
Shift Operators are further divided into 4 types. These are:
1. Signed Right shift operator (>>)
2. Unsigned Right shift operator (>>>)
3. Left shift operator(<<)
4. Unsigned Left shift operator (<<<)
Note: For more detail about the Shift Operators in Java, refer Shift Operator in
Java.
program to implement all Bitwise operators in java for user input
Java

Explain

import java.util.Scanner;

public class BitwiseOperators {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);

System.out.print("Enter first number: ");


int num1 = input.nextInt();

System.out.print("Enter second number: ");


int num2 = input.nextInt();

System.out.println("Bitwise AND: " + (num1 & num2));


System.out.println("Bitwise OR: " + (num1 | num2));
System.out.println("Bitwise XOR: " + (num1 ^ num2));
System.out.println("Bitwise NOT: " + (~num1));
System.out.println("Bitwise Left Shift: " + (num1 << 2));
System.out.println("Bitwise Right Shift: " + (num1 >> 2));
System.out.println("Bitwise Unsigned Right Shift: " + (num1 >>>
2));

input.close();
}
}
Input
Enter first number: 4
Enter second number: 8
Output
Bitwise AND: 0
Bitwise OR: 12
Bitwise XOR: 12
Bitwise NOT: -5
Bitwise Left Shift: 16
Bitwise Right Shift: 1
Bitwise Unsigned Right Shift: 1
Explanation
This program prompts the user to enter two numbers, num1 and num2. It then
performs the following bitwise operations using the &, |, ^, ~, <<, >>, and >>>
operators:
Bitwise AND
Bitwise OR
Bitwise XOR
Bitwise NOT
Bitwise Left Shift
Bitwise Right Shift
Bitwise Zero Fill Right Shift
Advantages
The advantages of using Bitwise Operators in Java are:
1. Speed: Bitwise operations are much faster than arithmetic operations as they
operate directly on binary representations of numbers.
2. Space Optimization: Bitwise operations can be used to store multiple values in
a single variable, which can be useful when working with limited memory.
3. Bit Manipulation: Bitwise operators allow for precise control over individual
bits of a number, which can be useful in various applications such as
cryptography, error detection, and compression.
4. Code Simplification: Bitwise operations can simplify the code by reducing the
number of conditional statements and loops required to perform certain tasks.
In summary, Bitwise Operators are an important tool for optimizing performance,
improving code readability, and reducing code complexity in Java applications.

In this article, we will mainly focus on the

Shift Operators in Java.


By shifting the bits of its first operand right or left, a shift operator
performs bit manipulation on data. The shift operators available in
the Java programming language are listed below. The shift
operator is a java operator that is used to shift bit patterns right
or left.
Types of Shift Operators in Java:
Name of
operator Sign Description

Signed Left The left shift operator moves all bits by a given number of
<<
Shift bits to the left.

Signed Right The right shift operator moves all bits by a given number of
>>
Shift bits to the right.

Unsigned It is the same as the signed right shift, but the vacant
>>>
Right Shift leftmost position is filled with 0 instead of the sign bit.

1. Signed Left Shift Operator in Java


This operator is represented by a symbol <<, read as double less
than.
Syntax:
left_operand << number
Illustration:
 Java

// Left Shifting a byte value

class GFG {

public static void main(String[] args)

byte a = 64, b;

int i;

i = a << 2;

b = (byte)(a << 2);

System.out.println("Original value of a: " + a);

System.out.println("i and b: " + i + " " + b);

Calculating the value of number<<2 if number=2. When the


value of a number is shifted to the left two places, the leftmost
two bits are lost. The number has a value of two. 0010 is the
binary representation of the number 2. In the following example,
the method for doing a left shift is explained:
Example:
In the below example below, the binary number 0010 (in decimal
2) becomes 1000 after shifting the bits to the left (in decimal 8).
 Java

// Java Program to demonstrate

// Signed Left-Shift Operator

// Importing required classes

import java.io.*;

// Main class

class GFG {

// main driver method

public static void main(String[] args)

int number = 2;

// 2 bit left shift operation

int Ans = number << 2;

System.out.println(Ans);

}
Output
8
2. Signed Right Shift Operator in Java
The Right Shift Operator moves the bits of a number in a given
number of places to the right. The >> sign represents the right
shift operator, which is understood as double greater than. When
you type x>>n, you tell the computer to move the bits x to the
right n places.
When we shift a number to the right, the least significant bits
(rightmost) are deleted, and the sign bit is filled in the most
considerable place (leftmost).
Syntax:
left_operand >> number
Illustration:
Calculate the value of number>>2 if number=8.
When the value of a number is shifted to the right two places, the
rightmost two bits are lost. The number has a value of eight. 1000
is the binary representation of the number 8. The following is an
example of how to perform the right shift:
In the example above, the binary number 1000 (in decimal 8)
becomes 0010 after shifting the bits to the right (in decimal 2).
Example:
 Java

// Java program to demonstrate

// the Signed right shift operator

import java.io.*;

class GFG

public static void main (String[] args) {


{

int number = 8;

// 2 bit signed right shift

int Ans = number >> 2;

System.out.println(Ans);

 Java

// Masking sign extension

class GFG {

public static void main (String[] args) {

char hex[]={

'0','1','2','3','4','5',

'6','7','8','9','a','b','c',

'd','e','f'
};

byte b=(byte) 0xf1;

System.out.println("b = 0x" + hex [(b>>4) & 0x0f] + hex[b & 0x0f]);

3. Unsigned Right Shift Operator in Java


Unsigned Right Shift Operator moves the bits of the integer a
given number of places to the right. The sign bit was filled with
0s. The Bitwise Zero Fill Right Shift Operator is represented by the
symbol >>>.
Syntax:
left_operand >>> number

 Java

// Java program to demonstrate

// the Unsigned right shift operator

import java.io.*;

class GFG

public static void main (String[] args)

{
byte num1 = 8;

byte num2 = -8;

System.out.println(num1 >>> 2);

System.out.println(num2 >>> 2);

Output
2
1073741822
Note: For negative bits, the signed and unsigned right shift
operators provide different results.
4. Unsigned Left Shift Operator in Java
Unlike unsigned Right Shift, there is no “<<<” operator in Java
because the logical (<<) and arithmetic left-shift (<<<)
operations are identical.

In Java, instanceof is a keyword used for checking


if a reference variable contains a given type of object reference or
not. Following is a Java program to show different behaviors of
instanceof. Henceforth it is known as a comparison operator
where the instance is getting compared to type returning
boolean true or false as in Java we do not have 0 and 1 boolean
return types.
Example of the Java instanceof Keyword
 Java

// Java Program to Illustrate instanceof Keyword


// Importing required I/O classes

import java.io.*;

// Main class

class GFG {

public static void main(String[] args)

// Creating object of class inside main()

GFG object = new GFG();

// Returning instanceof

System.out.println(object instanceof GFG);

Output
true

Examples of Java instaceof keyword


Here are all the examples of instanceof keywords with their
respective cases:
1. Here we will be creating sample classes with a
parent-child relationship.
 Java

// Java program to demonstrate working of instanceof Keyword

// Class 1

// Parent class

class Parent {

// Class 2

// Child class

class Child extends Parent {

// Class 3

// Main class

class GFG {

// Main driver method

public static void main(String[] args)


{

// Creating object of child class

Child cobj = new Child();

// A simple case

if (cobj instanceof Child)

System.out.println("cobj is instance of Child");

else

System.out.println(

"cobj is NOT instance of Child");

// instanceof returning true for Parent class also

if (cobj instanceof Parent)

System.out.println(

"cobj is instance of Parent");

else

System.out.println(

"cobj is NOT instance of Parent");


// instanceof returns true for all ancestors

// Note : Object is ancestor of all classes in Java

if (cobj instanceof Object)

System.out.println(

"cobj is instance of Object");

else

System.out.println(

"cobj is NOT instance of Object");

Output
cobj is instance of Child
cobj is instance of Parent
cobj is instance of Object

2. instanceof returning false for null


 Java

// Java program to demonstrate that instanceof

// returns false for null


class Test {

class Main {

public static void main(String[] args)

Test tobj = null;

// A simple case

if (tobj instanceof Test)

System.out.println("tobj is instance of Test");

else

System.out.println(

"tobj is NOT instance of Test");

Output
tobj is NOT instance of Test

3. Parent object is not an instance of Child


 Java
// A Java program to show that a parent object is

// not an instance of Child

class Parent {

class Child extends Parent {

// Driver Class

class Test {

// main function

public static void main(String[] args)

Parent pobj = new Parent();

if (pobj instanceof Child)

System.out.println("pobj is instance of Child");

else

System.out.println(

"pobj is NOT instance of Child");

}
}

Output
pobj is NOT instance of Child

4. Parent reference referring to a Child is an instance of


a Child
 Java

// A Java program to show that a parent reference

// referring to a Child is an instance of Child

class Parent {

class Child extends Parent {

// Driver class

class Test {

// main function

public static void main(String[] args)

// Reference is Parent type but object is


// of child type.

Parent cobj = new Child();

if (cobj instanceof Child)

System.out.println("cobj is instance of Child");

else

System.out.println(

"cobj is NOT instance of Child");

Output
cobj is instance of Child

Application of Java instanceof keyword


We have seen here that a parent class data member is accessed
when a reference of parent type refers to a child object. We can
access child data members using typecasting.
Syntax
((child_class_name) Parent_Reference_variable).func.name()
When we do typecasting, it is always a good idea to check if the
typecasting is valid or not. instanceof helps us here. We can
always first check for validity using instanceof, then do
typecasting.
Example
 Java

// Java program to demonstrate that non-method


// members are accessed according to reference

// type (Unlike methods which are accessed according

// to the referred object)

class Parent {

int value = 1000;

class Child extends Parent {

int value = 10;

// Driver class

class Test {

public static void main(String[] args)

Parent cobj = new Child();

Parent par = cobj;

// Using instanceof to make sure that par


// is a valid reference before typecasting

if (par instanceof Child) {

System.out.println(

"Value accessed through "

+ "parent reference with typecasting is "

+ ((Child)par).value);

Output
Value accessed through parent reference with typecasting is 10

Mechanism of System.out.print()
Java System.out.println() is used to print an argument that is passed
to it.
Parts of System.out.println()
The statement can be broken into 3 parts which can be understood
separately:
1. System: It is a final class defined in the java.lang package.
2. out: This is an instance of PrintStream type, which is a public and
static member field of the System class.
3. println(): As all instances of the PrintStream class have a public
method println(), we can invoke the same on out as well. This is an
upgraded version of print(). It prints any argument passed to it and
adds a new line to the output. We can assume that System.out
represents the Standard Output Stream.

Syntax:
System.out.println(parameter)
Parameters: The parameter might be anything that the user
wishes to print on the output screen.
Example of Java System.out.println()
Example 1:
Below is the implementation of System.out.println :
 Java

// Java code to illustrate

// System.out.println();

import java.io.*;

// Driver Class
class GFG {

// main function

public static void main(String[] args)

System.out.println("Welcome");

System.out.println("To");

System.out.println("GeeksforGeeks");

Output
Welcome
To
GeeksforGeeks

Example 2:
Below is the implementation of System.out.println :
 Java

// Java code to illustrate

// System.out.println();

import java.io.*;

// Driver Class
class GFG {

// main function

public static void main(String[] args)

// Declaring variable

int num1 = 10, num2 = 20, sum;

// Printing the variables

System.out.print("The addition of ");

System.out.print(

num1 + " and " + num2 + " is: ");

// Printing the result after operation

System.out.println(num1 + num2);

Output
The addition of 10 and 20 is: 30
Just like System.out, Java provides us with two other standard or
default input-output streams:
1. System.in: This is the standard input stream that is used to
read characters from the keyboard or any other standard input
device. Example:
InputStreamReader inp = new InputStreamReader(System.in);
2. System.err: This is the standard error stream that is used to
output all the error data that a program might throw, on a
computer screen or any standard output device.
Example:
System.err.print("Error");
Overloads of println() method
As we know, Method Overloading in Java allows different methods
to have the same name, but different signatures or parameters
where each signature can differ by the number of input
parameters or type of input parameters or both. From the use of
println() we observed that it is a single method of PrintStream
class that allows the users to print various types of elements by
accepting different type and number of parameters.
For example:
System.out.println(),
System.out.println(int),
System.out.println(double),
System.out.println(string),
System.out.println(character),
etc.
PrintStream has around 10 different overloads of println()
method that are invoked based on the type of parameters
passed by the user.
Example:
 Java

// Java code to illustrate method

// overloading in println()

import java.io.*;

// Driver Class

class PrintLN {

// main function

public static void main(String[] args)


{

// Declaring different datatypes

int num = 10;

char ch = 'G';

String str = "GeeksforGeeks";

double d = 10.2;

float f = 13.5f;

boolean bool = true;

// Various overloads of println() method

System.out.println();

System.out.println(num);

System.out.println(ch);

System.out.println(str);

System.out.println(d);

System.out.println(f);

System.out.println(bool);

System.out.println("Hello");

Output
10
G
GeeksforGeeks
10.2
13.5
true
Hello

Difference between System.out.print() and


System.out.println()
System.out.print()
This method prints the text on the console and the cursor remains
at the end of the text at the console. The next printing takes
place from just here. This method must take atleast one
parameter else it will throw an error.
System.out.println()
This method prints the text on the console and the cursor remains
at the start of the next line at the console. The next printing takes
place from the next line. This method may or may not take any
parameter.
Example:
 Java

// Java code to illustrate difference

// between print() and println()

import java.io.*;

// Driver Class

class Demo_print {

// main function
public static void main(String[] args)

System.out.println("Using print()");

// using print()

// all are printed in the

// same line

System.out.print("GfG! ");

System.out.print("GfG! ");

System.out.print("GfG! ");

System.out.println();

System.out.println();

System.out.println("Using println()");

// using println()

// all are printed in the

// different line

System.out.println("GfG! ");

System.out.println("GfG! ");
System.out.println("GfG! ");

Output:
Using print()
GfG! GfG! GfG!

Using println()
GfG!
GfG!
GfG!
Performance Analysis of System.out.println()
println() is a method that helps display output on a console. This
might be dependent on various factors that drives the
performance of this method. The message passed using println()
is passed to the server’s console where kernel time is required
to execute the task. Kernel time refers to the CPU time. Since
println() is a synchronized method, so when multiple threads are
passed could lead to the low-performance issue.
System.out.println() is a slow operation as it incurs heavy
overhead on the machine compared to most IO operations. There
is an alternative way of performing output operations by
invoking PrintWriter or the BufferedWriter class. They are fast
as compared to the println() of the PrintStream class.

Interesting Questions about Java Operators


1. Precedence and Associativity:
There is often confusion when it comes to hybrid equations which
are equations having multiple operators. The problem is which part to
solve first. There is a golden rule to follow in these situations. If the
operators have different precedence, solve the higher precedence
first. If they have the same precedence, solve according to
associativity, that is, either from right to left or from left to right. The
explanation of the below program is well written in comments within
the program itself.
Java

Explain

public class operators {


public static void main(String[] args)
{
int a = 20, b = 10, c = 0, d = 20, e = 40, f = 30;

// precedence rules for arithmetic operators.


// (* = / = %) > (+ = -)
// prints a+(b/d)
System.out.println("a+b/d = " + (a + b / d));

// if same precedence then associative


// rules are followed.
// e/f -> b*d -> a+(b*d) -> a+(b*d)-(e/f)
System.out.println("a+b*d-e/f = "
+ (a + b * d - e / f));
}
}

Output
a+b/d = 20
a+b*d-e/f = 219
2. Be a Compiler:
The compiler in our systems uses a lex tool to match the greatest
match when generating tokens. This creates a bit of a problem if
overlooked. For example, consider the statement a=b+++c; too many
of the readers might seem to create a compiler error. But this
statement is absolutely correct as the token created by lex is a, =, b, +
+, +, c. Therefore, this statement has a similar effect of first assigning
b+c to a and then incrementing b. Similarly, a=b+++++c; would
generate an error as the tokens generated are a, =, b, ++, ++, +, c.
which is actually an error as there is no operand after the second
unary operand.
Java

Explain

public class operators {


public static void main(String[] args)
{
int a = 20, b = 10, c = 0;

// a=b+++c is compiled as
// b++ +c
// a=b+c then b=b+1
a = b++ + c;
System.out.println("Value of a(b+c), "
+ " b(b+1), c = " + a + ", " + b
+ ", " + c);
// a=b+++++c is compiled as
// b++ ++ +c
// which gives error.
// a=b+++++c;
// System.out.println(b+++++c);
}
}

Output
Value of a(b+c), b(b+1), c = 10, 11, 0
3. Using + over ():
When using the + operator inside system.out.println() make sure to do
addition using parenthesis. If we write something before doing
addition, then string addition takes place, that is, associativity of
addition is left to right, and hence integers are added to a string first
producing a string, and string objects concatenate when using +.
Therefore it can create unwanted results.
Java

Explain

public class operators {


public static void main(String[] args)
{
int x = 5, y = 8;

// concatenates x and y as
// first x is added to "concatenation (x+y) = "
// producing "concatenation (x+y) = 5"
// and then 8 is further concatenated.
System.out.println("Concatenation (x+y)= " + x + y);

// addition of x and y
System.out.println("Addition (x+y) = " + (x + y));
}
}

Output
Concatenation (x+y)= 58
Addition (x+y) = 13
Advantages of Operators in Java
The advantages of using operators in Java are mentioned below:
1. Expressiveness: Operators in Java provide a concise and readable
way to perform complex calculations and logical operations.
2. Time-Saving: Operators in Java save time by reducing the amount
of code required to perform certain tasks.
3. Improved Performance: Using operators can improve performance
because they are often implemented at the hardware level, making
them faster than equivalent Java code.
Disadvantages of Operators in Java
The disadvantages of Operators in Java are mentioned below:
1. Operator Precedence: Operators in Java have a defined
precedence, which can lead to unexpected results if not used
properly.
2. Type Coercion: Java performs implicit type conversions when
using operators, which can lead to unexpected results or errors if
not used properly.

You might also like