Java Arithmetic Operators.docx

15
Java Arithmetic Operators We can use arithmetic operators to perform calculations with values in programs. Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. A value used on either side of an operator is called an operand. For example, in below statement the expression 47 + 3, the numbers 47 and 3 are operands. The arithmetic operators are examples of binary operators because they require two operands. The operands of the arithmetic operators must be of a numeric type. You cannot use them on boolean types, but you can use them on char types, since the char type in Java is, essentially, a subset of int. int a = 47+3; Operat or Use Description Example + x + y Adds x and y float num = 23.4 + 1.6; // num=25 - x - y Subtracts y from x long n = 12.456 – 2.456; //n=10 -x Arithmetically negates x int i = 10; -i; // i = -10 * x * y Multiplies x by y int m = 10*2; // m=20 / x / y Divides x by y float div = 20/100 ; // div = 0.2 % x % y Computes the remainder of dividing x by y int rm = 20/3; // rm = 2 In Java, you need to be aware of the type of the result of a binary (two-argument) arithmetic operator. If either operand is of type double, the other is converted to double.

Transcript of Java Arithmetic Operators.docx

Page 1: Java Arithmetic Operators.docx

Java Arithmetic Operators

We can use arithmetic operators to perform calculations with values in programs. Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. A value used on either side of an operator is called an operand. For example, in below statement the expression 47 + 3, the numbers 47 and 3 are operands. The arithmetic operators are examples of binary operators because they require two operands. The operands of the arithmetic operators must be of a numeric type. You cannot use them on boolean types, but you can use them on char types, since the char type in Java is, essentially, a subset of int.

int a = 47+3;Operator Use Description Example

+ x + y Adds x and y float num = 23.4 + 1.6; // num=25

-x - y Subtracts y from x long n = 12.456 – 2.456; //n=10

-x Arithmetically negates x int i = 10; -i; // i = -10

* x * y Multiplies x by y int m = 10*2; // m=20

/ x / y Divides x by y float div = 20/100 ; // div = 0.2

% x % y Computes the remainder of dividing x by y int rm = 20/3; // rm = 2

In Java, you need to be aware of the type of the result of a binary (two-argument) arithmetic operator.

If either operand is of type double, the other is converted to double. Otherwise, if either operand is of type float, the other is converted to float. Otherwise, if either operand is of type long, the other is converted to long. Otherwise, both operands are converted to type int.

For unary (single-argument) arithmetic operators:

If the operand is of type byte, short, or char then the result is a value of type int. Otherwise, a unary numeric operand remains as is and is not converted.

The basic arithmetic operations—addition, subtraction, multiplication, and division— all behave as you would expect for all numeric types. The minus operator also has a unary form that negates its single operand. Remember that when the division operator is applied to an integer type, there will be no fractional component attached to the result.

The following simple program demonstrates the arithmetic operators. It also illustrates the difference between floating-point division and integer division.

Page 2: Java Arithmetic Operators.docx

Java Code - See more at: http://www.w3resource.com/java-tutorial/java-arithmetic-operators.php#sthash.9mnRRDXP.dpuf

package operatorsdemo;      public class ArithmeticOperatorDemo {       // Demonstrate the basic arithmetic operators.           public static void main(String args[]) {           // arithmetic using integers           System.out.println("Integer Arithmetic");           int i = 1 + 1;           int n = i * 3;           int m = n / 4;           int p = m - i;           int q = -p;           System.out.println("i = " + i);           System.out.println("n = " + n);           System.out.println("m = " + m);           System.out.println("p = " + p);           System.out.println("q = " + q);           // arithmetic using doubles           System.out.println("\nFloating Point Arithmetic");           double a = 1 + 1;           double b = a * 3;           double c = b / 4;           double d = c - a;           double e = -d;           System.out.println("a = " + a);           System.out.println("b = " + b);           System.out.println("c = " + c);           System.out.println("d = " + d);           System.out.println("e = " + e);       }   }   - See more at: http://www.w3resource.com/java-tutorial/java-arithmetic-operators.php#sthash.9mnRRDXP.dpuf

Arithmetic Operators Example

1. /*2.         Arithmetic Operators Example3.         This example shows how to use Java Arithmetic operators like + (addition),4.         - (subtraction), * (multiplication) and / (division). 5. */6.  

Page 3: Java Arithmetic Operators.docx

7. public class ArithmeticOperatorsExample {8.  9.         public static void main(String[] args) {10.                 11.                 System.out.println("Arithmetic operators example :");12.                 13.                 int i = 50 + 20;14.                 int j = i - 10;15.                 int k = j * 2;16.                 double l = k / 6;17.                 18.                 System.out.println("i = " + i);19.                 System.out.println("j = " + j);20.                 System.out.println("k = " + k);21.                 System.out.println("l = " + l);22.         }23. }24.  25. /*26. Output would be27. Arithmetic operators example :28. i = 7029. j = 6030. k = 12031. l = 20.032. */

Increment and decrement operator package operatorsdemo;      public class ShortcutArithmeticOpdemo {       public static void main(String[] args) {                   int a,b,c,d;           a=b=c=d=100;                      int p = a++;           int r = c--;           int q = ++b;           int s = --d;           System.out.println("prefix increment operator result= "+ p + " & Value of a= "+ a);           System.out.println("prefix decrement operator result= "+ r + " & Value of c= "+c);           System.out.println("postfix increment operator result= "+ q + " & Value of b= "+ b);           System.out.println("postfix decrement operator result= "+ s + " & Value of d= "+d);       }  

Page 4: Java Arithmetic Operators.docx

}   - See more at: http://www.w3resource.com/java-tutorial/java-arithmetic-operators.php#sthash.9mnRRDXP.dpuf

Relational OperatorsRelational operator compares two values and determines the relationship between them. Relational operators are used to test whether two values are equal, whether one value is greater than another, and so forth.

Below table lists relational operators in java.

Relational Operators In Java

 Operator Meaning  Example  == Equals  a == b  != Not equals  a != b  > Greater than  a > b  <   Less than  a < b  >=  Greater than or equals  a >= b  <=  Less than or equals  a <= b 

Precedence of Relational Operators

Highest to Lowest

Operator

1 >, >=, <, <=2 ==, !=

Syntax of Relational Operators

Page 5: Java Arithmetic Operators.docx

op1 relOptr op2

op1 is a first operand to compare.op2 is a second operand to compare.relOptr is a relational operator.

Examples of Relational Operators

Example 1 : Program that displays use of all relational operators i.e ==, !=, >, <, >= and <=

class RelOptrDemo {   public static void main(String[] args)    {int a = 10, b = 15, c = 15;

System.out.println("Relational Operators and returned values");System.out.println(" a > b = " + (a > b)); System.out.println(" a < b = " + (a < b)); System.out.println(" b >= a = " + (b >= a)); System.out.println(" b <= a = " + (b <= a)); System.out.println(" b == c = " + (b == c)); System.out.println(" b != c = " + (b != c));    }}

Output

Relational Operators and returned valuesa > b = falsea < b = trueb >= a = trueb <= a = falseb == c = trueb != c = false

Examples of Relational Operators

Example 1 : Program that displays use of all relational operators i.e ==, !=, >, <, >= and <=

class RelOptrDemo 

Page 6: Java Arithmetic Operators.docx

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

System.out.println("Relational Operators and returned values");System.out.println(" a > b = " + (a > b)); System.out.println(" a < b = " + (a < b)); System.out.println(" b >= a = " + (b >= a)); System.out.println(" b <= a = " + (b <= a)); System.out.println(" b == c = " + (b == c)); System.out.println(" b != c = " + (b != c));    }}

Output

Relational Operators and returned valuesa > b = falsea < b = trueb >= a = trueb <= a = falseb == c = trueb != c = false

Java Logical Operators Examplepublic class Test {

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

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

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

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

This would produce the following result:

a && b = falsea || b = true!(a && b) = true

Java Logical Operators

Page 7: Java Arithmetic Operators.docx

package operatorsdemo;            public class BitwiseLogicalOpDemo {                public static void main(String[] args) {              //Integer bitwise logical operator              int a = 65; // binary representation 1000001              int b = 33; // binary representation 0100001                            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);                            //boolean logical operator              boolean bool1 = true;              boolean bool2 = true;              boolean bool3 = false;                            System.out.println("bool1 & bool2= " + (bool1 & bool2));              System.out.println("bool2 & bool3= " + (bool2 | bool3));              System.out.println("bool2 | bool3= " + (bool2 | bool3));              System.out.println("bool1 ^ bool2= " + (bool1 ^ bool2));     

Page 8: Java Arithmetic Operators.docx

        System.out.println("!bool1= " + !bool1);                }            }   - See more at: http://www.w3resource.com/java-tutorial/java-logical-operators.php#sthash.uNuHuacL.dpuf

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

// these are boolean variables           boolean A = true;      boolean B = false; 

      System.out.println("A|B = "+(A|B));      System.out.println("A&B = "+(A&B));      System.out.println("!A = "+(!A));      System.out.println("A^B = "+(A^B));      System.out.println("(A|B)&A = "+((A|B)&A));    }}

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

      int x = 0;      int y = 0;      boolean A = true;      boolean B = false; 

// A is true , ++x<0 will not be evaluated since the || operator is used.      boolean C = A||(++x<0);      System.out.println("x = "+x);      System.out.println("C = "+C);

// ++y<0 will be evaluated since the | operator is used.      boolean D = A|(++y<0);      System.out.println("y = "+y);      System.out.println("D = "+D);

// note both C and D evaluate to true.    }}

Operator Meaning

Page 9: Java Arithmetic Operators.docx

< less than

<= less than or equal to

> greater than

>= greater than or equal to

== equal to

!= not equal to

&& logical AND

|| logical OR

! logical NOT

The above 1st 6 are relational operators in java and last 3 are logical operators

The relation operators are used to compare 2 values. The output of relational operators is either true (1) or false (0)

Syntax:-

value1 relational_operator value2

Example:-

2 < 10     True3 > 8       False7.5>=5    True

value1 and value2 are can be constants, variable or combination of them.

Relation operator are used in if-else or in loop statement.

Example:-

Program to find Greatest number between 2

import java.util.Scanner;

class group{public static void main(String arg[]){int num1, num2;Scanner grest = new Scanner(System.in);System.out.println("Enter 1st number");num1 = grest.nextInt();

Page 10: Java Arithmetic Operators.docx

System.out.println("Enter 2nd number");num2 = grest.nextInt();if(num1 < num2)System.out.println("Greatest number"+num1);elseSystem.out.println("Greatest number"+num2);}}

Logical operators:-

logical operators && and || are used to when we want to check 2 or more condition statement.

Example

8 > 7 && 5 < 8      True8 < 5 || 8 < 9           False7 > 2 && 19 < 2    False

AND (&&) operator output is true only when either condition statement is true.OR (||) operator output is false only when either condition statement is false.

Truth table:-

A B AND

0 0 0

0 1 0

1 0 0

1 1 1

A B OR

0 0 0

0 1 1

1 0 1

1 1 1

NOT (!)  logical operator is used for compliment condition statement outputs.

Page 11: Java Arithmetic Operators.docx

Truth table:-

A NOT

0 1

1 0

Example:-

Program to solve following problemThe candidate is selected if his age and height is 18 and 5 and more respectively.

import java.util.Scanner;class group{public static void main(String arg[]){int age, height;Scanner data = new Scanner(System.in);System.out.println("Enter candidate age");age = data.nextInt();System.out.println("Enter cadidate height");height = data.nextInt();if((age >= 18) && (height >= 5))System.out.println("The cadidate is selected");elseSystem.out.println("sorry, candidate not selected");}}

Java program for logical NOTProgram to find max number between 2

import java.util.Scanner;class group{public static void main(String arg[]){int num1,num2;Scanner data = new Scanner(System.in);System.out.println("Enter 1st number");num1 = data.nextInt();System.out.println("Enter 2nd number");num2 = data.nextInt();if(!(num1>num2))System.out.println("max nuber between 2 is:"+num2);elseSystem.out.println("max nuber between 2 is:"+num1);

Page 12: Java Arithmetic Operators.docx

}}