Lara

Logical Operators

 

         Operators

 

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups

         Arithmetic Operators

         Relational Operators

         Bitwise Operators

         Logical Operators

         Assignment Operators

         Misc Operators

          

         The Arithmetic Operators

Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators

Assume integer variable A holds 10 and variable B holds 20, then

Show Examples

Operator

Description

Example

+ (Addition)

Adds values on either side of the operator.

A + B will give 30

- (Subtraction)

Subtracts right-hand operand from left-hand operand.

A - B will give -10

* (Multiplication)

Multiplies values on either side of the operator.

A * B will give 200

/ (Division)

Divides left-hand operand by right-hand operand.

B / A will give 2

% (Modulus)

Divides left-hand operand by right-hand operand and returns remainder.

B % A will give 0

++ (Increment)

Increases the value of operand by 1.

B++ gives 21

-- (Decrement)

Decreases the value of operand by 1.

 

 

         The Relational Operators

There are following relational operators supported by Java language.

Assume variable A holds 10 and variable B holds 20, then

Show Examples

Operator

Description

Example

== (equal to)

Checks if the values of two operands are equal or not, if yes then condition becomes true.

(A == B) is not true.

!= (not equal to)

Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.

(A != B) is true.

> (greater than)

Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.

(A > B) is not true.

< (less than)

Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.

(A < B) is true.

>= (greater than or equal to)

Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.

(A >= B) is not true.

<= (less than or equal to)

Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.

 

 

         The Bitwise Operators

Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte.

Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b = 13; now in binary format they will be as follows

a = 0011 1100†

b = 0000 1101

-----------------

a&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a = 1100 0011

The following table lists the bitwise operators

Assume integer variable A holds 60 and variable B holds 13 then

Show Examples

Operator

Description

Example

& (bitwise and)

Binary AND Operator copies a bit to the result if it exists in both operands.

(A & B) will give 12 which is 0000 1100

†| (bitwise or)

Binary OR Operator copies a bit if it exists in either operand.

(A | B) will give 61 which is 0011 1101

^ (bitwise XOR)

Binary XOR Operator copies the bit if it is set in one operand but not both.

(A ^ B) will give 49 which is 0011 0001

~ (bitwise compliment)

Binary Ones Complement Operator is unary and has the effect of 'flipping' bits.

(~A ) will give -61 which is 1100 0011 in 2's complement form due to a signed binary number.

<< (left shift)

Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.

A << 2 will give 240 which is 1111 0000

>> (right shift)

Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.

A >> 2 will give 15 which is 1111

>>> (zero fill right shift)

Shift right zero fill operator. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros.

A >>>2 will give 15 which is 0000 1111

 

The Logical Operators

The following table lists the logical operators

Assume Boolean variables A holds true and variable B holds false, then

Show Examples

Operator

Description

Example

&& (logical and)

Called Logical AND operator. If both the operands are non-zero, then the condition becomes true.

(A && B) is false

|| (logical or)

Called Logical OR Operator. If any of the two operands are non-zero, then the condition becomes true.

(A || B) is true

! (logical not)

Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.

!(A && B) is true

 

The Assignment Operators

Following are the assignment operators supported by Java language

Show Examples

Operator

Description

Example

=

Simple assignment operator. Assigns values from right side operands to left side operand.

C = A + B will assign value of A + B into C

+=

Add AND assignment operator. It adds right operand to the left operand and assign the result to left operand.

C += A is equivalent to C = C + A

-=

Subtract AND assignment operator. It subtracts right operand from the left operand and assign the result to left operand.

C -= A is equivalent to C = C Ė A

*=

Multiply AND assignment operator. It multiplies right operand with the left operand and assign the result to left operand.

C *= A is equivalent to C = C * A

/=

Divide AND assignment operator. It divides left operand with the right operand and assign the result to left operand.

C /= A is equivalent to C = C / A

%=

Modulus AND assignment operator. It takes modulus using two operands and assign the result to left operand.

C %= A is equivalent to C = C % A

<<=

Left shift AND assignment operator.

C <<= 2 is same as C = C << 2

>>=

Bitwise AND assignment operator.

C >>= 2 is same as C = C >> 2

&=

Right shift AND assignment operator.

C &= 2 is same as C = C & 2

^=

bitwise exclusive OR and assignment operator.

C ^= 2 is same as C = C ^ 2

|=

bitwise inclusive OR and assignment operator.

C |= 2 is same as C = C | 2

 

Miscellaneous Operators

There are few other operators supported by Java Language.

Conditional Operator ( ? : )

Conditional operator is also known as the ternary operator. This operator consists of three operands and is used to evaluate Boolean expressions. The goal of the operator is to decide, which value should be assigned to the variable. The operator is written as

variable x = (expression) ? value if true : value if false

Following is an example

Example

public class Test {

 

†† public static void main(String args[]) {

††††† int a, b;

††††† a = 10;

††††† b = (a == 1) ? 20: 30;

††††† System.out.println( "Value of b is : " +† b );

 

††††† b = (a == 10) ? 20: 30;

††††† System.out.println( "Value of b is : " + b );

†† }

}

This will produce the following result

Output

Value of b is : 30

Value of b is : 20

 

instanceof Operator

This operator is used only for object reference variables. The operator checks whether the object is of a particular type (class type or interface type). instanceof operator is written as

( Object reference variable ) instanceof† (class/interface type)

If the object referred by the variable on the left side of the operator passes the IS-A check for the class/interface type on the right side, then the result will be true. Following is an example

Example

public class Test1 {

 

†† public static void main(String args[]) {

 

††††† String name = "James";

 

††††† // following will return true since name is type of String

 

††††† boolean result = name

instanceof String;

††††† System.out.println( result );

†† }

}

This will produce the following result

Output

true

 

Precedence of Java Operators

Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator

For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3 * 2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

Category

Operator

Associativity

Postfix

>() [] . (dot operator)

Left toright

Unary

>++ - - ! ~

Right to left

Multiplicative

>* /

Left to right

Additive

>+ -

Left to right

Shift

>>> >>> <<

Left to right

Relational

>> >= < <=

Left to right

Equality

>== !=

Left to right

Bitwise AND

>&

Left to right

Bitwise XOR

>^

Left to right

Bitwise OR

>|

Left to right

Logical AND

>&&

Left to right

Logical OR

>||

Left to right

Conditional

?:

Right to left

Assignment

>= += -= *= /= %= >>= <<= &= ^= |=

Right to left

 

public class Test2 {

 

†† public static void main(String args[]) {

††††† int a = 60;† /* 60 = 0011 1100 */

††††† int b = 13;† /* 13 = 0000 1101 */

††††† int c = 0;

 

††††† c = a & b;††††††† /* 12 = 0000 1100 */

††††† System.out.println("a & b = " + c );

 

††††† c = a | b;††††††† /* 61 = 0011 1101 */

††††† System.out.println("a | b = " + c );

 

††††† c = a ^ b;††††††† /* 49 = 0011 0001 */

††††† System.out.println("a ^ b = " + c );

 

††††† c = ~a;†††††††††† /*-61 = 1100 0011 */

††††† System.out.println("~a = " + c );

 

††††† c = a << 2;†††††† /* 240 = 1111 0000 */

††††† System.out.println("a << 2 = " + c );

 

††††† c = a >> 2;†††††† /* 15 = 1111 */

††††† System.out.println("a >> 2† = " + c );

 

††††† c = a >>> 2;††††† /* 15 = 0000 1111 */

††††† System.out.println("a >>> 2 = " + c );

†† }

}

This will produce the following result

Output

a & b = 12

a | b = 61

a ^ b = 49

~a = -61

a << 2 = 240

a >> 15

a >>> 15

 

Note :

         The unary bitwise complement operator "~" inverts a bit pattern; it can be applied to any of the integral types, making every "0" a "1" and every "1" a "0". For example, a byte contains 8 bits; applying this operator to a value whose bit pattern is "00000000" would change its pattern to "11111111".

 

Note :

         The signed left shift operator "<<" shifts a bit pattern to the left, and the signed right shift operator ">>" shifts a bit pattern to the right. The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand. The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign

 

Note :

         The bitwise & operator performs a bitwise AND operation.

         The bitwise ^ operator performs a bitwise exclusive OR operation.

         The bitwise | operator performs a bitwise inclusive OR operation.

Bitwise and Bit Shift Operators

~†††††† Unary bitwise complement

<<††††† Signed left shift

>>††††† Signed right shift

>>>†††† Unsigned right shift

&†††††† Bitwise AND

^†††††† Bitwise exclusive OR

|†††††† Bitwise inclusive OR

 

         Basics:

1) Binary format has just two bit, 0 and 1 and that's why is called binary.

2) In binary arithmetic :

0 + 0 = 0

0 + 1 = 1

1 + 1 = 10

3) Negation bitwise operation will change 0 to 1 and 1 to 0 and itís denoted by ~.

4) OR bitwise operation will return 1 if any of operand is 1 and zero only if both operands are zeros.

5) AND bitwise operation will return 1 only if both operands are 1, otherwise zero.

6) XOR bitwise operation will return 1 if both operands are different e.g. one of them is 1 and other is zero and returns zero if both operands are same e.g. 1,1 or 0,0

7) Integral types in Java (int, long, short and byte) are signed numbers in Java where most significant bit (MSB) represent sign of number. 1 will denote a negative number and 0 as MSB will denote a positive numbers

8) Negative numbers in Java are represented as 2's complement of number. 2's complement of a number is 1's complement + 1 and 1's complement means all zero will turn to 1 and all 1 turned to zero in a binary number e.g. 1's complement of 10 would be 01. and 2's complement of 10 would be 10+1 = 11 (all in binary).

Bitwise unary complement operator (~) Example

         Bitwise unary complement operator changes bits from 0 to 1, or vice versa and can only be applied on integral types. Itís not applicable on boolean types.For example int variable contains 32 bits; Applying this operator to a value whose bit pattern is 0000 would change its pattern to 11111. Here is an example of bitwise unary complement operator in Java :

int number = 2; //0010

//example of bitwise unary complement operator (~)

System.out.println(" value of number before: " + number);

System.out.println(" value of number after negation: " + ~number);

Output:

value of number before: 2

value of number after negation: -3

Bitwise AND operator (&) Example

         Bitwise AND operator works similar to logical AND operator (&&) and returns 1 if both operands are 1. Difference with bitwise AND and logical AND also known as short-circuit AND operator is that, logical AND operator applies only to boolean type. Also bitwise AND operator is denoted by singe & while short circuit AND operator is denoted by &&. If A represent 0010 and B represent 1010 then result of A&B would be 0010. Here is another example of bitwise AND operator in Java

Test3:

int a = 2; //0010

int b = 4; //0100

//example of bitwise AND operator &

System.out.println("Result of a&b is " + (a&b)); //should be zero

Output:

Result of a&b is 0


 

Bitwise OR operator (|) Example

Bitwise OR operator is also similar to bitwise AND operator and applies to individual bits. Itís different than short-circuit OR operator, which is denoted by (||) and operates on boolean variable. Bitwise OR operator produce result of OR operation on two bits as shown in below example. Like other bitwise operator in Java, bitwise OR is only applicable to integral types.

Test 4:

int a = 2; //0010

int b = 4; //0100

System.out.println(" value of A bitwise OR B in Java : " + (a|b) );

Output:

value of A bitwise OR B in Java : 6

Bitwise XOR operator (^) Example

Bitwise XOR operator is denoted by ^ and also work on individual bits. There is no short-circuit XOR operator in Java and result of bitwise XOR operator is XOR operation of individual bits. see the truth table of XOR operation for predicting result. in short bitwise XOR operators will return 1 if both bits are different and return 0 if both bits are same. Bitwise XOR operator also offers a nice trick to swap two numbers without using temp variables. Here is a code example of using bitwise XOR operator in Java:

Test5:

int a = 2; //0010

int b = 4; //0100

System.out.println(" value of a XOR B in Java : " + (a^b) );

Output:

value of a XOR B in Java : 6



Bit Shift operator in Java- Example

Apart from bitwise operators, Java also provides bit shift operators, which can be used to shift bit from one position to another on both left and right side in a number. Java provides three bit shift operator signed left shift operator "<<", signed right shift operator ">>" and unsigned right shift operator ">>>". Left shift operator with sign, shifts bit into left side and fill the empty place with zero, while right shift operator with sign, shifts the bit on right side and fills the empty place with value of sign bit. For positive number it fills with zero and for negative numbers it fills with 1. On the other hand ">>>" right shift without sign operator will only shift the bit towards right without preserving sign of number. As per syntax of bitshift operator, left hand side of operand is the number whose bit needs to be shift and right hand side of operator is how many bits needs to shift. This will be much clear with following example of signed left shift, signed right shift and right shift without sign operators:


public class BitShiftTest {

public static void main(String args[]) {

int number = 8; //0000 1000

System.out.println("Original number : " + number);

//left shifting bytes with 1 position

number = number<<1; //should be 16 i.e. 0001 0000

//equivalent of multiplication of 2

System.out.println("value of number after left shift: " + number);

number = -8;

//right shifting bytes with sign 1 position

number = number>>1; //should be 16 i.e. 0001 0000

//equivalent of division of 2

System.out.println("value of number after right shift with sign: " + number);

number = -8;

//right shifting bytes without sign 1 position

number = number>>>1; //should be 16 i.e. 0001 0000

//equivalent of division of 2

System.out.println("value of number after right shift with sign: " + number);

}

}

Output:

Original number : 8

value of number after left shift: 16

value of number after right shift with sign: -4

value of number after right shift with sign: 2147483644


Important points to remember while using bit shift operators in Java

1. Smaller types like byte, short are promoted to int before applying bit shift operator in Java. This requires explicit casting on lower type of result.

2. If number of shift positions exceeds with number of bits in a variable, then remainder operator is used to calculate effective bit movement. For example int variables contains 32 bit, and if you shift bits to 33 times, then its equivalent of shifting bits 33%32 or just 1 time. e.g. 8 >> 33 is equal to 8 >> 1 and this is true for all bit shift operators.

3. Since bit shift operators can simulate divide by 2 and multiplied by 2 operation they can be used to implement fast multiplication and division but on the cost of readability as its difficult to comprehend code written using bit shift operators in Java.



The bitwise operators

Operator

Name

Example

Result

Description

a & b

and

3 & 5

1

1 if both bits are 1.

a | b

or

3 | 5

7

1 if either bit is 1.

a ^ b

xor

3 ^ 5

6

1 if both bits are different.

~a

not

~3

-4

Inverts the bits.

n << p

left shift

3 <<< 2

12

Shifts the bits of n left p positions. Zero bits are shifted into the low-order positions.

n >> p

right shift

5 >> 2

1

Shifts the bits of n right p positions. If n is a 2's complement signed number, the sign bit is shifted into the high-order positions.

n >>> p

right shift

-4 >>> 28

15

Shifts the bits of n right p positions. Zeros are shifted into the high-order positions.

 

Use: Shift left multiplies by 2; shift right divides by 2

On some older computers it was faster to use shift instead of multiply or divide.

y = x << 3;††††††† // Assigns 8*x to y.

y = (x << 2) + x;† // Assigns 5*x to y.

Use: Flipping between on and off with xor

Sometimes xor is used to flip between 1 and 0.

x = x ^ 1;††††† // Or the more cryptic x ^= 1;

In a loop that will change x alternately between 0 and 1.

 

Obscure use: Exchanging values with xor

Here's some weird code. It uses xor to exchange two values (x and y). This is translated to Java from an assembly code program, where there was no available storage for a temporary. Never use it; this is just a curiosity from the museum of bizarre code.

x = x ^ y;

y = x ^ y;

x = x ^ y;

 

1. Bitwise Logical Operators

Available bitwise logical operators are given below.

Operator

Meaning

&

Bitwise AND Operator

|

Bitwise OR Operator

^

Bitwise Exclusive OR Operator

~

Bitwise NOT operator

Table1: Bitwise Logical Operators.

Bitwise logical operators manipulate each bit as shown in the below table.

bit1

bit2

bit1 & bit2

bit1 | bit2

bit1 ^ bit2

~bit1

0

0

0

0

0

1

1

0

0

1

1

0

0

1

0

1

1

1

1

1

1

1

0

0

Table2: Bitwise Logical Operators behaviour.

 

Program for Bitwise Operators

 

 

 

public class BitwiseOperatorsDemo1

{

public static void main(String args[])

{

//Bitwise Logical Operators

System.out.println("********* Bitwise Logical Operators **************");

//Bitwise AND Operator

System.out.println("**** Bitwise AND Operator *******");

int value1 = 6;

int value2 = 5;

int result = value1&value2;

System.out.println("value1 : "+value1);

System.out.println("value2 : "+value2);

System.out.println("result : "+result);

//Bitwise OR Operator

System.out.println("**** Bitwise OR Operator *******");

value1 = 6;

value2 = 5;

result = value1|value2;

System.out.println("value1 : "+value1);

System.out.println("value2 : "+value2);

System.out.println("result : "+result);

//Bitwise Exclusive OR Operator

System.out.println("**** Bitwise Exclusive OR Operator *******");

value1 = 6;

value2 = 5;

result = value1^value2;

System.out.println("value1 : "+value1);

System.out.println("value2 : "+value2);

System.out.println("result : "+result);

//Bitwise NOT operator

System.out.println("**** Bitwise NOT operator *******");

value1 = 6;

result = ~value1;

System.out.println("value1 : "+value1);

System.out.println("result : "+result);

//Bitwise Shift Operators

System.out.println("********* Bitwise Shift Operators **************");

//Right Shift Operator

System.out.println("**** Right Shift Operator *******");

int value = 12;

int test = value >> 2;

System.out.println("value : "+value);

System.out.println("test : "+test);

value = -12;

test = value >> 2;

System.out.println("value : "+value);

System.out.println("test : "+test);

//Left Shift Operator

System.out.println("**** Left Shift Operator *******");

value = 12;

test = value << 2;

System.out.println("value : "+value);

System.out.println("test : "+test);

value = -12;

test = value << 2;

System.out.println("value : "+value);

System.out.println("test : "+test);

//Unsigned Right Shift Operator

System.out.println("**** Unsigned Right Shift Operator *******");

value = 12;

test = value >>> 2;

System.out.println("value : "+value);

System.out.println("test : "+test);

value = -12;

test = value >>> 2;

System.out.println("value : "+value);

System.out.println("test : "+test);

}

}

Output

 

The AND operator : (&)


The AND(&) logical operator gives one (1) in only case one case where the two inputs

Code:


x y x&y
-----------------------------
0 0 0
0 1 0
1 0 0
1 1 1


Example using & operator on bytes
java code

Test6

1

2

3

4

byte x = 50;

byte y = 51;

byte result = (byte) (x&y);

System.out.println("Result of x&y= : " + result );



The result equal = 50
which is in binary:

Code:

00110010
00110011
-------------
00110010

& operator on Integers:
java code

Test7

1

2

3

4

int xInt = 30;

int yInt = 31;

int result = (xInt&yInt);

System.out.println("Result of x&y (Integers)= : " + result );


The output is :

Code:

Result of x&y (Integers)= : 30

The OR operator : (|)


The OR operators gives one(1) if any of the two inputs equals one, zero otherwise.

Code:


x y x|y
-----------------------------
0 0 0
0 1 1
1 0 1
1 1 1


Example on |(OR) operator on bytes

java code

Test8

1

2

3

4

byte x = 50;

byte y = 51;

byte result = (byte) (x|y);

System.out.println("Result of x|y= : " + result );


The output is :

Code:

The result equal = 51

Code:

00110010
00110011
-------------
00110011
Example on |(OR) operator on integers
java code

Test9

1

2

3

4

int xInt = 30;

int zInt=33;

int result = (xInt|zInt);

System.out.println("Result of x|y (Integers)= : " + result );


The output is :

Code:

Result of x|y (Integers)= : 63


The XOR operator : (^)


The XOR(^) operator gives one(1) if the inputs are different, otherwise zero.

Code:


x y x^y
-----------------------------
0 0 0
0 1 1
1 0 1
1 1 0


Example on ^ operator on bytes

java code

Test10

1

2

3

4

byte x = 50;

byte y = 51;

byte result = (byte) (x^y);

System.out.println("Result of x^y= : " + result );



The result equal = 1

Code:

00110010
00110011
-------------
00000001

Example on ^ operator on Integers
java code

Test11

1

2

3

4

int xInt = 30;

int zInt=31;

int result = (xInt^zInt);

System.out.println("Result of x^y (Integers)= : " + result );


The output is :

Code:

Result of x^y (Integers)= : 1

The Inversion Operator: (~)


Invert each bit in the byte (one's complement of bits array).

Example :

Code:

~00110010 = 11001101

Invert operator on integer
java code

Test12

1

2

3

int xInt = 30;

int result = ~xInt;

System.out.println("Result of ~xInt(Integers)= : " + result );


The output is :

Code:

 

-----------

Bitwise AND Summary Table :

A

B

A & B

0

0

0

0

1

0

1

0

0

1

1

1

Live Example 1 : ANDing 42 and 15

class BitwiseAND{

† public static void main(String args[]){

 

† int num1 = 42;

† int num2 = 15;

 

† System.out.println("AND Result =" +(num1&num2));

 

† }

}

[468◊60]

Output :

AND Result = 10

Explanation of Code :

Num1 : 00101010†† 42

Num2 : 00001111†† 15

======================

AND† : 00001010†† 10

 

-----

Converting decimal to binary in Java Example

Java has many ways to change number system of particular number, you can convert any decimal number into either binary system, hexadecimal system or octal system by following the same procedure. here is code example of converting any decimal number into binary number in Java.


Test13

int number = 2;

//decimal to binary

String binaryString = Integer.toBinaryString(number);

System.out.println("decimal to binary: " + binaryString);

//decimal to octal

String octalString = Integer.toOctalString(number);

System.out.println("decimal to octal: " + octalString);

//decimal to hexadecimal

String hexString = Integer.toHexString(number);

System.out.println("decimal to hexadecimal: " + hexString);

//second way

binaryString = Integer.toString(number,2);

System.out.println("decimal to binary using Integer.toString: " + binaryString);

//decimal to octal

octalString = Integer.toString(number,8);

System.out.println("decimal to octal using Integer.toString: " + octalString);

//decimal to hexadecimal

hexString = Integer.toString(number,16);

System.out.println("decimal to hexadecimal using Integer.toString: " + hexString);


 

---------------------------------------------------

 

 

 

 

 

 

 

 

 

 

 

 

 

Programming logic -> Shift Right

 

Programming logic -> Shift Left

 

Sample Example :

 

 

-------------------------------------------------------------

 

How to Convert from Decimal to Binary

 

3

Continue to divide until you reach 0. Continue downwards, dividing each new quotient by two and writing the remainders to the right of each dividend. Stop when the quotient is 0.

 

Write out the new, binary number. Starting with the bottom remainder, read the sequence of remainders upwards to the top. For this example, you should have 10011100. This is the binary equivalent of the decimal number 156. Or, written with base subscripts: 15610 = 100111002

         This method can be modified to convert from decimal to any base. The divisor is 2 because the desired destination is base 2 (binary). If the desired destination is a different base, replace the 2 in the method with the desired base. For example, if the desired destination is base 9, replace the 2 with 9. The final result will then be in the desired base.

----------------

1.Write a Java Program to convert decimal to binary in java using Integer.toBinaryString(int num)

 

import java.util.Scanner;

 

public class ConvertDecimalToBinary {

†††† /** *www.instanceofjava.com */

†††† public static void main(String[] args) {

†††††††††† System.out.println("\nBinary representation of 1: ");

†††††††††† System.out.println(Integer.toBinaryString(1));

†††††††††† System.out.println("\nBinary representation of 4: ");

†††††††††† System.out.println(Integer.toBinaryString(4));

†††††††††† System.out.println("Binary representation of 10: ");

†††††††††† System.out.println(Integer.toBinaryString(10));

†††††††††† System.out.println("\nBinary representation of 12: ");

†††† †††† System.out.println(Integer.toBinaryString(12));

†††††††††† System.out.println("\nBinary representation of 120: ");

†††††††††† System.out.println(Integer.toBinaryString(120));

†††††††††† System.out.println("\nBinary representation of 500: ");

†††††††††† System.out.println(Integer.toBinaryString(500));

†††† }

}

2.Write a Java Program to convert decimal to binary in java

import java.util.Scanner;

import java.util.Stack;

 

import java.util.Scanner;

import java.util.Stack;

 

public class Test14 {

†††† /** *www.instanceofjava.com */

†††† public static void main(String[] args) {

†††††††††† Scanner in = new Scanner(System.in);

†††††††††† // Create Stack object

†††††††††† Stack<Integer> stack = new Stack<Integer>();

†††††††††† // Take User input from keyboard

†††††††††† System.out.println("Enter decimal number: ");

†††††††††† int num = in.nextInt();

†††††††††† while (num != 0) {

††††††††††††††† int d = num % 2;

††††††††††††††† stack.push(d);

††††††††††††††† num /= 2;

†††††††††† }

†††††††††† System.out.print("\nBinary representation is:");

†††††††††† while (!(stack.isEmpty())) {

††††††††††††††† System.out.print(stack.pop());

†††††††††† }

†††††††††† System.out.println();

†††† }

}

 

 

3.Write a Java Program to convert decimal to binary in java

public class Tset15 {

†††† /** *www.instanceofjava.com */

†††† public static void convertDeciamlToBinary(int num) {

†††††††††† int binary[] = new int[40];

†††††††††† int index = 0;

†††††††††† while (num > 0) {

††††††††††††††† binary[index++] = num % 2;

††††††††††††††† num = num / 2;

†††††††††† }

†††††††††† for (int i = index - 1; i >= 0; i--) {

††††††††††††††† System.out.print(binary[i]);

†††††††††† }

†††† }

 

†††† public static void main(String[] args) {

†††††††††† System.out.println("Binary representation of 1: ");

†††††††††† convertDeciamlToBinary(1);

†††††††††† System.out.println("\nBinary representation of 4: ");

†††††††††† convertDeciamlToBinary(4);

†††††††††† System.out.println("\nBinary representation of 10: ");

†††††††††† convertDeciamlToBinary(10);

†††††††††† System.out.println("\nBinary representation of 12: ");

†††††††††† convertDeciamlToBinary(12);

†††† }

}

-----------------------

Java program to convert decimal to binary

 

There are three following ways to convert Decimal number to binary number:

1) Using toBinaryString() method of Integer class.
2) Do conversion by writing your own logic without using any predefined methods.
3) Using Stack

Method 1: Using toBinaryString() method

class DecimalBinaryExample{

††††

††† public static void main(String a[]){

††† † System.out.println("Binary representation of 124: ");

††† † System.out.println(Integer.toBinaryString(124));

††††††† System.out.println("\nBinary representation of 45: ");

†††† †††System.out.println(Integer.toBinaryString(45));

††††††† System.out.println("\nBinary representation of 999: ");

††††††† System.out.println(Integer.toBinaryString(999));

††† }

}

Output:

Binary representation of 124:

1111100

 

Binary representation of 45:

101101

 

Binary representation of 999:

1111100111

Method 2: Without using predefined method

class DecimalBinaryExample{

† public void convertBinary(int num){

†††† int binary[] = new int[40];

†††† int index = 0;

†††† while(num > 0){

†††††† binary[index++] = num%2;

†††††† num = num/2;

†††† }

†††† for(int i = index-1;i >= 0;i--){

†††††† System.out.print(binary[i]);

†††† }

† }

† public static void main(String a[]){

†††† DecimalBinaryExample obj = new DecimalBinaryExample();

†††† System.out.println("Binary representation of 124: ");

†††† obj.convertBinary(124);

†††† System.out.println("\nBinary representation of 45: ");

†††† obj.convertBinary(45);

†††† System.out.println("\nBinary representation of 999: ");

†††† obj.convertBinary(999);

† }

}

Output:

Binary representation of 124:

1111100

Binary representation of 45:

101101

Binary representation of 999:

1111100111

Method 3: Decimal to Binary using Stack

import java.util.*;

class DecimalBinaryStack

{

† public static void main(String[] args)

† {

††† Scanner in = new Scanner(System.in);

††† // Create Stack object

††† Stack<Integer> stack = new Stack<Integer>();

††† // User input

††† System.out.println("Enter decimal number: ");

††† int num = in.nextInt();

††† while (num != 0)

††† {

††††† int d = num % 2;

††††† stack.push(d);

††††† num /= 2;

††† }

††† System.out.print("\nBinary representation is:");

††† while (!(stack.isEmpty() ))

††† {

††††† System.out.print(stack.pop());

††† }

††† System.out.println();

† }

}

Output:

Enter decimal number:

999

 

Binary representation is:1111100111