Updated OOP With JAVA - Module 1
Updated OOP With JAVA - Module 1
Inheritence:
Inheritence is the process by which one object acquires the properties of another
object. This is important as it supports the concept of hierarchical classification.
By the use of inheritence, a class has to define only those qualities that make it
unique. The general qualities can ber derived from the parent class or base class.
Ex: A child inheriting properties from parents.
Polymorphism
Polymorphism (meaning many forms) is a feature that allows one interface to be
used for a general class of actions. The specific action determined by the exact
nature of the situation. This concept is often expressed as ― one interface, multiple
methods‖.
Ex: ―+‖ can be used for addition of 2 numbers and also concatenation of 2 strings.
System.out.println(2+4); // outputs 6 as answer
System.out.println(―Hello‖ + ―Gautham‖); // outputs Hello Gautham as answer
Apart from this the additional features include:
Object:
An object can be any real world entity.
Ex: an animal, bank, human, box, fan etc
An object is a software bundle of related state and behavior.
An object is an instance of class.
Class:
A class is a blueprint or prototype from which objects are created.
Its just a template for an object, which describes an object.
Ex: a class describes how an animal looks like.
A class is a user defined data type.
Abstraction:
Data abstraction refers to providing only essential information to the outside world
and hiding their background details i.e., to represent the needed informatin in
program without presenting the details.
Ex: a database system hides certain details of how data is stored and created and
maintained.
class Example
{
public static void main(String args[])
{
System.out.println(―Welcome to Programming in Java‖);
}
}
Note:
In Java all code must reside inside a class and name of that class should match the
name of the file that holds the program.
Java is case-sensitive
Description:
(1) Class declaration: ―class Example‖ declares a class, which is an object- oriented
construct. Sampleone is a Java identifier that specifies the name of the class to be
defined.
(2) Opening braces: Every class definition of Java starts with opening braces and ends
with matching one.
(3) The main line: the line ― public static void main(String args[]) ― defines a method
name main. Java application program must include this main. This is the starting point
of the interpreter from where it starts executing. A Java program can have any number
of classes but only one class will have the main method.
(4) Public: This key word is an access specifier that declares the main method as
unprotected and therefore making it accessible to the all other classes.
(5) Static: Static keyword defines the method as one that belongs to the entire class and
not for a particular object of the class. The main must always be declared as static.
(6) Void: the type modifier void specifies that the method main does not return any value.
(7) The println: It is a method of the object out of system class. It is similar to the printf
or cout of c or c++. This always appends a newline character to the end of the string
i.e, any subsequent output will start on a new line.
The statement System.out.println(― the value of n is ―+n), the sign ―+‖ causes the value of
―n‖ to be appended to the string that preceeds it, and the resulting string is output.( Actually
n is first converted from an integer into its string equivalent and the concatenated with the
string that preceeds it)
The System.out.print( ) method is just like println( ) except that it does not output a newline
character after each call.
if statement
The if- statement is the most basic of all the control flow statements. It tells your
program to execute a certain section of code only if a particular test evaluates
to true.
Here is the general form of the if statement:
if (condition) statement;
Here the condition is Boolean expression.
If the condition is true then the statement is executed, if false then statement will be
skipped.
Example:
class Example
{
public static void main(String args[])
{
int a=10;
if(a>0)
System.out.println(―a is positive number‖);
System.out.println(― End of program‖);
}
OOPS with Java (ADS234071)
}
In the above program since a is greater than o it prints the output as
a is positive number
End of program
Output:
0
1
OOPS with Java (ADS234071)
2
3
4
End of Program
Java supports code blocks - which means that two or more statements are grouped
into blocks of code.
Opening and closing braces is used to achieve this.
Each block is treated as logical unit.
Whenever two or more statements has to be linked blocks can be used.
Example:
class Example
{
public static void main(String args[])
{
int a=10;
if(a>0)
{ // begin of block
System.out.println(―a is positive number‖);
System.out.println(― inside block‖);
}// end of block
}
}
Lexical issues:
Java programs are a collection of whitespace, identifiers, literals, comments, operators,
separators, and keywords.
Whitespace:
Java is a free from language- means no need to follow any indentation rules.
Whitespace is a space, tab, or newline.
OOPS with Java (ADS234071)
(b) Identifiers
(c) Literals.
(d) Operators
(e) Separators.
Reserved keyword:
Java language has 50 words as reserved keywords. They implement specific feature of the
language. The keywords combined with operators and separators according to syntax build
the Java language.
Identifiers:
Identifiers are programmer-designed token used for naming classes methods variable,
objects, labels etc. The rules for identifiers are
1. They can have alphabets, digits, dollar sign and underscores.
2. They must not begin with digit.
3. Uppercase and lower case letters are distinct.
4. They can be any lengths.
6. In case of more than one word starts with uppercase in next word.
7. All private and local variables use only lowercase and underscore.
8. All classes and interfaces start with leading uppercases.
Literals:
Literals in Java are sequence of characters that represents constant values to be stored in
variables. Java language specifies five major types of Literals. They are:
1. Integer Literals.
2. Floating-point Literals.
3. Character Literals.
4. String Literals.
5. Boolean Literals.
Operators:
An operator is a symbol that takes one or more arguments and operates on them to produce
an result.
Separators:
Separators are the symbols that indicates where group of code are divided and arranged.
Some of the operators are:
OOPS with Java (ADS234071)
Comments:
Java supports 3 styles of comments
Multiline comment: this type of comment begins with /* and ends with */
Ex: /* Welcome to
Java Programming */
Single line comments: this type of comment begins with // and ends at the end of
current line
Ex: // Welcome to java Programming
Documentation Comment: this type of comment is used to produce an HTML file
that documents your program. The documentation comment begins with /** and
ends with */
Java Buzzwords
The Java Buzzwords are a set of key features that define Java and distinguish it from other
programming languages. These were introduced by Sun Microsystems when Java was first
released. The main Java Buzzwords are:
1. Simple – Java is designed to be easy to learn, with a syntax similar to C++ but without
complex features like pointers and operator overloading.
2. Object-Oriented – Everything in Java is treated as an object, promoting modularity,
reusability, and easier maintenance.
3. Distributed – Java supports distributed computing through APIs like RMI (Remote
Method Invocation) and CORBA.
4. Multithreaded – Java has built-in support for multithreading, allowing efficient
execution of multiple tasks simultaneously.
5. Platform-Independent – Java programs run on any device with a Java Virtual Machine
(JVM), making it a "write once, run anywhere" language.
OOPS with Java (ADS234071)
6. Secure – Java provides a robust security model, including features like bytecode
verification, class loaders, and a security manager to prevent malicious code execution.
7. Robust – Java handles memory management automatically and has strong exception
handling, reducing crashes and memory leaks.
8. Architecture-Neutral – Java code is compiled into bytecode, which can be executed on
any processor that has a JVM.
9. Portable – Due to its platform independence and lack of hardware-specific features,
Java programs are highly portable.
10. High Performance – Although Java is interpreted, modern JVMs use Just-In-Time
(JIT) compilation for improved performance.
11. Dynamic – Java supports dynamic loading of classes, linking, and runtime adaptability.
12. Interpreted – Java bytecode is executed by the JVM, making debugging and
development easier.
OOPS with Java (ADS234071)
Data types
class
boolean interfaces
Integer Floating type
character string etc
byte float
short double
int
Primitive types:
long
Java defines eight primitive types of data: byte, short, int, long, char, float, double, and
boolean. As shown in above figure.
The primitive types represent single values—not complex objects. Although Java is
otherwise completely object-oriented, the primitive types are not.
OOPS with Java (ADS234071)
They are analogous to the simple types found in most other non–object-oriented
languages.
The reason for this is efficiency. Making the primitive types into objects would have
degraded performance too much. The primitive types are defined to have an explicit
range and mathematical behavior.
Because of Java‗s portability requirement, all data types have a strictly defined range.
For example, an int is always 32 bits, regardless of the particular platform.
Integers
Java defines four integer types: byte, short, int, and long.
All of these are signed, positive and negative values. Java does not support unsigned,
positive-only integers.
Many other computer languages support both signed and unsigned integers.
However, Java‗s designers felt that unsigned integers were unnecessary. Specifically,
they felt that the concept of unsigned was used mostly to specify the behavior of
the high-order bit, which defines the sign of an integer value.
byte
The smallest integer type is byte.
This is a signed 8-bit type that has a range from –128 to127.
Variables of type byte are especially useful when you‗re working with a stream of
data from a network or file.
Byte variables are declared by use of the byte keyword.
For example, the following declares two byte variables called b and c: byte b, c;
OOPS with Java (ADS234071)
short
short is a signed 16-bit type.
It has a range from –32,768 to 32,767.
It is probably the least-used Java type.
Floating-Point Types
Floating-point numbers, also known as real numbers, are used when evaluating
expressions that require fractional precision.
For example, calculations such as square root, or transcendental such as sine and
cosine, result in a value whose precision requires a floating-point type.
There are two kinds of floating-point types, float and double, which represent
single- and double-precision numbers, respectively.
float
The type float specifies a single-precision value that uses 32 bits of storage.
double
Double precision, as denoted by the double keyword, uses 64 bits to store a value.
Double precision is actually faster than single precision on some modern processors
that have been optimized for high-speed mathematical calculations.
Characters
In Java, the data type used to store characters is char.
However, C/C++ programmers beware: char in Java is not the same as char in C or
C++.
In C/C++, char is 8 bits wide. This is not the case in Java. Instead, Java uses Unicode
to represent characters.
Unicode defines a fully international character set that can represent all of the
characters found in all human languages.
It is a unification of dozens of character sets, such as Latin, Greek
Arabic, Cyrillic,Hebrew, Katakana, Hangul, and many more. For this purpose, it
requires 16 bits.
OOPS with Java (ADS234071)
Thus, in Java char is a 16-bit type. The range of a char is 0 to 65,536. There are no
negative
Booleans:
Java has a simple type called boolean for logical values. It can have only one of two possible
values. They are true or false.
Literals:
A constant value in Java is created by using a literal representation of it. There are 5 types of
literals.
Integer Literals.
Floating-point Literals.
Character Literals.
String Literals.
Boolean Literals.
Integer literals:
Any whole number value is an integer literal.
These are all decimal values describing a base 10 number.
There are two other bases which can be used in integer literal, octal( base 8) where 0
is prefixed with the value, hexadecimal (base 16) where 0X or 0x is prefixed with the
integer value.
Example:
int decimal = 100;
int octal = 0144;
int hexa = 0x64;
OOPS with Java (ADS234071)
Example:
0.0314 *10² (i.e 3.14).
6.5E+32 (or 6.5E32) Double-precision floating-point literal
7D Double-precision floating-point literal
.01f Floating-point literal
Character literals:
char data type is a single 16-bit Unicode character.
We can specify a character literal as a single printable character in a pair of single
quote characters such as 'a', '#', and '3'.
You must know about the ASCII character set. The ASCII character set includes 128
characters including letters, numerals, punctuation etc.
Below table shows a set of these special characters.
OOPS with Java (ADS234071)
Boolean Literals:
The values true and false are treated as literals in Java programming.
When we assign a value to a boolean variable, we can only use these two values.
Unlike C, we can't presume that the value of 1 is equivalent to true and 0 is equivalent
to false in Java.
We have to use the values true and false to represent a Boolean value.
Example
boolean chosen = true;
String Literal
The set of characters in represented as String literals in Java.
Always use "double quotes" for String literals.
There are few methods provided in Java to combine strings, modify strings and to
know whether to strings have the same values.
Example:
―hello world‖
―Java‖
Variables:
A variable is an identifier that denotes a storage location used to store a data value. A
variable may have different value in the different phase of the program. To declare one
identifier as a variable there are certain rules. They are:
1. They must not begin with a digit.
2. Uppercase and lowercase are distinct.
3. It should not be a keyword.
4. White space is not allowed.
Dynamic initialization:
Java allows variables to be initialized dynamically, using expression valid at the time
variable is declared.
Example:
class Example
{
public static void main(String args[])
{
double a=10, b=2.6;
double c=a/b;
System.out.println(―value of c is‖+c);
}
}
scope, you are localizing that variable and protecting it from unauthorized access
and/or modification.
class Scope
{
public static void main(String args[])
{
int x; // known to all code within main x = 10;
if(x == 10) // start new scope
{
int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y); x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here. System.out.println("x is " + x);
}
}
Note:
There should not be two variables with the same name in different scope.
The variable at outer scope can be accessed in inner scope but vice versa is not
possible.
Widening or Automatic type converion Automatic Type casting take place when, the
two types are compatible
the target type is larger than the source type
OOPS with Java (ADS234071)
Example :
public class Test
{
public static void main(String[] args)
{
int i = 100;
long l = i; //no explicit type casting required
float f = l; //no explicit type casting required
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}
}
Output :
Int value 100
Long value 100
Float value 100.0
{
double d = 100.04;
long l = (long)d; //explicit type casting required
int i = (int)l; //explicit type casting required
System.out.println("Double value "+d);
System.out.println("Long value "+l);
System.out.println("Int value "+i);
}
}
Output :
Double value 100.04
Long value 100
Int value 100
OOPS with Java (ADS234071)
byte b = 50;
b = (byte)(b * 2); which yields the correct value of 100.
Java defines several type promotion rules that apply to expressions. They are as follows:
First, all byte, short, and char values are promoted to int, as just described.
Then, if one operand is a long, the whole expression is promoted to long.
If one operand is a float, the entire expression is promoted to float.
If any of the operands is double, the result is double.
Arrays in Java
Arraywhich stores a fixed-size sequential collection of elements of the same type.
An array is used to store a collection of data, but it is often more useful to think of an
array as a collection of variables of the same type.
Example:
The following code snippets are examples of this syntax:
Creating Arrays:
You can create an array by using the new operator with the following syntax:
Example:
Following statement declares an array variable, myList, creates an array of 10 elements of
double type and assigns its reference to myList:
double[] myList = new double[10];
Following picture represents array myList. Here, myList holds ten double values and
the indices are from 0 to 9.
Processing Arrays:
When processing array elements, we often use either for loop or foreach loop because all
of the elements in an array are of the same type and the size of the array is known.
Example:
Here is a complete example of showing how to create, initialize and process arrays:
class TestArray
{
OOPS with Java (ADS234071)
Multidimensional Arrays
Java does not support multidimensional arrays. However, you can declare and create an array
of arrays (and those arrays can contain arrays, and so on, for however many dimensions you
need), and access them as you would C-style multidimensional arrays:
int coords[] [] = new int[12] [12];
coords[0] [0] = 1; coords[0] [1] = 2;
Programs:
// Compute distance light travels using long variables.
class Light
{
public static void main(String args[])
{
int lightspeed;
long days;
long seconds;
long distance; // approximate speed of light in miles per second
lightspeed = 186000;
days = 1000; // specify number of days here
OOPS with Java (ADS234071)
Type conversion
class Conversion
{
public static void main(String args[])
{
byte b;
int i = 257;
double d = 323.142;
System.out.println("\nConversion of int to byte.");
b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("\nConversion of double to int.");
i = (int) d;
System.out.println("d and i " + d + " " + i);
System.out.println("\nConversion of double to byte.");
b = (byte) d; System.out.println("d and b " + d + " " + b);
}
}
This program generates the following output:
Conversion of int to byte.
i and b 257 1
Conversion of double to int.
d and i 323.142 323
Conversion of double to byte.
d and b 323.142 67
OOP with Java (ADS234071)
Control Statements
Java’s program control statements can be put into the following categories: selection,
iteration, and jump.
Selection statements allow your program to choose different paths of execution based
upon the outcome of an expression or the state of a variable.
Iteration statements enable program execution to repeat one or more statements (that
is, iteration statements form loops).
Jump statements allow your program to execute in a nonlinear fashion.
The if statement
The if statement executes a block of code only if the specified expression is true.
If the value is false, then the if block is skipped and execution continues with the rest
of the program.
You can either have a single statement or a block of code within an if statement.
Note that the conditional expression must be a Boolean expression.
Syntax:
if (<conditional expression>) {
<statements>
}
Example:
public class Example {
public static void main(String[] args) {
int a = 10, b = 20;
if (a > b)
System.out.println("a > b");
if (a < b)
System.out.println("b > a");
}
}
Syntax:
if (condition)
statement1;
else statement2;
}
}
OOP with Java (ADS234071)
Nested ifs
A nested if is an if statement that is the target of another if or else.
When you nest ifs, the main thing to remember is that an else statement always refers
to the nearest if statement that is within the same block as the else and that is not
already associated with an else.
Here is an example:
if(i == 10) {
if(j < 20) a = b;
if(k > 100) c = d; // this if is
else a = c; // associated with this else
}
else a = d; // this else refers to if(i == 10)
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
...
else
statement;
Example:
class IfElse {
public static void main(String args[]) {
int month = 4; // April
String season;
if(month == 12 || month == 1 || month == 2)
season = "Winter";
else if(month == 3 || month == 4 || month == 5)
season = "Spring";
else if(month == 6 || month == 7 || month == 8)
season = "Summer";
else if(month == 9 || month == 10 || month == 11)
season = "Autumn";
else
season = "Bogus Month";
System.out.println("April is in the " + season + ".");
}
}
The program will select the value of the case label that equals the value of the
controlling expression and branch down that path to the end of the code block.
If none of the case label values match, then none of the codes within the switch
statement code block will be executed. Java includes a default label to use in cases
where there are no matches.
We can have a nested switch within a case block of an outer switch.
Syntax:
switch (<non-long integral expression>) {
case label1: <statement1> ; break;
case label2: <statement2> ; break;
…
case labeln: <statementn> ; break;
default: <statement>
}
Example:
public class Example {
public static void main(String[] args) {
int a = 10, b = 20, c = 30;
int status = -1;
if (a > b && a > c) {
status = 1;
} else if (b > c) {
status = 2;
} else {
status = 3;
}
switch (status) {
case 1:
System.out.println("a is the greatest");
break;
case 2:
OOP with Java (ADS234071)
case 3:
System.out.println("c is the greatest");
break;
default:
System.out.println("Cannot be determined");
}
}
}
The break statement is optional. If you omit the break, execution will continue on
into the next case.
It is sometimes desirable to have multiple cases without break statements between
them.
For example, consider the following program:
// In a switch, break statements are optional.
class MissingBreak {
public static void main(String args[]) {
for(int i=0; i<12; i++)
switch(i) {
case 0:
case 1:
case 2:
case 3:
case 4:
System.out.println("i is less than 5");
break;
case 5:
case 6:
case 7:
case 8:
case 9:
OOP with Java (ADS234071)
In summary, there are three important features of the switch statement to note:
The switch differs from the if in that switch can only test for equality, whereas if can
evaluate any type of Boolean expression. That is, the switch looks only for a match
between the value of the expression and one of its case constants.
No two case constants in the same switch can have identical values. Of course, a
switch statement and an enclosing outer switch can have case constants in common.
OOP with Java (ADS234071)
Iteration Statements
Syntax:
while (<loop condition>) {
<statements>
}
Example:
Syntax:
do {
<loop body>
} while (<loop condition>);
Example:
public class Example {
public static void main(String[] args) {
int count = 1;
System.out.println("Printing Numbers from 1 to 10");
do {
OOP with Java (ADS234071)
System.out.println(count++);
} while (count <= 10);
}
}
Syntax:
for (<initialization>; <loop condition>; <increment expression>) {
<loop body>
}
Example:
public class Example {
public static void main(String[] args) {
System.out.println("Printing Numbers from 1 to 10");
for (int count = 1; count <= 10; count++) {
System.out.println(count);
}
}
}
Jump Statements
Java supports three jump statements: break, continue, and return. These statements
transfer control to another part of your program.
The break statement
The break statement transfers control out of the enclosing loop (for, while, do or
switch statement).
You use a break statement when you want to jump immediately to the statement
following the enclosing control structure.
You can also provide a loop with a label, and then use the label in your break
statement.
The label name is optional, and is usually only used when you wish to terminate the
Syntax:
break; // the unlabeled form
break <label>; // the labeled form
OOP with Java (ADS234071)
outermost loop in a series of nested loops.
}
System.out.println("This is after second block.");
}
}
}
Running this program generates the following output:
Before the break.
This is after second block.
OOP with Java (ADS234071)
Syntax:
continue; // the unlabeled form
continue <label>; // the labeled form
Introduction
Java supports a rich set of operators. We have already used several of them, such as =,
+, –, and *. An operator is a symbol that tells the computer to perform certain mathematical or
logical manipulations. Operators are used in programs to manipulate data and variables. They
usually form a part of mathematical or logical expressions.
Java operators can be classified into a number of related categories as below:
1. Arithmetic operators
2. Relational operatorsLogical operators
3. Assignment operators
4. Increment and decrement operators
5. Conditional operators
6. Bitwise operators
7. Special operators
1. Arithmetic Operators
Arithmetic operators are used to construct mathematical expressions as in algebra. Java
provides all the basic arithmetic operators. They are listed in Tabled 3.1. The operators +, –, *,
and / all works the same way as they do in other languages. These can on any built-in numeric
data type of Java. We cannot use these operators on Boolean type. The unary minus operator,
in effect, multiplies its single operand by –1. Therefore, a number preceded by a minus sign
changes its sign.
Table 1.1 Arithmetic Operators
Operator Meaning
+ Addition or unary plus
– Subtraction or unary minus
* Multiplication
/ Division
% Modulo division (Remainder)
Relational Expressions
Expression Value
4.5 <= 10 TRUE
4.5 < –10 FALSE
– 35 >= 0 FALSE
10 < 7 + 5 TRUE
a+b==c+d TRUE*
* Only if the sum of values of a and b is equal to the sum of values of c and d.
3. Logical Operators
In addition to the relational operators, Java has three logical
operators, which are given in Table 3.4.
Table 3.1 Logical Operators
Operator 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. An example is:
a > b && x == 10
An expression of this kind which combines two or more relational expressions is termed
as a logical expression or a compound relational expression. Like the simple relational
expressions, a logical expression also yields a value of true or false, according to the truth table
shown in Table 3.5. The logical expression is given above is true only if both a > b and x = 10
are true. If either (or both) of them are false the expression is false.
4 Assignment Operators
Assignment operators are used to assign the value of an expression to a variable. We
have seen the usual assignment operator, ‘=’. In addition, Java has a set of ‘shorthand’
v op= exp;
assignment operators which are used in the form
where v is a variable, exp is an expression and op is a Java binary operatory. The operator
op = is known as the shorthand assignment operator.
The assignment statement
v op= exp;
is equivalent to
v = v op(exp);
with v accessed only once.
7 Bitwise Operators
Java has a distinction of supporting special operators known as bitwise operators for
manipulation of data at values of bit level. These operators are used for testing the bits, or
shifting them to the right or left. Bitwise operators may not be applied to float or double. Table
3.7 lists the bitwise operators. They are discussed in detail in Appendix D.
Table 7.1Bitwise Operators
Operator Meaning
& bitwise AND
! bitwise OR
^ Bitwise exclusive OR
~ one’s complement
<< shift left
>> shift right
>>> shift right with zero fill
8 Special Operators
Java supports some special operators of interest such as instanceof operatory and
member selection operator (.).
The instanceof is an object operator and returns true of the object on the left-hand side
is an instance of the class given on the right-hand side. This operator allows us to determine
whether the object belongs to a particular class or not.
Example:
person instanceof student
is true if the object person belongs to the class student; otherwise it is false.
Dot Operator
The dot operator (.) is used to access the instance variables and methods of class objects.
Examples:
personal.age / / Reference to the variable age
personal.salary / / Reference to the method salary()
It is also used to access classes and sub-packages from a package.
Precedence of Arithmetic Operators
An arithmetic expression without any parentheses will be evaluated from left to right using the rules
of precedence of operators. There are two distinct priority levels of arithmetic operators in Java:
The basic evaluation procedure includes two left-to-right passed through the
expression. During the first pass, the high priority operators (if any) are applied as they are
encountered.
High priority * / %
Low priority + –
During the second pass, the low priority operators (if any) are applied as they are
encountered. Consider the following evaluation statement:
x = a–b/3 + c*2–1
When a = 9, b = 12, and c = 3, the statement becomes
x = 9–12/3+3*2–1
and is evaluated as follows:
First pass
Step1: x = 9–4+3*2–1 (12/3 evaluated)
Step2: x = 9–4+6–1 (3*2 evaluated)
Second pass
Step3: x = 5+6–1 (9–4 evaluated)
Step4: x = 11–1 (5+6 evaluated)
Step5: x = 10 (11–1 evaluated)
However, the order of evaluation can be changed by introducing parentheses into an
expression. Consider the same expression with parentheses as shown below:
9–12/(3+3)*(2–1)
Whenever the parentheses are used, the expressions within parentheses assume highest
priority. If two or more sets of parentheses appear one after another as shown above, the
expression contained in the left-most set is evaluated first and the right-most in the last. Given
below are the new steps.
First pass
Step1: 9–12/6*(2–1)
Step2: 9–12/6*1
Second pass
Step3: 9–2*1
Step4: 9–2
Third pass
Step5: 7
This time, the procedure consists of three left-to-right passes. However, the number of
evaluation steps remain the same as 5 (i.e., equal to the number of arithmetic operators).
Parentheses may be nested, and in such cases, evaluation of the expression will proceed
outward from the innermost set of parentheses. Just make sure that every parentheses has a
matching closing one. For example
9–((12/3)+3*2)–1 = –2