Unit 04.
Operators in Java
------------------------------------------------------------------------------------------------------------------------
Operators
Operators are tokens (symbols) that perform specific operations on one or more operands (variables,
literals, or expressions). Java provides a wide range of operators, which can be categorized into
several categories.
Forms of Operators
Operators can take different forms based on the number of operands they operate on. Here are
different forms of operators in Java:
1. Unary Operators (acts on a single operand)
Examples: Unary plus operator (+), Unary minus operator (–), Increment operator (++),
Decrement operator (––) and Logical NOT operator (!)
2. Binary Operators (operate on two operands)
Examples: Arithmetic operators (+, –, *, /, %), Relational operators (==, !=, >, <, >=, <=),
Logical operators (&&, ||) and Assignment operator (=)
3. Ternary Operator (takes three operands) Example: Conditional operators (? :)
Types of Operators
Operators can also be categorized into different types based on their functionality and the operations
they perform. Here are the types of operators in Java:
Arithmetic Operators
Arithmetic operators perform mathematical (arithmetic) calculations on numeric operands. Here are
the arithmetic operators:
1. Addition (+): Adds two operands.
2. Subtraction (–): Subtracts the second operand from the first.
3. Multiplication (*): Multiplies two operands.
4. Division (/): Divides the first operand by the second.
5. Modulus (%): Returns the remainder of the division operation.
These arithmetic operators can be used with various numeric types, such as int, long, float and
double. They follow the usual mathematical precedence rules, and parentheses can be used to
specify the desired order of operations.
Increment and Decrement Operators
Increment / Decrement operators are used to increase/decrease the value of a variable by 1.
1. Increment (++): Increases the value of an operand by 1.
2. Decrement (––): Decreases the value of an operand by 1.
In Java, the increment and decrement operators have two forms: prefix and postfix. These forms
determine when the increment or decrement operation take place in relation to the use of the
variable. Here are the forms of increment and decrement operators:
1. Pre-increment Operator (prefix: ++variable)
The pre-increment operator increases the value of the variable by 1 before it is used in the
expression. The updated value is immediately available for use in the expression.
2. Pre-decrement Operator (prefix: ––variable)
The pre-decrement operator decreases the value of the variable by 1 before it is used in the
expression. The updated value is immediately available for use in the expression.
3. Post-increment Operator (postfix: variable++)
The post-increment operator uses the value of the variable in the expression and then
increases it by 1. The original value is used in the expression, and the variable is
incremented afterward.
4. Post-decrement Operator (postfix: variable––)
The post-decrement operator uses the value of the variable in the expression and then
decreases it by 1. The original value is used in the expression, and the variable is
decremented afterward.
In both prefix and postfix cases, the variable being incremented/decremented must be a numeric
type, such as int or long. It is important to note that prefix and postfix can have different effects
when used in complex expressions or as part of larger statements. Understanding their behaviour
and choosing the appropriate form can ensure the desired outcome in our code.
The choice between prefix and postfix forms depends on the desired behaviour and the specific
requirements of our code. Understanding the difference between these forms is crucial to ensure
correct results when working with increment and decrement operations.
Relational Operators
Relational operators are used to compare values and determine the relationship between two
operands. These operators return boolean values (true or false) based on the comparison result.
Here are the relational operators:
1. Equality (==): Checks if two operands are equal.
2. Inequality (!=): Checks if two operands are not equal.
3. Greater than (>): Checks if the first operand is greater than the second operand.
4. Less than (<): Checks if the first operand is less than the second operand.
5. Greater than or equal to (>=): Checks if the first operand is greater than or equal to the
second operand.
6. Less than or equal to (<=): Checks if the first operand is less than or equal to the second
operand.
These operators can be used with various types of operands, including numeric types (int, double,
etc.) and non-numeric types (such as char). The result of a relational operation is always a boolean
value indicating the comparison is true or false.
Relational operators are commonly used in conditional and iteration statements to make decisions
based on the relationship between values.
Logical Operators
Logical operators are used to combine boolean expressions and perform logical operations. They
allow us to make decisions based on multiple conditions and evaluate the truthiness or falseness of
the expressions involved. Java provides three logical operators:
1. Logical AND (&&): Returns true if both of its operands are true; otherwise, it returns false.
2. Logical OR (||): Returns true if at least one of its operands is true; otherwise, it returns false.
3. Logical NOT (!): Negates the boolean value of its operand. It returns true if the operand is
false, and false if the operand is true.
These logical operators are commonly used in conditional and iteration statements to control the
flow of the program based on certain conditions. They are also useful for combining boolean
expressions to create complex conditions.
Conditional Operator
The conditional operator (the ternary operator) is a shorthand way of writing conditional
expressions in Java. It allows us to make decisions and choose between expressions based on a
condition. The syntax of the conditional operator is as follows:
condition ? expression1 : expression2
Here is how the conditional operator works:
1. The condition is evaluated first.
2. If the condition is true, expression1 is evaluated and becomes the result of the entire
conditional expression.
3. If the condition is false, expression2 is evaluated and becomes the result of the entire
conditional expression.
It’s important to note that the expressions expersion1 and expression2 in the conditional operator
can be any valid expressions, including literals, variables, method calls, or even complex
expressions.
However, they must be compatible in type or have compatible types that can be implicitly
converted.
Example:
int n1 = 9, n2 = 10; int max = (n1>n2) ? n1 : n2;
In this example, the condition (n1>n2) is evaluated. If n1 is greater than n2, the value of n1 is
assigned to max. Otherwise, the value of n2 is assigned to max. The result of the conditional
expression becomes the value of max.
The conditional operator provides a concise way of expressing simple conditional logic in Java, and
it is often used in situations where we need to assign a value to a variable based on a condition.
Assignment Operator
The assignment operator is used to assign a value to a variable. It allows us to store a value in a
variable and update its content. The assignment operator is denoted by the equal sign (=). Here’s the
syntax:
variable = value;
The value on the right side of the assignment operator is assigned to the variable on the left side.
The type of value must be compatible with the type of variable.
Example:
int num = 9;
In this example, the value 9 is assigned to the variable num.
It’s important to note that the assignment operator is a binary operator, meaning it requires both a
left-hand side (variable) and a right-hand side (value). The expression on the right side is evaluated
first, and then the resulting value is assigned to the variable on the left side.
The assignment operator can also be combined with other operators to perform compound
assignments. Compound assignment operators, also known as short-hand operators, provide a
concise way to combine an arithmetic operation with assignment. They allow us to perform an
arithmetic operation and assign the result to a variable in a single statement. For example: int num
= 10;
num += 5; //Equivalent to num = num + 5;
In this case, the compound assignment operator (+=) adds 5 to the current value of num and assigns
the result back to num. After the compound assignment, the variable num holds the value 15.
Precedence and Associativity of Operators
In Java, operators have different levels of precedence, which determines the order in which they are
evaluated within an expression. Operators with higher precedence are evaluated before operators
with lower precedence. If two operators have the same precedence, their evaluation order depends
on their associativity.
Here is a summary of the precedence and associativity of operators in Java, listed from highest to
lowest precedence:
Table 4.1 Operators Precedence
Precedence Operators
1 Unary +, Unary –, ++, –– and !
2 *. / and %
3 + and –
4 <. >, <= and >=
5 == and !=
6 &&
7 ||
8 ?:
9 =, +=, –=, *=, /= and %=
The associativity of most operators in Java is left-to=right, which means that operators with the
same precedence are evaluated from left to right. However, there are few exceptions:
• Assignment operators (=, +=, –=, *=, /= and %=) have right-to-left associativity.
• Conditional operator (?:) has right-to-left associativity.
It’s important to understand operator precedence and associativity when writing expressions to
ensure that the evaluation order is as intended. We can also use parentheses to override the default
precedence and explicitly define the order of evaluation within an expression.
Expressions
An expression is a combination of operators and operands. Here, operands can be variables,
constants, and method invocations that produce a value. Here are some examples of expressions:
sum = num1 + num2;
avg = sum/2; result = 9 + 10;
In Java, expressions can be categorized into several types based on their functionality and the value
they produce. Here are the main types of expressions:
1. Arithmetic Expressions
Evaluate mathematical operations and produce numeric results.
Example: int result = 5 + 3 * 2;
2. Relational Expressions
Compare values and produce a boolean result (true or false). These are typically used in
conditional statements and loops.
Example: boolean isEqual = num1 == num2;
3. Logical Expressions
Combines boolean values using logical operators.
Example: boolean result = (x > 9 && y < 10)
4. Conditional Expressions
Provide a shorthand way of comparing values in a single expression.
Example: int max = (num1 > num2) ? num1 : num2;
5. Assignment Expressions
Assign a value to a variable using the assignment operator.
Example: int grade = 9;
print( ) and println( ) Methods
print( ) and println( ) methods are used to display output to the console or terminal. Here’s an
explanation of each method:
1. print( ) Method: The print( ) method is used to display text or values to the console. It does not
automatically append a new line character after the output. It prints the output and keeps the
cursor on the same line. This means that any subsequent output will be displayed on the same
line immediately after the previous output.
Example: [Link](“Hello”);
[Link](“World”);
Output: HelloWorld
In the example above, the first print( ) method displays the text “Hello” on the console without
moving the cursor to the next line. Therefore, the next print( ) method displays the text “World”
on the same line.
2. println( ) Method: The println( ) method also is used to display text or values to the console, but
it automatically appends a new line character after the output. This means that any subsequent
output will be displayed on a new line.
Example: [Link](“Hello”);
[Link](“World”);
Output: Hello
World
In the example above, the first println( ) method displays the text “Hello” on the console and
the cursor will move to the next line. Therefore, the next println( ) method displays the text
“World” on the new line.
In summary, the print( ) method prints the output without moving the cursor to the next line, while
the println( ) method prints the output and moves the cursor to the next line.
===========================
Unit 05. Input in Java
------------------------------------------------------------------------------------------------------------------------
Initialization
Initialization refers to the process of assigning initial values to variables before the execution of a
program.
Example:
int num = 5;
In the above example, variable num has been initialized with the value 5.
Parameter
A parameter is a variable declared in the method’s declaration, which represents a value that must be
passed to the method when it is called. Parameters act as placeholder for data that will be used
within method’s block.
In Java, methods are an essential part of data processing. When defining a method, we can specify
parameters that allow us to pass values into the method for processing. Parameters help make our
code more flexible and allow us to perform operations on different data without writing separate
code for each scenario.
Example: public static void
findSquare(int num)
{
:
}
In the above example, variable num has been used as method’s parameter, which receives the value
that is passed to the method when it is called.
Introduction to Packages
Package is a collection of related classes. It provides a way to group related classes together, making
it easier to manage and organize large projects. It also helps in avoiding naming conflicts by
providing a unique namespace for classes.
To use classes from other packages, we can import them into our code using import keyword and
import statements are placed before the class declaration.
The [Link] Package
The [Link] package is a special package in Java that is automatically imported into every Java
program. It contains fundamental classes that are essential for the Java language itself and are
widely used in Java programs.
Some of the notable classes in this package include:
• String – The class representing a sequence of characters.
• System – Provides access to the system environment and I/O console. Math
– Contains mathematical methods and constants.
The [Link] package is an integral part of the Java platform and provides the core functionality
that every Java program relies on. Note, its classes are automatically available, allowing
programmers to use them without any explicit imports.
Input Streams (Scanner Class)
In Java, an input stream is a mechanism provided by the Java I/O system to read data sequentially
from a source. It represents a flow of data from which a Java program can read bytes or characters.
Input streams provide a lower-level mechanism for reading bytes from binary source, while Scanner
class offers a higher-level and more user-friendly way to read data from various sources.
The Scanner Class
The Scanner class is a utility class that allows us to read input from various sources, such as the
keyboard or files. It is part of [Link] package and provides methods for accepting various types of
inputs. We must import [Link] package to avail the methods available in Scanner class. The
keyword import is used to import a package into a program. To use Scanner class from [Link]
package, we can use one of the following statements before our class declaration:
import [Link];
or
import [Link].*;
To use the methods from Scanner class, we need to create an instance (object) of it and associate it
with an input source. Here’s an example pf creating Scanner object to read from the keyboard:
Scanner sc = new Scanner([Link]);
In this example, [Link] is passed as a parameter to the Scanner constructor, which associates the
object sc with the standard input stream (keyboard).
The following table gives some commonly used methods to accept inputs of different types:
Table 5.1 Methods of Scanner Class
Method Purpose
nextInt( ) Reads int value
nextLong( ) Reads long value
nextFloat( ) Reads float value
nextDouble( ) Reads double value
next( ) Reads String value
nextLine( ) Also reads String value
next( ).charAt(0) Reads char value
The Scanner class provides two methods for reading input as strings: next( ) and nextLine( ). The
main difference between these two methods is how they handle whitespace characters. The next( )
method reads the input until it encounters a whitespace character, excluding the whitespace
character. Where as the nextLine( ) method reads the entire line of input until it encounters a
newline character, including any whitespace characters.
The combination of next( ) method from Scanner class and charAt( ) method from String class is
used as next( ).charAt(0) to read the input as string and then retrieve the character at the first
position of that string. In simple words, next( ).charAt(0) is used to accept char input.
Types of Errors
In Java, errors can be broadly categorized into three types: compile-time errors (syntax errors),
runtime errors (exceptions) and logical errors. Let’s take a closer look at each type.
1. Compile-time errors
These errors occur during the compilation phase of a Java program. They are also known as
compilation errors or syntax errors. These errors indicate that the code violates the rules of the
Java programming language and cannot be compiled into bytecode. Some common examples of
compiler-time errors include:
• Missing semicolon at the end of a statement
• Undefined variables or methods
• Incorrect or mismatched data types
• Incorrect syntax or misspelled keywords
2. Run-time errors
These errors occur during the execution phase of a Java program. They are also known as
exceptions. These errors indicate exceptional conditions that occur during the program’s
execution, such as invalid input, division by zero. Some common examples of runtime errors
include:
• ArithmeticException (e.g., division by zero)
• InputMismatchException (e.g., string input for an int variable)
3. Logical Errors
These errors occur when the program runs without any syntax or runtime errors but produces
incorrect results. They arise due to mistakes in the program’s logic. These errors are typically
more challenging to detect, and fix compared to syntax and run-time errors.
It’s worth mentioning that errors can be handled differently depending on their type. Syntax errors
prevent the program from being compiled, while run-time errors terminate program execution
abnormally. Logical errors require careful analysis and correction of the program’s logic to produce
the desired results.
Types of Comments
Comments are non-executable statements of a program. Because they are ignored by the compiler
and do not affect the execution of the program. They are purely for human readers to understand the
code better. We can use comments to add explanatory or descriptive text to our program.
There are three types of comments in Java:
1. Single-line comments: These comments start with two forward slashes “//” and continue until
the end of the line. Anything written after “//” is considered a comment.
2. Multi-line comments: These comments start with “/*” and end with “*/”. We can use them to
write comments that span multiple lines.
3. Documentation comments: These comments are used for generating documentation
automatically. They start with “/**” and end with “*/”.
Comments are helpful for making our program more readable, explaining complex sections. It’s
good practice to include comments that provide a clear explanation of our code’s functionality,
especially for complex or non-obvious parts of program.
===========================
Unit 06. Mathematical Library Methods
------------------------------------------------------------------------------------------------------------------------
Introduction to package [Link] [default]
The [Link] package is a special package in Java that is automatically imported into every Java
program. It contains fundamental classes that are essential for the Java language itself and are
widely used in Java programs.
Some of the notable classes in this package include:
• String – The class representing a sequence of characters.
• System – Provides access to the system environment and I/O console.
• Math – Contains mathematical methods and constants.
The [Link] package is an integral part of the Java platform and provides the core functionality
that every Java program relies on. Note, its classes are automatically available, allowing
programmers to use them without any explicit imports.
Methods of Math class
The Math class provides a set of static methods for performing common mathematical operations.
The following table gives some commonly used methods to from the Math class:
Table 6.1 Methods of Math Class
Method Return Type Purpose
max( ) int / double Returns the larger of two values.
min( ) int / double Returns the smaller of two values.
sqrt( ) double Returns the square root of the specified value.
abs( ) int / double Returns the absolute value of a value.
cbrt( ) double Returns the cube root of the specified value.
pow( ) double Returns the value of first value raised to the power of the second
value.
ceil( ) double Returns the smallest value, which is greater than or equal to the
specified value.
floor( ) double Returns the largest value, which is less than or equal to the specified
value.
round( ) int / long Returns the specified value to nearest integer.
random( ) double Returns a value, greater than or equal to 0.0 and less than 1.0.
Did you know?
In Java [Link] is a static final double constant. It represents the value of pi, which is
approximately 3.141592653589793. You can use it in your program to perform calculations
involving the mathematical constant pi without needing to define it yourself.
Unit 07. Conditional constructs in Java
------------------------------------------------------------------------------------------------------------------------
Introduction
Conditional constructs in Java allow you to make decisions in your code based on certain
conditions. These constructs help you control the flow of your program by executing different
blocks of code depending on whether a condition is true or false. There are mainly two types of
conditional constructs in Java: if statements and switch statements.
The if Statement
In Java, the if statement is used for conditional branching. It allows us to execute a block of code
only if a certain condition is true. The basic syntax of the if statement is as follows:
if(condition)
//Code to be executed if the condition is true
Here, condition is a boolean expression. If the condition evaluates to true, the code will be
executed; otherwise, it will be skipped.
Additionally, we can use an else block to specify a block of code that should be executed if the if
condition is false. Here's an example:
if(num > 9)
[Link](“Number is greater than 9”);
else
[Link](“Number is not greater than 9”);
In this example, if the value of num is greater than 9, the first [Link] statement will be
executed; otherwise, the statement after the else will be executed.
We can also chain multiple if-else statements to handle multiple conditions. Here's an example:
if(num > 0)
[Link](“Positive Number”);
else if(num < 0)
[Link](“Negative Number”);
else
[Link](“Zero”);
In this example, the code checks whether the num variable is positive, negative, or zero and prints
the corresponding message.
We can also have nested if statements, where one if statement is inside another. This allows for
more complex conditional logic.
The switch Statement
The switch statement in Java allows us to choose between multiple code blocks to be executed
based on the value of an expression. It is a cleaner and more concise alternative to using multiple if-
else statements when we have a series of conditions to evaluate. The syntax of the switch statement
is:
switch(expression)
{
case value1:
//Code to be executed if expression matches value1
break;
case value2:
//Code to be executed if expression matches value2
break;
//additional cases as needed
default:
//Code to be executed if none of the cases match
}
Components of switch Statement
Expression: The expression is the value that we want to evaluate. It can be of byte, short, int, char
or String type. The result of this expression is compared with the values specified in the case labels.
case: This represents a possible value that the expression might have. If the expression matches
value1, the code block following that case will be executed. We can have multiple cases.
Code Blocks: The code block associated with each case label contains the statements to be
executed if the corresponding case is matching. If a case is matched, the code inside that case is
executed until a break statement is encountered.
break: The break statement is used to exit the switch statement. If a break statement is not used
after a case, the control will fall through to the next case. It is crucial to include break to prevent
this fallthrough behaviour.
default: It is an optional block that is executed if none of the cases match. It is similar to the else
statement in an if-else structure. Including a default is not mandatory, but it can provide a fallback
option if none of the specified cases match.
Example for switch Statement
switch(dayOfWeek)
{
case 1:
[Link](“Monday”);
break;
case 2:
[Link](“Tuesday”); break;
case 3:
[Link](“Wednesday”);
break;
//additional cases as needed
default:
[Link](“Unknown day”);
}
In this example, if dayOfWeek is 3, it will print “Wednesday” because that’s the case that matches.
If none of the cases match, it will print “Unknown day” due to the default block.
Notes:
• The switch statement can be more efficient than a series of if-else statements when we have a
large number of possible values.
• Each case value must be unique, and the expression type must be compatible with the case
values.
• The break statement is crucial to prevent fall-through behaviour. Each case should end with a
break, or the control will continue to the next case.
• The default is optional, but it provides a way to handle values not covered by specific cases.
[Link](0)
In Java, the [Link](0) statement is used to terminate the Java Virtual Machine (JVM) with an
exit code of 0. The argument passed to [Link]( ) represents the exit status of the program.
Conventionally, a status code of 0 indicates successful termination, while non-zero values typically
indicate an error or abnormal termination.
It’s worth noting that in most cases, we don't need to explicitly call [Link](0) to end a Java
program. However, there might be cases where we want to explicitly terminate the program, such as
in the event of an error, or in situations where we want to ensure a specific exit code is returned.
Keep in mind that forcefully terminating the program using [Link]() can skip cleanup code, so
it should be used judiciously.
===========================