[go: up one dir, main page]

0% found this document useful (0 votes)
55 views35 pages

CH-2 Theory All and Program

The document discusses Java arithmetic operators and assignment operators with examples. It defines common arithmetic operators like addition, subtraction, multiplication, division, and modulus. It provides code examples to demonstrate how each operator works. It also defines common assignment operators like =, +=, -=, *=, /=, %= and provides examples of how they assign values to variables.

Uploaded by

Parth thakkare
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views35 pages

CH-2 Theory All and Program

The document discusses Java arithmetic operators and assignment operators with examples. It defines common arithmetic operators like addition, subtraction, multiplication, division, and modulus. It provides code examples to demonstrate how each operator works. It also defines common assignment operators like =, +=, -=, *=, /=, %= and provides examples of how they assign values to variables.

Uploaded by

Parth thakkare
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

COMPUTER (PRACTICAL WORK)

CLASS-IX: Java Arithmetic Operators with Examples

Operators constitute the basic building block to any programming language. Java too
provides many types of operators which can be used according to the need to
perform various calculation and functions be it logical, arithmetic, relational etc. They
are classified based on the functionality they provide. Here are a few types:

1. Arithmetic Operators (A) Arithmetic Operator:


2. Unary Operators operator description
3. Assignment Operator + addition
4. Relational Operators - subtraction
5. Logical Operators * multiplication
6. Ternary Operator / division
7. Bitwise Operators
% modulo
8. Shift Operators

Addition(+): This operator is a binary operator and is used to add two operands.

Data type Size in byte Range


class Addition { byte 1 -128 to +127
public static void main(String[] args) boolean 1 True or False
{ char 2 A-Z ,a-z, (0 to 9) digits, etc.
int num1 = 10, num2 = 20, sum = 0; short 2 -32768 to +32767
System.out.println("num1 = " + num1); int 4 -2147483648 to 2147483647
System.out.println("num2 = " + num2); long 8 -9223372036854775808
sum = num1 + num2; to 9223372036854775807
System.out.println("The sum = " + sum); float 4 -3.4 e38 to +3.4e18
} double 8 -1.7e308 to +1.7e308
}
Output:
num1 = 10
num2 = 20
The sum = 30

Subtraction(-): This operator is a binary operator and is used to subtract two operands.
class Subtraction {
public static void main(String[] args)
{
int num1 = 20, num2 = 10, sub = 0;
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
sub = num1 - num2;
System.out.println("Subtraction = " + sub);
}
} 1.8 Variable name in java OR Naming in java:
Output:  In variable name, use only character (A to Z, a to z) ,digit (0 to 9) and
num1 = 20 underscores ‘_’
num2 = 10  Variable name cannot include with space character.
Subtraction = 10  Variable name does no begin with digit.
 Variable name always start with characters.
 Upper case and lower case count as different variables.
 Keywords not allows as a variable name.
Multiplication(*): This operator is a binary operator and is used to multiply two operands.

class Multiplication {
public static void main(String[] args)
{
int num1 = 20, num2 = 10, mult = 0;
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
mult = num1 * num2;
System.out.println("Multiplication = " + mult);
}
}
Output:
num1 = 20
num2 = 10
Multiplication = 200

Division(/): This is a binary operator that is used to divide the first operand(dividend) by the
second operand(divisor) and give the quotient as result.
class Division {
public static void main(String[] args)
{
int num1 = 20, num2 = 10, div = 0;
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
div = num1 / num2;
System.out.println("Division = " + div);
}
}
Output:
num1 = 20
num2 = 10
Division = 2

Modulus(%): This is a binary operator that is used to return the remainder when the first
operand(dividend) is divided by the second operand(divisor).
class Modulus {
public static void main(String[] args)
{
int num1 = 5, num2 = 2, mod = 0;
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
mod = num1 % num2;
System.out.println("Remainder = " + mod);
}
}
Output: num1 = 5
num2 = 2
1.11 Keyword in java
Keywords are important part of java. Java language has number of keywords reserved. Let’s
we see it below table.
abstract long import transient
char throw protected native
catch private class null
boolean package throws const
default static byte new
finally break else case
do double float extends
implements this Final int
if volatile public instanceof
return interface short assert
try void continue const
for while goto
Switch synchronized super

class ArithmeticOp
{
public static void main(String[] args)
{
int a,b,add,sub,mul,div,mod,avg;
a=16;
b=3;
add=a+b;
sub=a-b;
mul=a*b;
div=a/b;
mod=a%b;
avg=(a+b)/2;
System.out.println("addition =" +add);
System.out.println("subtraction =" +sub);
System.out.println("multiplication =" +mul);
System.out.println("division =" +div);
System.out.println("modules =" +mod);
System.out.println("average =" +avg);
}
}
Output:
addition =19
subtraction =13
multiplication =48
division =5
modules =1
average =9
COMPUTER – CLASS-IX
Java Assignment Operator
These operators are used to assign values to a variable. The left side operand of the
assignment operator is a variable and the right side operand of the assignment
operator is a value.

1. “=”: This is the simplest assignment operator which is used to assign the value
on the right to the variable on the left. This is the basic definition of assignment
operator and how does it functions.

class Assignment {
public static void main(String[] args)
{
int num;
String name;
num = 10;
name = "CJCS";
System.out.println("num is assigned: " + num);
System.out.println("name is assigned: " + name);
}
}
Output:
num is assigned: 10
name is assigned: CJCS
2. “+=”: This operator is a compound of ‘+’ and ‘=’ operators. It operates by
adding the current value of the variable on left to the value on the right and then
assigning the result to the operand on the left.
class Assignment {
public static void main(String[] args)
{
int num1 = 10, num2 = 20; " + num1);
System.out.println("num2 = " + num2);
num1 += num2;
System.out.println("num1 = " + num1);
}
}
Output:
num1 = 10
num2 = 20
num1 = 30
3. “-=”: This operator is a compound of ‘-‘ and ‘=’ operators. It operates by
subtracting the value of the variable on right from the current value of the variable on
the left and then assigning the result to the operand on the left.

class Assignment {
public static void main(String[] args)
{
int num1 = 10, num2 = 20;
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
num1 -= num2;
System.out.println("num1 = " + num1);
}
}

Output:
num1 = 10
num2 = 20
num1 = -10
4. “*=”: This operator is a compound of ‘*’ and ‘=’ operators. It operates by
multiplying the current value of the variable on left to the value on the right and then
assigning the result to the operand on the left.
class Assignment {
public static void main(String[] args)
{
int num1 = 10, num2 = 20;
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
num1 *= num2;
System.out.println("num1 = " + num1);
}
}
Output:
num1 = 10
num2 = 20
num1 = 200

5. “/=”: This operator is a compound of ‘/’ and ‘=’ operators. It operates by


dividing the current value of the variable on left by the value on the right and then
assigning the quotient to the operand on the left.
class Assignment {
public static void main(String[] args)
{
int num1 = 20, num2 = 10;
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
num1 /= num2;
System.out.println("num1 = " + num1);
}
}
Output:
num1 = 20
num2 = 10
num1 = 2

6. “%=”: This operator is a compound of ‘%’ and ‘=’ operators. It operates by


dividing the current value of the variable on left by the value on the right and then
assigning the remainder to the operand on the left.
class Assignment {
public static void main(String[] args)
{

int num1 = 5, num2 = 3;

System.out.println("num1 = " + num1);


System.out.println("num2 = " + num2);
num1 %= num2;
System.out.println("num1 = " + num1);
}
}
Output:
num1 = 5
num2 = 3
num1 = 2
//demo of assignment operator
package ABC;
public class helloprogram
{
public static void main(String[] args)
{
int a, b; // a=?, b=?
a = 10; // a=10, b=?
b = 4; // a=10, b=4
a = b; // a=4, b=4
b = 7; // a=4, b=7
System.out.println("Value of a=" +a); //print value of a
System.out.println("Value of b=" +b); // print value of b
}
}
Output:
Value of a=4
Value of b=7
COMPUTER – CLASS-IX
Relational Operators with Examples
1. ‘Equal to’ operator (==): This operator is used to check whether the two given operands are equal
or not. The operator returns true if the operand at the left-hand side is equal to the right-hand side,
else false.

class Relational {
public static void main(String[] args)
{
int var1 = 5, var2 = 10, var3 = 5;
System.out.println("Var1 = " + var1);
System.out.println("Var2 = " + var2);
System.out.println("Var3 = " + var3);
System.out.println("var1 == var2: "+ (var1 == var2));
System.out.println("var1 == var3: "+ (var1 == var3));
}
}
Output:
Var1 = 5
Var2 = 10
Var3 = 5
var1 == var2: false
var1 == var3: true

2. ‘Not equal to’ Operator(!=): This operator is used to check whether the two given operands are
equal or not. It functions opposite to that of the equal-to operator. It returns true if the operand at
the left-hand side is not equal to the right-hand side, else false.

class Relational {
public static void main(String[] args)
{
int var1 = 5, var2 = 10, var3 = 5;

System.out.println("Var1 = " + var1);


System.out.println("Var2 = " + var2);
System.out.println("Var3 = " + var3);

System.out.println("var1 == var2: "+ (var1 != var2));

System.out.println("var1 == var3: "+ (var1 != var3));


}
}

Output:
Var1 = 5
Var2 = 10
Var3 = 5
var1 == var2: true
var1 == var3: false
3. ‘Greater than’ operator(>): This checks whether the first operand is greater than the second
operand or not. The operator returns true when the operand at the left-hand side is greater than the
right-hand side.

class Relational {
public static void main(String[] args)
{
int var1 = 30, var2 = 20, var3 = 5;

System.out.println("Var1 = " + var1);


System.out.println("Var2 = " + var2);
System.out.println("Var3 = " + var3);

System.out.println("var1 > var2: "+ (var1 > var2));

System.out.println("var3 > var1: "+ (var3 >= var1));


}
}

Output:
Var1 = 30
Var2 = 20
Var3 = 5
var1 > var2: true
var3 > var1: false

4. ‘Less than’ Operator(<): This checks whether the first operand is less than the second operand or
not. The operator returns true when the operand at the left-hand side is less than the right-hand
side. It functions opposite to that of the greater than operator.

class Relational {
public static void main(String[] args)
{
int var1 = 10, var2 = 20, var3 = 5;

System.out.println("Var1 = " + var1);


System.out.println("Var2 = " + var2);
System.out.println("Var3 = " + var3);

System.out.println("var1 < var2: "+ (var1 < var2));

System.out.println("var2 < var3: "+ (var2 < var3));


}
}

Output:
Var1 = 10
Var2 = 20
Var3 = 5
var1 < var2: true
var2 < var3: false
5. 'Greater than or equal to' operator(>=): This checks whether the first operand is greater than or
equal to the second operand or not. The operator returns true when the operand at the left-hand
side is greater than or equal to the right-hand side.

class Relational {
public static void main(String[] args)
{
int var1 = 20, var2 = 20, var3 = 10;

System.out.println("Var1 = " + var1);


System.out.println("Var2 = " + var2);
System.out.println("Var3 = " + var3);

System.out.println("var1 >= var2: "+ (var1 >= var2));

System.out.println("var2 >= var3: "+ (var3 >= var1));


}
}

Output:
Var1 = 20
Var2 = 20
Var3 = 10
var1 >= var2: true
var2 >= var3: false

6. 'Less than or equal to' Operator(<): This checks whether the first operand is less than or equal to
the second operand or not. The operator returns true when the operand at the left-hand side is less
than or equal to the right-hand side.

class Relational {
public static void main(String[] args)
{
int var1 = 10, var2 = 10, var3 = 9;

System.out.println("Var1 = " + var1);


System.out.println("Var2 = " + var2);
System.out.println("Var3 = " + var3);

System.out.println("var1 <= var2: "+ (var1 <= var2));

System.out.println("var2 <= var3: "+ (var2 <= var3));


}
}
Output:
Var1 = 10
Var2 = 10
Var3 = 9
var1 <= var2: true
var2 <= var3: false
COMPUTER CLASS-IX
Logical Operators

Write into activity copy


1. ‘Logical AND’ Operator(&&): This operator returns true when both the conditions under
consideration are satisfied or are true. If even one of the two yields false, the operator results false.
For example, cond1 && cond2 returns true when both cond1 and cond2 are true (i.e. non-zero).

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

System.out.println("Var1 = " + a);


System.out.println("Var2 = " + b);
System.out.println("Var3 = " + c);

if ((a < b) && (b == c)) {


d = a + b + c;
System.out.println("The sum is: " + d);
}
else
System.out.println("False conditions");
}
}

Output:
Var1 = 10
Var2 = 20
Var3 = 20
The sum is: 50

2. 'Logical OR' Operator(||): This operator returns true when one of the two conditions under
consideration are satisfied or are true. If even one of the two yields true, the operator results true.
To make the result false, both the constraints need to return false.

class Logical {
public static void main(String[] args)
{
int a = 10, b = 1, c = 10, d = 30;
System.out.println("Var1 = " + a);
System.out.println("Var2 = " + b);
System.out.println("Var3 = " + c);
System.out.println("Var4 = " + d);
if (a > b || c == d)
System.out.println("One or both"+ " the conditions are true");
else
System.out.println("Both the"+ " conditions are false");
}
}
Output:
Var1 = 10
Var2 = 1
Var3 = 10
Var4 = 30
One or both the conditions are true

3. 'Logical NOT' Operator(!): Unlike the previous two, this is a unary operator and returns true when
the condition under consideration is not satisfied or is a false condition. Basically, if the condition is
false, the operation returns true and when the condition is true, the operation returns false.

class Logical {
public static void main(String[] args)
{
int a = 10, b = 1;

System.out.println("Var1 = " + a);


System.out.println("Var2 = " + b);

System.out.println("!(a < b) = " + !(a < b));


System.out.println("!(a > b) = " + !(a > b));
}
}
Output:
Var1 = 10
Var2 = 1
!(a < b) = true
!(a > b) = false

################################################################
Bitwise operators in Java
Bitwise OR (|) –
This operator is 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 gives 0.
For example,
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)

Bitwise OR Operation of 5 and 7


0101
| 0111
________
0111 = 7 (In decimal)

Bitwise AND (&) –


This operator is 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 gives 0.
For example,
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)

Bitwise AND Operation of 5 and 7


0101
& 0111
________
0101 = 5 (In decimal)

Bitwise XOR (^) –


This operator is 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 gives 0.
For example,
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)

Bitwise XOR Operation of 5 and 7


0101
^ 0111
________
0010 = 2 (In decimal)

Bitwise Complement (~) –


This operator is unary operator, denoted by ‘~’. It returns the one’s compliment representation of
the input value,
i.e, with all bits inversed, means it makes every 0 to 1, and every 1 to 0.
For example,
a = 5 = 0101 (In Binary)

Bitwise Compliment Operation of 5

~ 0101
________
1010 = 10 (In decimal)
Note – Compiler will give 2’s complement of that number, i.e., 2’s compliment of 10 will be -6.
public class operators {
public static void main(String[] args)
{
Examples
int a = 5;
int b = 7;
System.out.println("a&b = " + (a & b));
System.out.println("a|b = " + (a | b));
System.out.println("a^b = " + (a ^ b));
System.out.println("~a = " + ~a);
a &= b;
System.out.println("a= " + a);
}
}
Output :
a&b = 5
a|b = 7
a^b = 2
~a = -6
a= 5
Chapter 1
Bitwise operators modify variables considering the bit patterns that represent the values they store.
operator description Unary complement (bit
~
& Bitwise AND inversion)
| Bitwise inclusive OR << Shift bits left
^ Bitwise exclusive OR(XOR) >> Shift bits right

Example 1: bitwise AND


class DemobitwiseAnd Description:
{ a=10 and b=7 first convert into binary
public static void main(String[] args) value.
{ 00001010 this is 10 value binary
int a,b,c; 00000111 this is 5 value binary
a=10;
b=7; Now And (&&) operator apply to
c=a & b; those above binary value. And we will
System.out.println("ans is =" +c); get value of c variable.
00001010
} 00000111
} AND 00000010 this value is
convert into decimal
answer is C=2
Output:
ans is =2

Example 2: bitwise OR
class Demobitwiseor Description:
{ a=10 and b=7 first convert into binary
public static void main(String[] args) value.
{ 00001010 this is 10 value binary
int a,b,c; 00000111 this is 5 value binary
a=10;
b=7; Now OR operator apply to those above
c=a | b; binary value. And we will get value of
System.out.println("ans is =" +c); c variable.
} 00001010
} 00000111
OR 00001111 this value is convert
into decimal
answer is C=15
Output:
ans is =15

Example 3: bitwise XOR


class DemobitwiseXor Here we have declared a, b, c variable.
{ Then assign value 10 into var a, and
public static void main(String[] args) assign value 7 into variable b.
{ Now variables a and b convert into
int a,b,c; binary. See below.
a=10;
b=7; A 00001010

__________________________________________________________________________________
Chapter 1

c=a ^ b; B 00000111
System.out.println("ans is =" +c); XOR (c) 00001101
} So after perform XOR operation, the
} result is assign in to variable C, so here
c variables value becomes 14.
C=13.
Output:
ans is =13

Example 4: bitwise shift left


class demobitwiseshiftleft a =20; we have first convert into binary
{ value.
public static void main(String[] args) 00010100.
{ Now each bit shift one bit left side.
int a,b; 00101000.
a=20; After we will get bit position like this.
b=a<<1; Now convert above bit patent into
System.out.println("ans is =" +b); } decimal and get result b=40;
}
Output:
ans is = 40

Example 5: bitwise shift right


class BitwiseShiftright a =20; we have first convert into binary
{ value.
public static void main(String[] args) 00010100.
{ Now each bit shift one bit right side.
int a,b; After we will get bit position like this.
a=20; 00001010
b=a>>1; Now convert above bit patent into
System.out.println("ans is =" +b); decimal and get result b=10;
}
}
Output:
ans is =10

(F) Conditional Operator Or Ternary Operator:


The conditional operator evaluates an expression, returning one value if that expression
evaluates to true, and a different one if the expression evaluates as false
Syntax:
condition? result1: result2;
Example 1:
//demo of conditional operator
class ConditinalOP
{
public static void main(String[] args)
{
int a,b,c;
a=10;
b=7;

__________________________________________________________________________________
Chapter 1

c = (a>b)? a: b;
System.out.println("maximum number is=" +c);
}
}
Output:
maximum number is=10

(G) Increment or Decrement Operator:

The increase operator (++) and the decrease operator (--) increase or reduce by one
the value stored in a variable. They are equivalent to +=1 and to -=1, respectively.

Example 1 Example 2
x = 3; x = 3;
y = ++x; y = x++;
// x contains 4, y contains 4 // x contains 4, y contains 3

Example 1:
// demo of prefix-increment and postfix- increment operator
class helloprogram
{
public static void main(String[] args)
{
int a,b,c;
a=10; //a=10, b=?, c=?
a++; //a=11, b=?,c=?
System.out.println("value of a="+a);
b=a++; //a=12, b=11,c=?
c=++a; //a=13, b=11,c=13?
System.out.println("value of a="+a); //a=13 print
System.out.println("value of b="+b); //b=11 print
System.out.println("value of c="+c); //c= 13 print
}
}
Output:
value of a=11
value of a=13
value of b=11
value of c=13

Example 2:
// demo of prefix-decrement and postfix- decrement operator
class helloprogram
{
public static void main(String[] args)
{
int a,b,c;
a=10; //a=10, b=? , c=?
a--; //a=9, b=? , c=?

__________________________________________________________________________________
Chapter 1

System.out.println("value of a="+a);
b=a--; //a=8, b=9, c=?
c=--a; //a=7, b=9, c=7?
System.out.println("value of a="+a); //a=7 print
System.out.println("value of b="+b); //b=9 print
System.out.println("value of c="+c); //c=7 print
}
}
Output:
value of a=9
value of a=7
value of b=9
value of c=7

__________________________________________________________________________________
COMPUTER – CLASS-IX
PRACTICE PROGRAMS (DO PRACTICE INTO ROUGH COPY)

1. Arithmetic operators are: +, -, *, /, %

public class ArithmeticOperatorDemo {


public static void main(String args[]) {
int num1 = 100;
int num2 = 20;

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


System.out.println("num1 - num2: " + (num1 - num2) );
System.out.println("num1 * num2: " + (num1 * num2) );
System.out.println("num1 / num2: " + (num1 / num2) );
System.out.println("num1 % num2: " + (num1 % num2) );
}
}

Output:
num1 + num2: 120
num1 - num2: 80
num1 * num2: 2000
num1 / num2: 5
num1 % num2: 0

2. Assignments operators in java are: =, +=, -=, *=, /=, %=


public class AssignmentOperatorDemo {
public static void main(String args[]) {
int num1 = 10;
int num2 = 20;

num2 = num1;
System.out.println("= Output: "+num2);

num2 += num1;
System.out.println("+= Output: "+num2);
num2 -= num1;
System.out.println("-= Output: "+num2);

num2 *= num1;
System.out.println("*= Output: "+num2);

num2 /= num1;
System.out.println("/= Output: "+num2);

num2 %= num1;
System.out.println("%= Output: "+num2);
}
}
Output:
= Output: 10
+= Output: 20
-= Output: 10
*= Output: 100
/= Output: 10
%= Output: 0

3. Auto-increment and Auto-decrement Operators ++ and --


num++ is equivalent to num=num+1;
num–- is equivalent to num=num-1;
Example of Auto-increment and Auto-decrement Operators
public class AutoOperatorDemo {
public static void main(String args[]){
int num1=100;
int num2=200;
num1++;
num2--;
System.out.println("num1++ is: "+num1);
System.out.println("num2-- is: "+num2);
}
}
Output:
num1++ is: 101
num2-- is: 199
4. Logical operators in java are: &&, ||, !

public class LogicalOperatorDemo {


public static void main(String args[]) {
boolean b1 = true;
boolean b2 = false;

System.out.println("b1 && b2: " + (b1&&b2));


System.out.println("b1 || b2: " + (b1||b2));
System.out.println("!(b1 && b2): " + !(b1&&b2));
}
}
Output:
b1 && b2: false
b1 || b2: true
!(b1 && b2): true

5) Comparison(Relational) operators ==, !=, >, <, >=, <=


public class RelationalOperatorDemo {
public static void main(String args[]) {
int num1 = 10;
int num2 = 50;
if (num1==num2) {
System.out.println("num1 and num2 are equal");
}
else{
System.out.println("num1 and num2 are not equal");
}

if( num1 != num2 ){


System.out.println("num1 and num2 are not equal");
}
else{
System.out.println("num1 and num2 are equal");
}

if( num1 > num2 ){


System.out.println("num1 is greater than num2");
}
else{
System.out.println("num1 is not greater than num2");
}

if( num1 >= num2 ){


System.out.println("num1 is greater than or equal to num2");
}
else{
System.out.println("num1 is less than num2");
}

if( num1 < num2 ){


System.out.println("num1 is less than num2");
}
else{
System.out.println("num1 is not less than num2");
}

if( num1 <= num2){


System.out.println("num1 is less than or equal to num2");
}
else{
System.out.println("num1 is greater than num2");
}
}
}

Output:
num1 and num2 are not equal
num1 and num2 are not equal
num1 is not greater than num2
num1 is less than num2
num1 is less than num2
num1 is less than or equal to num2

6) Bitwise Operators There are six bitwise Operators: &, |, ^, ~, <<, >>
Example of Bitwise Operators
public class BitwiseOperatorDemo {
public static void main(String args[]) {
int num1 = 11; /* 11 = 00001011 */
int num2 = 22; /* 22 = 00010110 */
int result = 0;

result = num1 & num2;


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

result = num1 | num2;


System.out.println("num1 | num2: "+result);

result = num1 ^ num2;


System.out.println("num1 ^ num2: "+result);

result = ~num1;
System.out.println("~num1: "+result);

result = num1 << 2;


System.out.println("num1 << 2: "+result); result = num1 >> 2;
System.out.println("num1 >> 2: "+result);
}
}
Output:
num1 & num2: 2
num1 | num2: 31
num1 ^ num2: 29
~num1: -12
num1 << 2: 44 num1 >> 2: 2

7) Ternary Operator
variable num1 = (expression) ? value if true : value if false

public class TernaryOperatorDemo {

public static void main(String args[]) {


int num1, num2;
num1 = 25;

num2 = (num1 == 10) ? 100: 200;


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

num2 = (num1 == 25) ? 100: 200;


System.out.println( "num2: "+num2);
}
}
Output:
num2: 200
num2: 100
COMPUTER CLASS-IX
JAVA PROGRAMS
Note: Write down into activity copy.

1. Java Program To Calculate Area Of Circle

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

Scanner s= new Scanner(System.in);

System.out.println("Enter the radius:");


double r= s.nextDouble();
double area=(22*r*r)/7 ;
System.out.println("Area of Circle is: " + area);
}
}

2. Java Program To Calculate Area Of Triangle


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

Scanner s= new Scanner(System.in);

System.out.println("Enter the width of the Triangle:");


double b= s.nextDouble();

System.out.println("Enter the height of the Triangle:");


double h= s.nextDouble();

//Area = (width*height)/2
double area=(b*h)/2;
System.out.println("Area of Triangle is: " + area);
}
}

3. Java Program To Find Area Of Rectangle


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

Scanner s= new Scanner(System.in);

System.out.println("Enter the length:");


double l= s.nextDouble();
System.out.println("Enter the breadth:");
double b= s.nextDouble();

double area=l*b;
System.out.println("Area of Rectangle is: " + area);
}
}

4. Java Program To Find Area Of Isosceles Triangle.


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

Scanner s= new Scanner(System.in);

System.out.println("Enter the length of same sided");

double a= s.nextDouble();

System.out.println("Enter the side2 of the Triangle");

double b= s.nextDouble();

double area=(b/4)*Math.sqrt((4*a*a)-(b*b));

System.out.println("Area of Isosceles Triangle is: " + area);


}
}

5. Java Program To Find Area of Parallelogram


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

Scanner s= new Scanner(System.in);

System.out.println("Enter the height:");


double d1= s.nextDouble();
System.out.println("Enter the breadth:");
double d2= s.nextDouble()

double area=(d1*d2) ;
System.out.println("Area of Parallelogram is: " + area);
}
}

6. Java Program To Calculate Area Of Rhombus


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

Scanner s= new Scanner(System.in);

System.out.println("Enter the diagonal 1:");


double d1= s.nextDouble();
System.out.println("Enter the diagonal 2:");
double d2= s.nextDouble();

double area=(d1*d2)/2;
System.out.println("Area of Rhombus is: " + area);
}
}
What is operator precedence?
The operator precedence represents how two expressions are bind together. In an
expression, it determines the grouping of operators with operands and decides how an
expression will evaluate.

While solving an expression two things must be kept in mind the first is a precedence and
the second is associativity.

Precedence
Precedence is the priority for grouping different types of operators with their operands.
It is meaningful only if an expression has more than one operator with higher or lower
precedence. The operators having higher precedence are evaluated first. If we want to
evaluate lower precedence operators first, we must group operands by using parentheses
and then evaluate.

Associativity
We must follow associativity if an expression has more than two operators of the same
precedence. In such a case, an expression can be solved either left-to-right or right-to-
left, accordingly.

Java Operator Precedence Table


The following table describes the precedence and associativity of operators used in Java.
Precedence Operator Type Associativity

15 () Parentheses Left to Right


[] Array subscript
· Member selection

14 ++ Unary post-increment Right to left


-- Unary post-decrement

13 ++ Unary pre-increment Right to left


-- Unary pre-decrement
+ Unary plus
- Unary minus
! Unary logical negation
~ Unary bitwise complement
(type) Unary type cast

12 * Multiplication Left to right


/ Division
% Modulus

11 + Addition Left to right


- Subtraction

10 << Bitwise left shift Left to right


>> Bitwise right shift with sign extension
>>> Bitwise right shift with zero extension

9 < Relational less than Left to right


<= Relational less than or equal
> Relational greater than
>= Relational greater than or equal
instanceof Type comparison (objects only)

8 == Relational is equal to Left to right


!= Relational is not equal to

7 & Bitwise AND Left to right

6 ^ Bitwise exclusive OR Left to right


5 | Bitwise inclusive OR Left to right

4 && Logical AND Left to right

3 || Logical OR Left to right

2 ?: Ternary conditional Right to left

1 = Assignment Right to left


+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment

0 , Comma Left to right

Note: Larger the number higher the precedence.

Java Operator Precedence Example


Let's understand the operator precedence through an example. Consider the following
expression and guess the answer.

1. 1 + 5 * 3

You might be thinking that the answer would be 18 but not so. Because the multiplication
(*) operator has higher precedence than the addition (+) operator. Hence, the expression
first evaluates 5*3 and then evaluates the remaining expression i.e. 1+15. Therefore, the
answer will be 16.

Let's see another example. Consider the following expression.

1. x + y * z / k

In the above expression, * and / operations are performed before + because of


precedence. y is multiplied by z before it is divided by k because of associativity.
The Scanner class is used to get user input, and it is found INPUT:
in the java.util package. Enter name
hds
MethodDescription Enter Male/Femalemale
nextBoolean() Reads a boolean value from the user Enter Roll no
nextByte() Reads a byte value from the user 23
nextDouble() Reads a double value from the user Enter mobile No887755447
nextFloat() Reads a float value from the user Enter HSC percentage23.34
nextInt() Reads a int value from the user Over 18? input true/false
nextLine() Reads a String value from the user true
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user
OUTPUT:
Name: hds
// ELECTION program to read data of using Scanner class.
Gender: m
import java.util.*;
Roll No: 23
public class Scanner1{
Mobile Number: 886674927
public static void main(String[] args) {
HSC Percent: 23.34
Scanner sc = new Scanner(System.in);
You Can Vote
// String input
System.out.println("Enter name");
String name = sc.nextLine(); Note: If you enter wrong input (e.g. text in a numerical
// Character input input), you will get an exception/error message (like
System.out.println("Enter Male/Female"); "InputMismatchException").
char gender = sc.next().charAt(0);
// Numerical data input
// byte, short and float can be read also
System.out.println("Enter Roll no");
int roll = sc.nextInt();
System.out.println("Enter mobile No");
long mobileNo = sc.nextLong();
System.out.println("Enter HSC percentage");
double percent = sc.nextDouble();
// Boolean data Input
System.out.println("Over 18? input true/false");
boolean bn=sc.nextBoolean();
// Print values to check if the input was correctly obtained

System.out.println("Name: "+name);
System.out.println("Gender: "+gender);
System.out.println("Roll No: "+roll);
System.out.println("Mobile Number: "+mobileNo);
System.out.println("HSC Percent: "+percent);
if(bn==true) {
System.out.println("You Can Vote");
}
else if(bn==false) {
System.out.println("You Can't Vote");
}
}
}
Basic Math methods

Method Description

Math.abs() It will return the Absolute value of the given value.

Math.max() It returns the Largest of two values.

Math.min() It is used to return the Smallest of two values.

Math.sqrt() It is used to return the square root of a number.

Math.cbrt() It is used to return the cube root of a number.

Math.pow() It returns the value of first argument raised to the power to second argument.

Math.ceil() It is used to find the smallest integer value that is greater than or equal to the argument or
mathematical integer.

Math.floor() It is used to find the largest integer value which is less than or equal to the argument and is equal
to the mathematical integer of a double value.

Math.PI Math.PI is a static final double constant in Java, equivalent to in π Mathematics.

Provided by java.lang.Math class, Math.PI constant is used to carry out multiple mathematical and
scientific calculations like finding the area & circumference of a circle or the surface area and volume
of a sphere.

Math.E The Math.E property represents Euler's number, the base of natural logarithms, e, which is
approximately 2.718.

𝙼𝚊𝚝𝚑.𝙴 = e ≈ 2.718

Example-1

public class MathLibraryExample {

public static void main(String[] args) {

int i = 7;
int j = -9;

double x = 72.3;

double y = 0.34;

System.out.println("i is " + i);

System.out.println("j is " + j);

System.out.println("x is " + x);

System.out.println("y is " + y);

// The absolute value of a number is equal to the number if the number is positive or zero and equal
to the negative of the number if the number is negative.

System.out.println("|" + i + "| is " + Math.abs(i));

System.out.println("|" + j + "| is " + Math.abs(j));

System.out.println("|" + x + "| is " + Math.abs(x));

System.out.println("|" + y + "| is " + Math.abs(y));

// The "ceiling" of a number is the smallest integer greater than or equal to the number. Every integer
is its own //ceiling.

System.out.println("The ceiling of " + i + " is " + Math.ceil(i));

System.out.println("The ceiling of " + j + " is " + Math.ceil(j));

System.out.println("The ceiling of " + x + " is " + Math.ceil(x));

System.out.println("The ceiling of " + y + " is " + Math.ceil(y));

// The "floor" of a number is the largest integer less than or equal to the number.

// Every integer is its own floor.

System.out.println("The floor of " + i + " is " + Math.floor(i));

System.out.println("The floor of " + j + " is " + Math.floor(j));

System.out.println("The floor of " + x + " is " + Math.floor(x));


System.out.println("The floor of " + y + " is " + Math.floor(y));

// Comparison operators

// min() returns the smaller of the two arguments you pass it

System.out.println("min(" + i + "," + j + ") is " + Math.min(i,j));

System.out.println("min(" + x + "," + y + ") is " + Math.min(x,y));

System.out.println("min(" + i + "," + x + ") is " + Math.min(i,x));

System.out.println("min(" + y + "," + j + ") is " + Math.min(y,j));

// There's a corresponding max() method

// that returns the larger of two numbers

System.out.println("max(" + i + "," + j + ") is " + Math.max(i,j));

System.out.println("max(" + x + "," + y + ") is " + Math.max(x,y));

System.out.println("max(" + i + "," + x + ") is " + Math.max(i,x));

System.out.println("max(" + y + "," + j + ") is " + Math.max(y,j));

// The Math library defines a couple of useful constants:

System.out.println("Pi is " + Math.PI);

System.out.println("e is " + Math.E);

// pow(x, y) returns the x raised

// to the yth power.

System.out.println("pow(2.0, 2.0) is " + Math.pow(2.0,2.0));

System.out.println("pow(10.0, 3.5) is " + Math.pow(10.0,3.5));

System.out.println("pow(8, -1) is " + Math.pow(8,-1));

// sqrt(x) returns the square root of x.

for (i=0; i < 10; i++) {


System.out.println(

"The square root of " + i + " is " + Math.sqrt(i));

// Finally there's one Random method

// that returns a pseudo-random number

// between 0.0 and 1.0;

System.out.println("Here's one random number: " + Math.random());

System.out.println("Here's another random number: " + Math.random());

// Use of cbrt() method

double cbrtval = Math.cbrt(216);

System.out.println("cube root : " + cbrtval);

Output:

You might also like