Java Tutorial 6 --- "Associativity and Precedence"
DOC-
CODE -
package com.company;
public class Tut6 {
public static void main(String[] args) {
// Associativity & Precedence
// int a = 6*5 - 34/2;
/* BODMAS Rule doesn't apply in here
= 6*5 - 34/2
= 30-34/2
= 30-17
= 13
*/
// System.out.println(a);
// int b = 34/2 - 6*5;
/* Highest precedence goes to * and /. They are then evaluated on the basis
of left to right associativity.
= 34/2 - 6*5
= 17 - 6*5
= 17 - 30
= -13
*/
// System.out.println(b);
// Quick Quiz
// (i) x-y/2 = ?
int x = 50;
int y = 10;
int quiz1 = x-y/2;
// JAVA = 45 BODMAS = 20
System.out.println(quiz1);
// (ii) b^2-4ac/2
int a = 4;
int b = 10;
int c = 5;
int quiz2 = b*b-4*a*c/2;
// JAVA = 60 BODMAS = 10
System.out.println(quiz2);
// (iii) v^2-u^2
int v = 7;
int u = 2;
int quiz3 = v*v-u*u;
// JAVA = 45 BODMAS = 45
System.out.println(quiz3);
// (iv) m*n-p
int m = 10;
int n = 5;
int p = 2;
int quiz4 = m*n-p;
System.out.println(quiz4);
// To behave JAVA calculations like BODMAS use Parenthesis()
}
}
Comments
Post a Comment