• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Java » Java Operators

Compound Assignment Operators in Java Example

By Dinesh Thakur

Besides the assignment operator in Java has combined operators assignment. They contribute to reducing the amount of code as impracticable two operations by an operator. The combined operators have the following syntax:

operand1 operator = operand2 ;

The above expression is identical to the following :

operanda1 = operanda1 operator operanda2 ;

Here is an example of a combined assignment operator :

int x = 2 ;

int y = 4 ;

x * = y; / / Same as x = x * y;

System.out.println (x); / / 8

The most commonly used compound assignment operators are + = (value added operand2 to operand1) – = ( subtract the value of operand right by the value of the first on the left ) . Other composite operators assignment are * = , / = and % = . The following example gives a good idea of ​​the combined operators assignment and their use:

int x = 6 ;

int y = 4 ;

System.out.println (y * = 2 ); / / 8

int z = y = 3 ; / / y = 3 and z = 3

System.out.println (z); / / 3

System.out.println (x | = 1 ); / / 7

System.out.println (x + = 3 ); / / 10

System.out.println (x / = 2 );/ / 5

In the example, first create the variables x and y and we appropriate them values ​​6 and 4. On the next line print the bracket y, then we assign a new value to the operator * = 2 and literal. The result of the operation is 8. Further, in the example apply other compound assignment operators and earn the result of Console.

Comparison Operators in Java Example

By Dinesh Thakur

In this example we reviewed six comparison operator <, <=,>,> =, == And ! =. Comparison operators always produce a boolean result value (true or false). Java has several comparison operator, which can be used for the comparison of any combination of integers, with float or symbols.

Operator

Action

==

equal

! =

Not

> 

Greater

> =

Greater than or equal

< 

Less

<=

Less than or equal

 

In this sample Comparison Operators Example, first created two variables a and b and their appropriated values ​​100 and 50 . The next line printed on the console rules by the method println () to System.out, the result of the comparison of the two variables a and b by the operator > . The returned result is true, because a has a larger value of b. On the next 50 order prints the returned result from the use of the remaining 50 comparison operator with variables a and b.

Here’s a sample program that demonstrates the use of operators for comparison in Java:

public class ComparisonOperators 

{

     public static void main(String args[])

    {

          int a = 100, b = 50;

          System.out.println(“a > b : ” + (a > b)); // true

          System.out.println(“a < b : ” + (a < b)); // false

          System.out.println(“a >= b : ” + (a >= b)); // true

          System.out.println(“a <= b : ” + (a <= b)); // false

          System.out.println(“a == b : ” + (a == b)); // false

          System.out.println(“a != b : ” + (a != b)); // true

    }

}

Increment and Decrement Operators in Java Examples

By Dinesh Thakur

Java has two very useful operators. They are increment (++) and decrement (- -) operators. The increment operator (++) add 1 to the operator value contained in the variable. The decrement operator (- -) subtract from the value contained in the variable.

There are two ways of representing increment and decrement operators.

a) as a prefix i.e. operator precedes the operand. Eg. ++ i; – -j ;

b) as a postfix i.e. operator follows the operand. Eg. i- -; j ++;

In case of prefix increment operator (Eg. ++i), first the value of the operand will be incremented then incremented value will be used in the expression in which it appears.

In case of postfix increment operator (Eg. I++), first the current value of the operand is used in the expression in which it appears and then its value is incremented by 1.

Java Example to implement Increment Operator. 
class IncrementOperator
{
         public static void main(String args[])
       {
               int X=14, Y=17;
               System.out.println("The Value X is : " +X);
               System.out.println("The Value Y is : " +Y);
               System.out.println("The Value ++X is : " +(++X));
               System.out.println("The Value Y++ is : " +(Y++));
               System.out.println("The Value X is : " +X);
               System.out.println("The Value of  Y is : " +Y);
       }
}

Java Example to implement Increment Operator

Java Example to implement Decrement Operator 
class DecrementOperator
{
         public static void main(String args[])
       {
               int X=10, Y=12;
               System.out.println("The Value X is : " +X);
               System.out.println("The Value Y is : " +Y);
               System.out.println("The Value --X is : " +(--X));
               System.out.println("The Value Y-- is : " +(Y--));
               System.out.println("The Value X is : " +X);
               System.out.println("The Value of  Y is : " +Y);
       }
}

Java Example to implement Decrement Operator

Java Example to perform increment and decrement operations using Scanner Class. 
import java.util.*;
class IncrementDecrementUsingScanner
{
                    public static void main(String args[])
           {
                      int a;
                      Scanner scan=new Scanner(System.in);
                      System.out.print("Enter the Value of a : ");
                      a=scan.nextInt();
                      System.out.println("Before Increment A : "+a);
                      System.out.println("After Increment A : "+(++a));
                      a++;
                      System.out.println("After Two Time Increment A : " +a);
                      System.out.println("Before Decrement A : "+a);
                      --a;
                      a--;
                      System.out.println("After Decrement Two Time A : "+a);
           }
}

Java Example to perform increment and decrement operations using Scanner Class

Assignment Operator in Java Example

By Dinesh Thakur

The assignment operator (=) is the most commonly used binary operator in Java. It evaluates the operand on the tight hand side and then assigns the resulting value to a variable on the left hand side. The right operand can be a variable, constant, function call or expression. The type of right operand must be type compatible with the left operand. The general form of representing assignment operator is

                       Variable = expression/constant/function call

                       a = 3; //constant

                       x = y + 10; //expression

In the first case, a literal value 3 is stored in the memory location allocated to variable a. In the second case, the value of expression y+ 10is evaluated and then stored in memory allocated to

variable x.

Consider a statement x = y = z = 3;

Such type of assignment statement in which a single value is given to a number of variables is called multiple assignment statement i.e. value 3 is assigned to the variables x, y and z. The assignment operator (=) has a right to left associatively, so the above expression is interpreted as

(x = (y = (z = 3)));

Here, first the value 3 is assigned to z, then value stored in z is assigned to y and then finally y is assigned to x. Now let us consider a statement

x = 3 = 5;

This type of statement is invalid assignment statement and it will generate an error.

\

There is another kind of assignment statement which combines a simple assignment operator with five arithmetic binary operators and six bitwise operators. This type of operator is known as compound assignment operator. The general syntax of compound assignment operator IS

                 Variable operator= expression/constant/function call

For example: Suppose i is a variable of type int then the statement,

i += 5;

will add the literal 5 to the variable i and store the result back into the variable i. The various compound assignment operators and their effect are as shown in table

Operator

Usage

Effect

+=

-=

*=

/=

%=

&=

|=

^=

<<=

>>=

>>>=

a+=b;

a-=b;

a*=b;

a/=b;

a%=b;

a&=b;

a|=b;

a^=b;

a<<=b;

a>>=b;

a>>>=b;

a=a+b;

a=a-b;

a=a*b;

a=a/b;

 a=a%b;

a=a&b;

a=a|b;

a=a^b;

 a=a<<b;

 a=a>>b;

    a=a>>>b;

Such operator makes the statement concise so they are also called shorthand assignment operator. The expression a = a+b is almost same as that of a += b but the mainadvantage of shorthand assignment operator is that the operand is that the operand on the left handside of the assignment is evaluated only once. The assignment operators have the lowestprecedence as compared to other operators. Only one variable is allowed on the left hand sideof the expression. Therefore a=x*y is valid and m*n=l is invalid.

It is to be kept in mind that assignment operator (=) and equality operator (= =) are different. The assignment operator is used to assign a value to a variable whereas the equality operator used to compare two operands. These operators cannot be used in place of each other. The assignment operator( =) has lower precedence than arithmetic, relational, bitwise, and logical operators.

Java Example to implement assignment operations
import java.util. *;
class AssignmentOperator
{
                  public static void main(String args[])
         {
                    int X=12, Y=13, Z=16;
                    System.out.println("The Assignment Value is : ");
                    X+=2;
                    Y-=2;
                    Z*=2;
                    System.out.println("The Value of X is : " +X);
                    System.out.println("The Value of Y is : " +Y);
                    System.out.println("The Value of Z is : " +Z);
          }
}

Java Example to implement assignment operations

Java Example to perform assignment operations using Scanner Class.
import java.util. *;
class AssignmentOperator
{
                  public static void main(String args[])
         {
                    int X,Y;
                    Scanner scan=new Scanner(System.in);
                    System.out.print("Enter the Value of X : ");
                    X=scan.nextInt();
                    System.out.print("Enter the Value of b : ");
                    Y=scan.nextInt();
                    System.out.println("X += 6 : "+(X+=6));
                    System.out.println("X -= 4 : "+(X-=4));
                    System. out. println("Y *= 4 : "+(Y*=4));
                    System. out. println("Y /= 6 : " +(Y/=6));
          }
}

Java Example to perform assignment operations using Scanner Class.

Java Arithmetic Operators Example

By Dinesh Thakur

Arithmetic operators are used to perform arithmetic calculations. Java provides basic arithmetic operators. They are +,-, *, /, %. The different Arithmetic operators that were used in java programming.

         

                                                             Arithmetic operators

Operators

Example

Meaning

+

–

*

/

%

a+b

a-b

a*b

a/b

a%b

Addition (or) Unary plus

Subtraction (or) Unary minus

Multip Iication

Division

Modulo division (Remainder)

 

class JavaArithmeticOperators  
{
          public static void main(String args[ ])
      {
                 int  a=15, b=9;
                 System.out.println("The Addition is : " +(a+b));
                 System.out.println("The Subtract is : "+(a-b));
                 System.out.println("The Multiple  is : "+(a*b));
                 System.out.println("The Division  is : " +(a/b));
                 System.out.println("The Modulo  is : "+(a%b));
      }
}

Java Arithmetic Operators Example

Break Statement Java Example

By Dinesh Thakur

The break statement terminates the execution of the loop in which it is defined and the control is transferred immediately to the next executable statement after the loop. The break statement is normally used with either while, do-while, for or a switch statement. It is mostly used to exit early from the loop by skipping the remaining statements of loop or switch control structures.

It is simply written as

break;

//Program to Show Importance of Break Statement 
public class ImpBreak
{
       public static void main(String[] args)
    {
         System.out.println("Show Importance of Break Statement");
         for(int i=1; i<=10;i++)
             {
                  System.out.println("i = "+i);
                  if(i==5)
                   {
                       System.out.println("\nBye");
                       break;
                   }
             }
     }
}

Break Statement Java Example

In this example, the for loop executed starting from i=1 to 10 in steps of 1. Now when the condition (i==s)in the body of the loop is satisfied, the break statement causes the control to move out of for loop

Explicit Type Conversion (Type Casting)

By Dinesh Thakur

In addition to the implicit type conversion, Java also provides the facility of explicit type conversion within an expression. In implicit type conversion, a value of lower data type is converted to a value of higher data type. This results in no loss of information. However, if you try to convert a value of higher data type to that of lower data type then java compiler generates an error message “possible loss of precision”. For example:

float i = 12.50;

But if you want to force this conversion which may result in loss of information then this can be accomplished using explicit type casting.

Using explicit type casting, we can override Java’s default type conversions by explicitly specifying our own temporary data type according to the requirements. When we type cast a value, its data type is changed temporarily from its declared data type to the new data type. To explicit type cast, give the target type in parentheses followed by the variable’s name or the value to be cast.

(target_data type) operand;

For example:

float height = (float)5.5;

int d = (int ) (a/b); // Here a and b are of double type

In the first example, integer literal 5.5 is converted to float type and result is stored in variable height. The cast is necessary because there is no automatic conversion from double to float. In the second example, the outcome of the expression is converted to into Parentheses surrounding a/b is necessary, otherwise the cast to int will only apply to a and not to the outcome of the result.

Explicit type conversion is also known as narrowing a type. The explicit type casting is important in situations where the fractional part of a number is to be preserved. E.g. If you want to calculate the percentage marks of student appearing in examination in five different subjects of 100 marks each and suppose that total marks obtained is stored in a variable tot_marks_obt of type int, then on executing the statement.

per = tot_marks_obt/5;

gives you the percentage as an integer value and fractional part will be ignored. Thus in

this case, to retain fractional part you need to cast variable tot _marks _ obt to type double before dividing it by 5 as shown in the following statement.

per = (double)tot_marks_obt/5;

In the above statement, the type of variable tot_marks_obt is converted explicitly into double data type and stored in temporary variable of type double which is then divided by 5.0 (implicitly conversion from int to double) and this percentage calculated in fraction form stored in variable per. Here, the conversion does not change the original data type of operand and type is temporarily changed within the expression.

To illustrate the concept of explicit typecasting, let us consider a program to convert temperature given in Fahrenheit to one in Celsius.

/* Program to Convert temperature given in Fahrenheit to celsius using Explicit type conversion */

class ExplicitTypeConversion

{

         public static void main(String args[])

    {

          double c;

          double f=96;

          c = (double) 5/9 * (f-32);

           System.out.println(“Temperature in Celcius is : ” +c);

     }

}

Mathematical Operations in Java Example

By Dinesh Thakur

Most of the computer languages typically support advanced math operations (such as square root, trigonometric sine, cosine etc.) by way of function libraries. Java also provides a range of methods that support such functions in the standard libraries Math class stored in the package java.lang. Java’s Math class contains a collection of methods and two constants that compute standard mathematical functions.

All the methods and constants available in the Math class are static; so they can simply be referred by just writing class name Math and name of the method or constant you want to use separated by a period (.)

//Program to Show various Methods of Math Class
 public class MathematicalOperations
{
       public static void main(String [] args)
   {
          System.out.println("Absolute value -16 = " + Math.abs(-16));
          System.out.println("Sine of va1ue PI/2= " + Math.sin(Math.PI/2));
          System.out.println("Arc Cosine of -1  = " + Math.acos(-1));
          System.out.println("Upper limit of 7.8 = "+ Math.ceil(7.8));
          System.out.println("Lower limit of 7.8 = "+ Math.floor(7.8));
          System.out.println("Maximum of 15 and 20 = " +Math.max(15,20));
          System.out.println("Rounded value = " + Math.round(7.68));
          System.out.println("Square root of 4 = " + Math.sqrt(4.0));
          System.out.println("2 power 3 is  = " + Math.pow(2.0,3.0));
          System.out.println("Log of 1000 = " + Math.log(1000.0));
   }
}

Mathematical Operations in Java Example

Implicit Type Conversion in Java Example

By Dinesh Thakur

The conversion of a data type which is carried out automatically by the compiler without programmer intervention is called the implicit type conversion. When two variables of different data types are involved in the same expression, the Java compiler uses built-in library functions to trans- form the variables to common data type before evaluating the expression. To decide which variable’s data type is to be converted, the Java compiler follows certain rules and converts the lower data type to that of a higher data type. This is known as widening a type.

 

The rules in the sequence in which they are checked are as follows.

1. If one of the operands is double, the other is promoted to double before the operation is carried out.

2. Otherwise, if one of the operands is float, the other is promoted to float before the operation is carried out.

3. Otherwise, if one of the operands is long, the other is promoted to long before the operation is carried out.

4. Otherwise if either operand is int, the other operand is promoted to int.

5. If neither operand is double, float, long or int, both operands are promoted to int.

//Program to Show Implicit Type Conversion  
public class ImplicitTypeConversion
{
         public static void main (String[] args)
     {
           byte  i=10;
           long  j=1+8;
           double k=i*2.5 +j;
           System.out.println("I =" +i);
           System.out.println("J =" +j);
           System.out.println("K =" +k);
      }
}

Implicit Type Conversion in Java Example

Conditional Operator in Java with Example

By Dinesh Thakur

Conditional operator (?:) is the only ternary operator available in Java which operates on three operands. The symbol “?” placed between the first and the second operand , and ” : ” is inserted between the second and third operand. The first operand (or expression) must be a boolean . The conditional operator together with operands form a conditional expression which takes the following form.

expr1? expr2:expr3

where expr1 is a boolean expression and expr2 and expr3 are the expressions of any type other than void. The expr2 and expr3 must be of the same type.

 

If expr1 has value true, the operator returns a result expr2 .
If expr1 has value false, the operator returns a result expr3 .

During the  calculates the value of the first argument . if it has the true value , then calculates the second (middle ) argument returned as a result . However , if the calculated result of the first argument is false, then it is given the third ( last ) argument the returned as a result. Here is an example of the use of the operator ” ? ” :

//Program to Find greatest of three numbers using Conditional Operator
 import java.util.Scanner; //program uses Scanner class
public class ConditionalOperator
{
        public static void main(String[] args)
    {
          int a,b,c,result;
          //create Scanner object to obtain input from keyboard
          Scanner input=new Scanner(System.in);
          System.out.print("Enter the Three Number : "); //prompt for input
          a=input.nextInt();   //Read First number
          b=input.nextInt();   //Read Second number
          c=input.nextInt();   //Read third number
          result = (a>b)? ((a>c)?a:c) : ((b>c)?b:c);
          System.out.println( result  + " is Greatest");
    
     }
 }

Conditional Operator in Java with Example

Bitwise Operators in Java Example

By Dinesh Thakur

Java provides an extensive bit manipulation operator for programmers who want to communicate directly with the hardware. These operators are used for testing, setting or shifting individual bits in a value. In order to work with these operators, one should be aware of the binary numbers and two’s complement format used to represent negative integers.

The bitwise operators can be used on values of type long, int, short, char or byte, but cannot be used with boolean, float, double, array or object type.

The bitwise AND (&) bitwise OR (!) and bitwise Exclusive OR (^)are the three logical bitwise operators. These are the binary operators which compare the two operands bit by bit. If either of the operands with a bitwise operator is of type long then the result will be long, otherwise the result is of type int.

Bitwise AND (&)operator combines its two integer operands by performing a logical AND operation on their individual bits. It sets each bit in the result to 1 if corresponding bits in both operands are 1. One of the applications of bitwise AND operator is forcing selected bits of an operand to 0.

Bitwise OR (|)operator combines its two integer operands by performing a logical OR operation on their individual bits. It sets each bit in the result to 1if the corresponding bits in either or both of the operands are 1. One of the applications of bitwise OR is forcing selected bits of an operand to 1.

Bitwise Exclusive OR operator (^) combines its two integer operands by performing a logical XOR operands on their individual bits. It sets each bit in the result to 1 if the corresponding bits in two operands are different. One of the applications of bitwise Exclusive OR operator is to change 0’s to 1’s and l’s to 0’s.

Bitwise One’s Complement operator (-) Bitwise complement operator (-) is a unary operator. It inverts each bit of its operand i.e. Is become Os and Os become Is. This operator can be used to

1.  To encrypt the contents of a file which can later be decrypted.

2.  To store negative numbers in some computers that supports one’s complement method for storing negative number.

Let us consider an operand a = 0000 0000 0001 0010 then on performing (~a) we get

-a = 1111 1111 1110 1101

Bitwise shift left operator (<<) shifts the bits of the left operand to left by number of positions specified by the right operand. The high order bits of the left operand are lost and 0 bits are shifted in from the right .It has the following syntax

Operand1 << operand2

Here, operand1 is binary representation of a number to be the shifted and operand2 represents the number of positions by which it is shifted.

Bitwise Shift Right operator (>>)shifts the bits of the left operand to right by a number of positions specified by the right operand. The low order bits of the left operand are lost and the high order bits shifted in are either 0 or 1 depending upon whether the left operand is positive or negative. If the left operand is positive, Os are shifted into the high order bits and if the left operand is negative, 1’s are shifted instead. It has the following syntax.

operand1>>operand2

Here, operand1 is the binary representation of a number to be shifted and operand2 represents the number of positions by which it is shifted.

Bitwise Shift Right with zero fill (>>>) operator is similar to bitwise shift right (>>) operator with the exception that it always shifts zero’s into the high order bits of the result regardless of the sign of the left hand operand.

//program Showing bitwise Operators 
import static java.lang.Long .*;
 public class BitwiseOperators
 {
    public static void main (String [] args)
    {
       Short x=20,y=0xaf ;
       Short z= -24;
       System.out.println(" x & y --> " + (x & y));
       System.out.println(" x | y --> " + (x | y));
       System.out.println(" x ^ y --> " + (x ^ y));
       System.out.println(" z << 2 --> " + (z<<2));
       System.out.println(" z >>> 2 --> " +  (z>>>2));
       System.out.println(" z >> 2 --> " + (z>>2));
      
    }
 }

Bitwise Operators in Java Example

Logical Operators in Java Examples

By Dinesh Thakur

Logical operators are used to combine one or more relational expressions that results in formation of complex expressions known as logical expressions. Like relational operators, the logical operators evaluate the result of logical expression in terms of Boolean values that can only be true or false according to the result of the logical expression.

In Java, there are six logical operators: logical AND (&), logical OR (|), logical exclusive

OR i.e. XOR (^), logical negation (!), conditional AND (&&), conditional OR  (||). All the logical operators are binary operators except logical negation which is a unary operator. The logical AND (&) operator evaluates to true if and only if both its operands evaluates to true. The logical OR (I) operator evaluates to true if and only if either of its operands evaluate true. The logical exclusive OR i.e. XOR (^) operator evaluates to true if and only if either, but not both, of its operands are true. In other words, it evaluates to false if both the operands are false.

The logical NOT(!) operator takes a single operand and evaluates to true if the operand is false and evaluates to false if the operand is true.

 

Table shows you the different Logical Operators used in Java Programming

 

                                                             Logical Operators

 

Operators

Meaning

&&

||

!

Logical AND

                                    Logical OR

Logical NOT

 

The logical operators && and || are used when we want to form compound conditions by combining two or more relations. Logical operators return results indicated in the following table.

 

x

Y

X && Y

X || Y

T

T

F

F

T

F

T

T

T

F

F

F

T

T

T

F

 

//program Showing Logical Operations
public class LogicalOperators
{
    public static void main (String [] args)
    {
       int x=6 ,y=4,z=5;
       System.out.println(" x>y & y>z-->" + (x>y & y>z));
       System.out.println(" x>y | y>z-->" + (x>y | y>z));
       System.out.println(" x>y ^  y>z-->" +(x>y  ^ y>z));
       System.out.println(" x>y && y>z-->"  +  (x>y&& y>z));
       System.out.println(" x>y || y>z-->"  +  (x>y||y>z));
       System.out.println(" !(x>y)--> " + (!(x>y)));  
    }
    
}

Logical Operators in Java Examples

Java Example to implement Logical Operators using Scanner Class. 
import java.util.*;
import java.lang.*;
class LogicalOperatorsUsingScanner
{
              public static void main(String args[])
         {
                  int x,y,z;
                  Scanner scan = new Scanner(System.in);
                  System.out.print("Enter the Value of x : ");
                  x=scan.nextInt();
                  System.out.print("Enter the Value of y : ");
                  y=scan.nextInt();
                  System.out.print("Enter the Value of z : ");
                  z=scan.nextInt();
                  System.out.println("x>y and x>z : "+((x>y) &&(x>z)));
                  System.out.println("x not equal to z : "+(x!=z));
          }
}

Java Example to implement Logical Operators using Scanner Class

Relational Operators in Java Example

By Dinesh Thakur

Relational operators also known as comparison operators are used to check the relation between two operands. In other words, the operators used to make comparisons between two operands are called relational operators. Relational operators are binary operators and hence require two operands. The result of a relational operation is a Boolean value that can only be true or false according to the result of the comparison.

Relational operators are normally used with if statements, while loop, do-while loop and for loop to make branching and looping decisions.

 

Table shows you the different relational operators used in java programming.

 

                                                          Relational Operators

 

Operator

Operations

Example

< 

> 

<=

>=

==

!=

Less than

Greater than

Less than or equal to

Greater than equal to

Equal to

Not equal to

x<y

x>y

x<=y

x>=y

x=y

x!=y

 

//program Showing Relational Operations
  public class RelationalOperators
{
       public static void main (String[] args)
    {
          int x=5 ,y=3;
          System.out.println("x  > y --> " + (x>y));
          System.out.println("x  < y --> "  + (x<y));
          System.out.println("x <= y --> " + (x<=y));
          System.out.println("x >= y --> " + (x>=y));
          System.out.println("x == y --> " + (x==y));
          System.out.println("x != y --> " + (x!=y));
      
     }
}

Relational Operators in Java Example

Java Example to Perform Relational Operations Using Scanner Class. 
import java.util. *;
class RelationalOperationsUsingScanner
{
          public static void main(String args[])
       {
                int x,y;
                Scanner scan = new Scanner(System.in);
                System.out.print("Enter the Value of x : ");
                x=scan.nextInt();
                System.out.print("Enter the Value of y : ");
                y=scan.nextInt();
                System.out.println("x>y : "+(x>y));
                System.out.println("x<y : "+(x<y));
                System.out.println("x>=y : "+( x>=y));
                System.out.println("x<=y : "+( x<=y));
        }
}

Java Example to Perform Relational Operations Using Scanner Class

Arithmetic Operators in Java Examples

By Dinesh Thakur

The Arithmetic operators are used to perform arithmetic operations. The Arithmetic operators are binary operators that work with integers, floating point numbers and even characters (i.e. they can be used with any primitive type except the boolean).

There are five arithmetic operators available in Java which include addition (+), subtraction (-), multiplication (*), division (/) and modulus (%) operator. The modulus operator tells us what would be the remainder after integer division is performed on a particular expression. Unlike C/C++, the modulus operator can also be applied to floating point values. The rest of the operators have same meaning as they have in mathematics.

The operands acted on by arithmetic operators must represent numeric values. Thus the operands can be integer quantities, floating point quantities or characters. The Arithmetic operators when used with characters operate on Unicode values of the characters.

The result of division of one integer quantity by another is referred to as integer division as this operation results in a quotient without a decimal point. On the other hand, if division is carried out with two floating point numbers or with one floating point and one integer number, the result will be a floating point quotient.

//Program Showing Arithmetic Operations
public class ArithmeticOperators
 {
          public static void main (String[] args)
      {
            float x=10.5f ,y=2.3f ;
            System.out.println(" x+y = " + (x+y));
            System.out.println(" x-y = " + (x-y));
            System.out.println(" x*y = " + (x*y));
            System.out.println(" x/y = " + (x/y));
            System.out.println(" x%y = " + (x%y));
      
       }
 }

Arithmetic Operators in Java Examples

Java Example to Perform Arithmetic Operation Using Scanner Class. 
 
import java.util. *;
class ArithmeticOperatorsUsingScanner
{
           public static void main(String args[])
       {
                 int a,b;
                 Scanner scan=new Scanner(System.in);
                 System.out.print("Enter the Value of a : ");
                 a=scan.nextInt();
                 System.out.print("Enter the Value of b : ");
                 b=scan.nextInt();
                 System.out.println("Addition is : " +(a+b));
                 System.out.println("Subtraction is : "+( a-b));
                 System.out.println("Multiplication is : "+( a*b));
                 System.out.println("Division is : "+( a/b));
                 System.out.println("Modulus is : "+( a%b));
       }
}

Java Example to Perform Arithmetic Operation Using Scanner Class

Area of Triangle in Java Example

By Dinesh Thakur

Here is the Java Example for Area of Triangle

class AreaofTriangle 
{
            public  static  void  main  (String  args [ ] )
            {
                        int b,h;
                        float  a;
                        b =17;
                        h=23;
                        a= (float) 1/2*b*h;
                        System.out.println("Area  of  Triangle  is  "+a);
            }
 
}

Area of Triangle in Java

(float) before 1/2 is used for typecasting. If we divide two integers, the result is also as integer. The benefit of using (float) is that it converts 1/2 into 1.0/2.0 and obviously we get the result as 0.5. If we don’t typecast 1/2, then the result of division of two integers is also an integer, hence the result of ½ comes out to be 0, so it is compulsory to typecast an expression which has a / (divide sign).

Shift Operators in Java Examples

By Dinesh Thakur

The left-shift, right-shift, and zero-fill-right-shift operators <<, >>, and >>> shift the individual bits of an integer by a specified integer amount.

Example:

 

x << 3;

y >> 1;

z >>> 2;

 

In the first example, the individual bits of the integer variable x are shifted to the left three places (so it is multiplied by 23 i.e. 8). In the second example, the bits of yare shifted 1 place to the right, so it is divided by 2. Finally, the third example shows z being shifted to the right two places, with zeros shifted into the two leftmost places (it is divided by 4 and its sign is converted to positive value if it was negative earlier) .

The number being shifted in this case is the decimal 7, which is represented in binary as 0111. The first right-shift operation shifts the bits two places to the right, resulting in the binary number 0001, or decimal 1. The next operation, a left-shift, shifts the bits one place to the left, resulting in the binary number 1110, or decimal 14. The last operation is a zero-fill-right-shift, which shifts the bits one place to the right, resulting in the binary number 0011, or decimal 3.

With positive numbers, there is no difference between the two operators right-shift operator and zero-fill-right-shift operator, they both shift zeros into the upper bits of a number. The difference arises when we start shifting negative numbers. The negative numbers have the high-order bit set to 1. The right-shift operator preserves the high-order bit and effectively shifts the lower 31 bits to the right. This behavior yields results for negative numbers similar to those for positive numbers. That is, -8 shifted right by one results in -4. The zero-fill-right-shift operator, on the other hand, shifts zeros into all the upper bits, including the high-order bit. When this shifting is applied to negative numbers, the high-order bit becomes 0 and the number becomes positive.

 

Here is the Java Example for left-shift, right-shift, and zero-fill-right-shift operators

class   ShiftOperators    
{  
            public  static  void  main  (String  args[ ] )
            {
                         int  x  =  7 ;
                         System.out.println ("x  =  "  +  x) ;
                         System.out.println ("x  >>  2  =  "  +   (x  >>  2) ) ;
                         System.out.println ("x  <<  1  =  "  +  (x  <<  1) ) ;
                        System.out.println ("x  >>>  1  =  "  +  (x  >>>  1) ) ;   
                }                 
}

Shift Operators in Java

Bitwise AND, OR, and XOR Operators in Java Example

By Dinesh Thakur

The bitwise AND, OR, and XOR operators (&, |,and /\) all act on the individual bits of an integer. These operators are useful when an integer is being used as a bit field.

Here is the Java Example for Bitwise AND, OR, and XOR Operators

class  BitwiseANDORXOROperators  
{
            public  static  void  main  (String  args[ ] )
            {
                        int  x  =  13,  y  =  10;
                        System.out.println("x   =  "  +  x);
                        System.out.println("y  =  "  +  y);
                        System.out.println("x  &  y  =  "  +  (x  &  y) ) ;
                        System.out.println("x  |  y  =  "  +  (x  |   y) ) ;
                        System.out.println("x  ^  Y  =  "  +  (x  ^  y) ) ;
            }
}

Bitwise AND, OR, and XOR Operators

Bitwise Complement Operator Example in Java

By Dinesh Thakur

The bitwise complement operator (~), which perform a bitwise negation of an integer value. Bitwise negation means that each bit in the number is toggled. In other words, all the binary 0s become 1s and all the binary 1s become 0s.

x = 8;

Y = ~x;

Integer numbers are stored in memory as a series of binary which can be either 0 or 1. A number is considered negative if the highest order bit in the number is set to 1. Because a bitwise complement converts all the bits in a number including the high order bit (sign bit). Since the number becomes negative, it is in 2’s compliment form. To know its decimal value, first we will subtract 1 from the number and then perform l’s compliment onto it (i.e. convert 1 to 0 and 0 into 1).

Here is the Java Example for Bitwise Complement Operator:

class BitwiseComplementOperator 
{         
            public  static  void  main  (String  args[ ] )
            {
                        int  x  =  8 ;
                        System.out.println("x  =  "  +  x);
                        int  y  =  ~x;
                        System.out.println ("y  =  "  +  y);
            }
}

Bitwise Complement Operator

Java Continue With Label Example

By Dinesh Thakur

This Java continue statement with label example shows how to use java continue statement to skip to next iteration of the labeled loop.

Here is the Java Example for the program JavaContinueWithLabelExample :

import java.util.Scanner; 
public class JavaContinueWithLabelExample
{
      public static void main(String[] args)
    {
        try
              {
             int n ;
             System.out.println("Enter an the Starting Number");
             Scanner scan = new Scanner(System.in);
             n = scan.nextInt();
             if ( n < 0 )
             System.out.print("Please Enter Number should be non-negative.");
           else
            {
               firstforloop: for (int i = n;i<=100; i++)
                 {
                    secondforloop: for (int j = n; j < i; j++)
                       {
                         if (i % j == 0)
                           {
                             continue firstforloop;
                           }
                       }
                             System.out.print(i +",");
                             if (i == 61)
                               {
                                 continue firstforloop;
                               }
                   }
               }
         }
catch (Exception e){}
   }
}

Java continue statement with label example

Java Continue Statement Example

By Dinesh Thakur

Like the break statement, the continue statement also skips the remaining statements of the body of the loop where it is defined but instead of terminating the loop, the control is transferred to the beginning of the loop for next iteration. The loop continues until the test condition of the loop becomes false.

When used in the while and do-while loops, the continue statement causes the test condition to be evaluated immediately after it. But in case of for loop, the increment/decrement expression evaluates immediately after the continue statement and then the test condition is evaluated.
It is simply written as
continue;

Here is the Java Example for the program JavaContinueStatementExample :

public class JavaContinueStatementExample 
{
       public static void main(String[] args)
         {
         try
          {
            int[] arrayOfInts = { 92, 37, 31, 59, 112, 176 , 230, 81, 62, 7 };
            int search = 112;
            System.out.print("All Elements are : ");
            for(int i=0; i < arrayOfInts.length ; i ++)
               {
                 if(arrayOfInts[i] == search)
                         continue;
                  else
                  System.out.print(arrayOfInts[i] + " , " );
               }
           }
catch (Exception e){}
       }
}

Java Continue Statement Example

Java Break Statement with Label Example

By Dinesh Thakur

This Java break statement with label example shows how to use java break statement to terminate the labeled loop.

Here is the Java Example for the program JavaBreakWithLableExample :

import java.util.Scanner; 
public class JavaBreakWithLableExample
{
           public static void main(String[] args)
       {
          try
                   {
             int n ;
             System.out.println("Enter an the Starting Number");
             Scanner scan = new Scanner(System.in);
             n = scan.nextInt();
             if ( n < 0 )
             System.out.print("Please Enter Number should be non-negative.");
             else
                  {
                 firstforloop: for (int i = n;i<=100; i++)
                         {
                          secondforloop: for (int j = n; j < i; j++)
                             {
                                if (i % j == 0)
                                  {
                                     continue firstforloop;
                                  }
                             }
                                System.out.print(i +",");
                                if (i == 61)
                                  {
                                    break firstforloop;
                                  }
                        }
                     }
               }
catch (Exception e){}
  }
}

Java break statement with label example

Java Break Statement Example

By Dinesh Thakur

This Java break statement example shows how to use java break statement to terminate the loop. The Java break statement has two forms labeled and unlabeled. in the below example You can see unlabeled form.

Here is the Java Example for the program JavaBreakStatementExample :

public class JavaBreakStatementExample 
{
      public static void main(String[] args)
     {
        try
         {
              int[] arrayOfInts = { 92, 37, 31, 59, 112, 176, 230, 81, 62, 7 };
              int search = 112;
              System.out.print("Elements before 112 are : ");
              for(int i=0; i < arrayOfInts.length ; i ++)
                 {
                    if(arrayOfInts[i] == search)
                       break;
                    else
                      System.out.print(arrayOfInts[i] + " , " );
                 }
          }
                    catch (Exception e){}
    }
}

Java break statement example

Constant – What is Constant? Type of Constant

By Dinesh Thakur

Constants: Constants in java are fixed values those are not changed during the Execution of program. A literal is a constant value that can be classified as integer literals, string literals and boolean literals. To make a static field constant in Java, make a variable as both static and final. java supports several types of Constants  those are  

Integer Constants:  Integer Constants refers to a Sequence of digits which Includes only negative or positive Values and many other things those are as follows

• An Integer Constant must have at Least one Digit.
• it must not have a Decimal value.
• it could be either positive or Negative.
• if no sign is Specified then it should be treated as Positive.
• No Spaces and Commas are allowed in Name.

Real Constants:

• A Real Constant must have at Least one Digit.
• it must have a Decimal value.
• it could be either positive or Negative.
• if no sign is Specified then it should be treated as Positive.
• No Spaces and Commas are allowed in Name.

Like 251, 234.890 etc are Real Constants.

In The Exponential Form of Representation the Real Constant is Represented in the two Parts The part before appearing e is called mantissa whereas the part following e is called Exponent.

• In Real Constant The Mantissa and Exponent Part should be Separated by letter e.
• The Mantissa Part have may have either positive or Negative Sign.
• Default Sign is Positive.

Single Character Constants

A Character is Single Alphabet a single digit or a Single Symbol that is enclosed within Single inverted commas.

Like ‘S’ ,’1’ etc are Single  Character Constant.

String Constants:  String is a Sequence of Characters Enclosed between double Quotes These Characters may be digits ,Alphabets  Like “Hello” , “1234” etc.

Backslash Character Constants: Java Also Supports Backslash Constants those are used in output methods For Example \n is used for new line Character These are also Called as escape Sequence or backslash character Constants For Ex:    

\t  For Tab  ( Five Spaces in one Time ).

\b Back Space etc.

final Variable (OR Constant Variable)

Variables are useful when you need to store information that can be changed as program runs. However, there may be certain situations in the program in which the value of variable should not be allowed to modify. This is accomplished using a special type of variable known as final variable. The final variable also called constant variable. It is a variable with a value that cannot be modified during the execution of the program.

To declare a final variable, use the final keyword before the variable declaration and initialize it with a value. Its syntax is

final datatype varName = value;

For example:

final double PI = 3.141592;

This statement declares a variable PI of type double which is initialized to 3.141592, that cannot be modified. If an attempt is made to modify a final variable after it is initialized, the compiler issues an error message “cannot assign a value to final variable PI”.

You can also defer the initialization of final variable, such a final variable is know as blank final. However, it must be initialized before it is used.
Final variables are benefitical when one need to prevent accidental change to method parameters and with variables accessed by anonymous class.
Now consider a program to calculate the area of the circle,

//Area of the circle
public class AreaCircle {
    public static void main(String[] args) {
        int r = 10; // initializing radius
        final double PI = 3.141592 //final variable
        double area;
        //PI = 3.142; will generate an error
        area = PI * r * r;
        System.out.println(“Area of circle is –>” +area);
     }
}
Output: Area of circle is — >314.1592
NOTE: It is recommended to declare a final variable in uppercase

What is Identifiers,Literals,Operator and Separators

By Dinesh Thakur

Identifiers :- The Identifiers are those which are used for giving a name to a variable  ,class and method ,packages ,interfaces etc There Are Some Rules against for using the Identifiers

 

  • Name of Identifier not be a Keyword
  • Must be Start from Alphabet not from digit
  • Uppercase and Lowercase are Different
  • Can be any length

 

Literals :- Literals are Sequence of Characters like Digits ,alphabets ,letters those are used for Representing the Value of the Variable  Like Integer Literals, String Literals, Float Literals

 

Operator:- operators are the Special Symbols those have  specific functions associated with them for Performing the operations it needs some Operands

 

        Operands are those on which operations are performed by the Operators

        Like  2 +3

        In this + is the Operator and 2 and 3 Operands.

 

Separators :- These are Special Symbols used to Indicate the group of code that is either be divided or arrange into the Block The Separators includes Parentheses, Open Curly braces  Comma, Semicolon, or either it will  be period or dot Operator

 

Java Operator | Types of Operator in Java

By Dinesh Thakur

An operator is a special symbol that tells the compiler to perform a specific mathematical or logical operation on one or more operands where an operand can be an expression. An operation is an action(s) performed on one or more operands that evaluates mathematical expressions or change the data. [Read more…] about Java Operator | Types of Operator in Java

Primary Sidebar

Java Tutorials

Java Tutorials

  • Java - Home
  • Java - IDE
  • Java - Features
  • Java - History
  • Java - this Keyword
  • Java - Tokens
  • Java - Jump Statements
  • Java - Control Statements
  • Java - Literals
  • Java - Data Types
  • Java - Type Casting
  • Java - Constant
  • Java - Differences
  • Java - Keyword
  • Java - Static Keyword
  • Java - Variable Scope
  • Java - Identifiers
  • Java - Nested For Loop
  • Java - Vector
  • Java - Type Conversion Vs Casting
  • Java - Access Protection
  • Java - Implicit Type Conversion
  • Java - Type Casting
  • Java - Call by Value Vs Reference
  • Java - Collections
  • Java - Garbage Collection
  • Java - Scanner Class
  • Java - this Keyword
  • Java - Final Keyword
  • Java - Access Modifiers
  • Java - Design Patterns in Java

OOPS Concepts

  • Java - OOPS Concepts
  • Java - Characteristics of OOP
  • Java - OOPS Benefits
  • Java - Procedural Vs OOP's
  • Java - Polymorphism
  • Java - Encapsulation
  • Java - Multithreading
  • Java - Serialization

Java Operator & Types

  • Java - Operator
  • Java - Logical Operators
  • Java - Conditional Operator
  • Java - Assignment Operator
  • Java - Shift Operators
  • Java - Bitwise Complement Operator

Java Constructor & Types

  • Java - Constructor
  • Java - Copy Constructor
  • Java - String Constructors
  • Java - Parameterized Constructor

Java Array

  • Java - Array
  • Java - Accessing Array Elements
  • Java - ArrayList
  • Java - Passing Arrays to Methods
  • Java - Wrapper Class
  • Java - Singleton Class
  • Java - Access Specifiers
  • Java - Substring

Java Inheritance & Interfaces

  • Java - Inheritance
  • Java - Multilevel Inheritance
  • Java - Single Inheritance
  • Java - Abstract Class
  • Java - Abstraction
  • Java - Interfaces
  • Java - Extending Interfaces
  • Java - Method Overriding
  • Java - Method Overloading
  • Java - Super Keyword
  • Java - Multiple Inheritance

Exception Handling Tutorials

  • Java - Exception Handling
  • Java - Exception-Handling Advantages
  • Java - Final, Finally and Finalize

Data Structures

  • Java - Data Structures
  • Java - Bubble Sort

Advance Java

  • Java - Applet Life Cycle
  • Java - Applet Explaination
  • Java - Thread Model
  • Java - RMI Architecture
  • Java - Applet
  • Java - Swing Features
  • Java - Choice and list Control
  • Java - JFrame with Multiple JPanels
  • Java - Java Adapter Classes
  • Java - AWT Vs Swing
  • Java - Checkbox
  • Java - Byte Stream Classes
  • Java - Character Stream Classes
  • Java - Change Color of Applet
  • Java - Passing Parameters
  • Java - Html Applet Tag
  • Java - JComboBox
  • Java - CardLayout
  • Java - Keyboard Events
  • Java - Applet Run From CLI
  • Java - Applet Update Method
  • Java - Applet Display Methods
  • Java - Event Handling
  • Java - Scrollbar
  • Java - JFrame ContentPane Layout
  • Java - Class Rectangle
  • Java - Event Handling Model

Java programs

  • Java - Armstrong Number
  • Java - Program Structure
  • Java - Java Programs Types
  • Java - Font Class
  • Java - repaint()
  • Java - Thread Priority
  • Java - 1D Array
  • Java - 3x3 Matrix
  • Java - drawline()
  • Java - Prime Number Program
  • Java - Copy Data
  • Java - Calculate Area of Rectangle
  • Java - Strong Number Program
  • Java - Swap Elements of an Array
  • Java - Parameterized Constructor
  • Java - ActionListener
  • Java - Print Number
  • Java - Find Average Program
  • Java - Simple and Compound Interest
  • Java - Area of Rectangle
  • Java - Default Constructor Program
  • Java - Single Inheritance Program
  • Java - Array of Objects
  • Java - Passing 2D Array
  • Java - Compute the Bill
  • Java - BufferedReader Example
  • Java - Sum of First N Number
  • Java - Check Number
  • Java - Sum of Two 3x3 Matrices
  • Java - Calculate Circumference
  • Java - Perfect Number Program
  • Java - Factorial Program
  • Java - Reverse a String

Other Links

  • Java - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW