Chapter 3

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 43

ECEG – 3142: Object Oriented Programming (OOP)

(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

Chapter 3
Fundamental Programming Structures
In Chapter 1 you learned how to create, compile, and run a Java program. Now you will learn how to solve practical problems
programmatically. At this point, we are assuming that you successfully installed the JDK and were able to run the sample
programs. It’s time to start programming. This chapter shows you how the basic programming concepts are implemented in
Java. You will learn elementary programming using Primitive Data Types, Variables, Constants, Operators, Expressions, Flow
Control Structures and Simple Console I/O.

3.1. A Simple Java Program


Let us begin with a simple Java program that displays the message “Welcome to Java!” on the console. Console
refers to text entry and display device of a computer.

/**
* A Simple Java program, which
* simply prints “Welcome to Java!".
*/
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}

The expected output is:

Welcome to Java!

Discussion - Welcome.java
Now that you've seen a basic template which used to construct a simple Java application program. The
source code, which defines a class called "Hello". You might be wondering how it works. The following
explanation will provide you with a basic understanding of the code, but the deeper implications will only
become apparent after you've finished reading the rest of the tutorial.

Source Code Comments


The following bold text defines the comments of the "Hello World!" application.
/**
* A Simple Java program, which
* simply prints “Welcome to Java!".
*/

Comments help programmers to communicate and understand the program. They are not programming
statements and thus are ignored by the compiler. They are NOT executable, but they provide useful
explanation and documentation. I strongly suggest that you write comments liberally to explain your thought
and logic. The Java programming language supports three kinds of comments (check chapter 2).

DBU, Department of Electrical and Computer Engineering, 3th Year 1


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

Class Definition
The following bold text begins the class definition block for the "Welcome" application. It is the most basic
form of a class definition.
Public class Welcome {
……
}
Classes are the building blocks with which all Java applications and applets are built. Everything in a Java
program must be inside a class. Chapter 2 provides an overview of classes in general, and Chapter 4 discusses
classes in detail.

Although we spend a lot more time on classes in the next chapter, for now think of a class as a container for
the program logic that defines the behavior of an application. For now it is enough to know that every
application begins with a class definition.

Every Java program begins with a class declaration in which the keyword class is followed by the class
name.
o The keyword class begins the class definition for a class
Following the keyword class is the name of the class. Each class has a name. In this example, the class
name is Welcome.
o The rules for class names: Names must begin with a letter, and after that, they can have any
combination of letters and digits. The length is essentially unlimited. You cannot use a Java
reserved word (such as public or class) for a class name.
o Class Naming Convention: class names are nouns that start with an uppercase letter. If a name
consists of multiple words, use an initial uppercase letter in each of the words. (This use of
uppercase letters in the middle of a word is sometimes called “camel case” or, self-
referentially, “CamelCase.”)
o The source file name for the source code must have exactly the same name as the public class
name, with the extension .java appended. Thus, you must store this code in a file called
FirstSample.java. (Again, case is important—don’t use firstsample.java)
The braces {......} encloses the body of the class. The code for each class appears between the opening
and closing curly braces marked in bold above.
The main Method
The following bold text begins the definition of the main method: it defines the so-called main() method,
which is the entry point for program execution.
Public static void main(String[] args) {
……
}

In order to run a class, the class must contain a method named main. The program is executed from
the main method. A method is a construct that contains statements.
The words public, static and void are keywords. For now, don’t worry about these keywords, just think
of them as part of what you need to get a Java program to compile.
The main method accepts a single argument: an array of elements of type String. This array is the
mechanism through which the runtime system passes information to your application. For example:
Each string in the array is called a command-line argument.
Again, the braces {......} encloses the body of the method, which contains programming statements.
The main method is similar to the main function in C and C++; it's the entry point for your application
and will subsequently invoke all the other methods required by your program.

DBU, Department of Electrical and Computer Engineering, 3th Year 2


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

Statements
Statements are roughly equivalent to sentences in natural languages. A programming statement forms a
complete unit of execution. It performs a single piece of programming action.

In Java, every statement must end with a semicolon (;), known as the statement terminator.
Statements can span multiple lines if need be. I.e. carriage returns do not mark the end of a statement.
You can also write multiple statements in a single line.
The body of the main method in the above program contains a statement that outputs a single line of
text to the console. The System.out.println statement. This statement prints a message "Welcome to
Java! " to the console
Block
A block is a group of zero or more statements enclosed by a pair of braces {}. This group of statements is
treated as one single unit.

A pair of braces in a program forms a block that groups the program’s components.
In Java, each block begins with an opening brace ({) and ends with a closing brace (}).
It can be used anywhere
There are two blocks in the above program.
o One contains the body of the class Hello: Every class has a class block that groups the data and
methods of the class.
o The other contains the body of the main() method. Every method has a method block that
groups the statements in the method.
There is no need to put a semi-colon after the closing brace.
Blocks can be nested, meaning that one block can be placed within another
Note:

Java source programs are case sensitive. It would be wrong, for example, to replace main in the program with
Main. The filename, which is the same as the class name, is also case-sensitive.

Reserved words, or keywords, have a specific meaning to the compiler and cannot be used for other purposes
in the program. Other reserved words in this program are public, static, and void.

Whitespaces: Blank, tab, and newline are collectively called whitespace. Extra whitespaces are ignored, i.e.,
only one whitespace is needed to separate the tokens. Nonetheless, extra whitespaces improve the
readability, and I strongly suggest you use extra spaces and newlines to improve the readability of your code.

Like any programming language, Java has its own syntax, and you need to write code that obeys the syntax
rules. If your program violates the rules—for example if the semicolon is missing, a brace is missing,the Java
compiler will report syntax errors. Try to compile the program with these errors and see what the compiler
reports.

If your program has compilation errors, you have to modify the program to fix them, then recompile it. If your
program has runtime errors or does not produce the correct result, you have to modify the program, recompile
it, and execute it again.

3.2. Variables
A computer program manipulates (or processes) data. A variable is a storage location that stores a piece of
data for processing. It is called variable because you can change the value stored inside. Variable is name of

DBU, Department of Electrical and Computer Engineering, 3th Year 3


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

reserved area allocated in memory. In other words, it is a name of memory location. It is a combination of
"vary + able" that means its value can be changed.

More precisely, a variable is a named storage location, which stores a value of a particular data type.
In other words, a variable has a name, a type and stores a value of that particular type.

 A variable has a name (aka identifier):


- A variable name is an identifier needed to uniquely identify each variable,
- It is used to assign a value to the variable (e.g., radius = 1.2), as well as to retrieve the
value stored (e.g., radius * radius * 3.14159265).
 A variable has a type: Examples of type are: The concept of type was introduced into the early
programming languages to simplify interpretation of data.
 A variable can store a value of the declared type: It is important to take note that a variable in
most programming languages is associated with a type, and can only store value of that
particular type. For example, a int variable can store an integer value such as 123, but NOT a
real number such as 12.34, nor texts such as "Hello".
Variable Declaration and Initializing
To use a variable, you need to first declare its name and type, and an optional initial value. Variables are for
representing data of a certain type. The variable declaration tells the compiler to allocate appropriate memory
space for the variable based on its data type.

Declaring a Single Variable

You can declare a variable in one of the following syntaxes:

type varName; // Declaring an uninitialized variable of a type


type varName = initialValue; // Declaring & initializing a variable at the same time

Take note that:

 Each variable declaration statement begins with a type, Here type is one of Java's primitive data
types (such as int, float, double, char, etc.) or the name of a class or interface and varName is the
name of the variable.
 By convention, variable names are in lowercase. If a name consists of several words, concatenate all
of them and capitalize the first letter of each word except the first.
o Examples of variable names are radius and interestRate.
 Each statement is terminated with a semi-colon (;).
 The symbol '=', known as the assignment operator, can be used to assign an initial value to a
variable, in a declaration statement.
 In Java, you can declare a variable anywhere inside your program, as long as it is declared before it is
being used.
 Each variable can only be declared once.
 Once a variable is declared, you can assign and re-assign a value to that variable, via the assignment
operator '='.

DBU, Department of Electrical and Computer Engineering, 3th Year 4


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

 Once the type of a variable is declared, it can only store a value of that particular type. For example,
an int variable can hold only integer such as 123, and NOT floating-point number such as -2.17 or
text string such as "Hello".
 Once declared, the type of a variable CANNOT be changed.
Here are some examples of variable declarations:

int sum; // Declare a variable named "sum" of the type "int" for storing an integer
double radius; // Declare radius to be a double variable
char x; // Declare a variable named "x" of the type "char" for storing a character
int height = 20; // Declare an "int" variable, and assign an initial value
String msg = "Hello"; // Declare a "String" variable, and assign an initial value

The examples use the data types int, double, and char. Later you will be introduced to additional data types.

Variables often have initial values. You can declare a variable and initialize it in one step. Consider, for instance,
the following code:
int count = 1;

This is equivalent to the next two statements:


int count;
x = 1;

Declaring Multiple Variables

Multiple variables of the same type can be declared and initialized in one statement using comma as a
delimiter. If variables are of the same type, you can declare them in one of the following syntaxes:

type varName1, varName2,…; // Declare multiple variables of the SAME type, with out initializing
type varName1 = iniValue1, varName2=iniValue2, …; // Declare & initialize multiple variables

Take note that:

 Each variable declaration statement begins with a type, and applicable for only that type. That is,
you cannot mix 2 types in one variable declaration statement.
 You can also use a shorthand form to declare and initialize variables of the same type together. For
example, int i = 1, j = 2;
Here are some examples of variable declarations:

int sum1, sum2; // Declare 2 “int” variables named "sum1" and “sum2”
double x=2.12, y=32.11; // Declare 2 double variables and assign an initial value

Variable Assignment

After a variable is declared, you can assign a value to it by using an assignment statement. In Java, the equal
sign (=) is used as the assignment operator. The syntax for assignment statements is as follows:

varName = expression;

DBU, Department of Electrical and Computer Engineering, 3th Year 5


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

Here,

- varName: is the name of the variable, A variable must be declared before it can be assigned a
value.
- expression can be a literal value or a computation involving values, variables, and operators that
evaluates to a value
For example, consider the following code:

int x; // Declare variable x


int y=2; // Declare and initialize variable y
double radius, area; // Declare radius and area to be double variables
x=3; // Assign 3 to variable x
radius = 1.0; // Assign 1.0 to variable radius
x = 5 * (3 / 2) + 3 * 2; // Assign the value of the expression to x
x = y + 1; // Assign the addition of y and 1 to x
area = radius * radius * 3.14159; // Compute area

In Java, an assignment statement is essentially an expression that evaluates to the value to be assigned to the
variable on the left-hand side of the assignment operator. For this reason, an assignment statement is also
known as an assignment expression. For example, the following statement is correct:

int x;
System.out.println(x=1);

Which is equivalent to:

int x;
x=1;
System.out.println(x);

The following statement is also correct:

int i, j, k;
i=j=k=1;
Which is equivalent to:

int i, j, k;
k=1;
j=k;
i=j;

Note That:
- A variable must be declared before it can be assigned a value. A variable declared in a method
must be assigned a value before it can be used.
- To assign a value to a variable, the variable name must be on the left of the assignment operator.
Thus, 1 = x; would be wrong.

DBU, Department of Electrical and Computer Engineering, 3th Year 6


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

-In mathematics, x = 2 * x + 1 denotes an equation. However, in Java, x = 2 * x + 1 is an assignment


statement that evaluates the expression 2 * x + 1 and assigns the result to x.
- In an assignment statement, the data type of the variable on the left must be compatible with the
data type of the value on the right. For example, int x = 1.0 would be illegal, because the data type
of x is int. You cannot assign a double value (1.0) to an int variable without using type casting. Type
casting is introduced later in “Type Conversions.”
More examples on variables,

int number; // Declare a variable named "number" of the type "int" (integer).
number = 99; // Assign an integer value of 99 to the variable "number".
number = 88; // Re-assign a value of 88 to "number".
number = number + 1; // Evaluate "number + 1", and assign the result back to "number".
int sum = 0; // Declare an int variable named "sum" and assign an initial value of 0.
sum = sum + number; // Evaluate "sum + number", and assign the result back to "sum", i.e. add number into sum.
int num1 = 5, num2 = 6; // Declare and initialize 2 int variables in one statement, separated by a comma.
double radius = 1.5; // Declare a variable named "radius", and initialize to 1.5.
String msg; // Declare a variable named msg of the type "String".
msg = "Hello"; // Assign a double-quoted text string to the String variable.
int number; // ERROR: The variable named "number" has already been declared.
sum = 55.66; // ERROR: The variable "sum" is an int. It cannot be assigned a double.
sum = "Hello"; // ERROR: The variable "sum" is an int. It cannot be assigned a string.

3.3. Constants
The value of a variable may change during the execution of a program, but a named constant or simply
constant represents permanent data that never changes. For example in a program which computes area of
a circle, pi (π=3.14159) is a constant. So, if you use it frequently, you don’t want to keep typing 3.14159;
instead, you can declare a constant for it.

The syntax for declaring a constant is as follow:

final datatype CONSTANTNAME = VALUE;


Here,

- The word final is a Java keyword for declaring a constant. It indicates that you can assign to
the variable once, and then its value is set once and for all.
- datatype is one of Java's primitive data types (such as int, float, double, char, etc.) or the name
of a class or interface.
- CONSTANTNAME: is the name of the constant. By convention, constants are named in
uppercase: such as PI, not pi or Pi .
For Example:

final double PI = 3.14159;

Note That:
- A constant must be declared and initialized in the same statement.
- There are three benefits of using constants:
 You don’t have to repeatedly type the same value.
 If you have to change the constant value (e.g., from 3.14 to 3.14159 for PI), you
need to change it only in a single location in the source code;

DBU, Department of Electrical and Computer Engineering, 3th Year 7


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

 A descriptive name for a constant makes the program easy to read.

3.4. Data Types and Values


3.4.1. Overview
The Java programming language is a statically and strongly typed language. This means, every variable and
every expression has a type, and every type is strictly defined.

 Statically-typed, which means that all variables must first be declared before they can be used. This
involves stating the variable's type and name, as you've already seen.
- Every variable and every expression has a type that is known at compile time, (every type is
strictly defined).
 Strongly Typed: all assignments, expressions and parameters are checked for type compatibility.
- The Java compiler checks all expressions and parameters to ensure that the types are
compatible. There are no automatic coercions or conversions of conflicting types as in some
languages. Any type mismatches are errors that must be corrected before the compiler will
finish compiling the class.
- Types limit the values that a variable can hold or that an expression can produce, limit the
operations supported on those values, and determine the meaning of the operations.
 Strong static typing helps detect errors at compile time.
The types of the Java programming language are divided into two categories: primitive types and reference
types.

 Primitive data types are predefined by the language and named by a keyword. They are also
commonly referred to as simple types. They represent single values—not complex objects. Although
Java is otherwise completely object-oriented, the primitive types are not.
 Reference types include class types, interface types, and array types. Class objects and various type of
array variables come under reference data type. Reference variables are created using defined
constructors of the classes. They are used to access objects. These variables are declared to be of a
specific type that cannot be changed. A reference variable can be used to refer any object of the
declared type or any compatible type. Default value of any reference variable is null.
There are, correspondingly, two kinds of data values that can be stored in variables, passed as arguments,
returned by methods, and operated on: primitive values and reference values.

3.4.2. Primitive Data Types


Primitive data types are predefined by the language and named by its reserved keywords. They are also
commonly referred to as simple types.

 The primitive types represent single values—not complex objects. Although Java is otherwise
completely object-oriented, the primitive types are not. The reason for this is efficiency.
 You can use these types as-is, or to construct arrays or your own class types. Thus, they form the
basis for all other types of data that you can create.
 They are defined to have an explicit range and mathematical behavior.
o Every data type has a range of values. The compiler allocates memory space for each
variable or constant according to its data type.
o A variable's data type determines the values it may contain, plus the operations that may be
performed on it.

DBU, Department of Electrical and Computer Engineering, 3th Year 8


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

 There are eight primitive data types supported by Java: byte, short, int, long, char, float, double, and
boolean.
 The eight primitive data types supported by the Java programming language can be placed in four
groups:
o Integer types: This group includes byte, short, int, and long, which are for whole-valued
signed numbers.
o Floating-point/ Real types: This group includes float and double, which represent numbers
with fractional precision.
o Character types: This group includes char, which represents symbols in a character set, like
letters and numbers.
o Boolean type: This group includes boolean, which is a special type for representing
true/false values

Type Default
Value Size Range
Name Value
byte
8-bit signed two's complement 8-bit −128 through +127 0
integers
short
16-bit signed two's complement 16-bit −32,768 through +32,767 0
integers
int
32-bit signed two's complement 32-bit −2,147,483,648 through 0
integers +2,147,483,647
64-bit signed two's complement 64-bit −9,223,372,036,854,775,808 0L
long integers through
+9,223,372,036,854,775,807
float
32-bit IEEE 754 floating-point 32-bit ±1.401298E−45 through 0.0f
numbers ±3.402823E+38
64-bit IEEE 754 floating-point 64-bit ±4.94065645841246E−324 0.0
double numbers through
±1.79769313486232E+308
boolean Boolean literals 1-bit true or false false
16-bit unsigned integers 16-bit '\u0000' through '\uFFFF' '\u0000'
char
representing UTF-16 code units

Table 3.1: the eight primitive data types of Java

3.4.2.1. Integer Types


 Java provides the four integer types shown in Table 3.1.
 The values of integer types are signed two's complement integer. I.e. numbers without fractional
parts. whole numbers
o All of these are signed, positive and negative values. Negative values are allowed.
o All the integer types are stored internally as two's complement.
 A positive number is stored as its corresponding binary representation.
 A negative number: the corresponding positive binary number are inverted and then
1 is added to the result.
 For example, the byte representation of the number 3 will be 00000011. The byte
representation of the number –4 is 11111100.
 The byte and short types are mainly intended for specialized applications, such as low-level file
handling, or for large arrays when storage space is at a premium.

DBU, Department of Electrical and Computer Engineering, 3th Year 9


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

 The most commonly used integer type is int. it is often the best choice when an integer is needed.
The reason is that when byte and short values are used in an expression they are promoted to int
when the expression is evaluated. (Type promotion is described later in this chapter.)
 The range of a long is quite large. This makes it useful when big, whole numbers are needed.
o It is useful for those occasions where an int type is not large enough to hold the desired
value.
 For example, in a program that computes the number of miles that light will travel in
a specified number of days. If you want to represent the number of inhabitants of
our planet
 Note: A long literal value has an l or L suffix.
o Hence, To assign an integer literal value to a variable of a long type, appending L or l suffix to
the literal,
o For example, long lvar = 123456789L;
 Literal values of the integral type’s byte, short, int, and long can be expressed by these number
systems:
o Decimal: Base 10, whose digits consists of the numbers 0 through 9; this is the number
system you use every day, values are assigned as decimal values by default, as in
o Binary: To assign a binary value, prefix the value with 0b (0b followed by a binary number)
o Octal: To assign an octal value, prefix the value with a zero. (0 followed by an octal number)
For example, 010 is 8. Naturally, this can be confusing, and we recommend against the use
of octal constants.
o Hexadecimal: To assign a hexadecimal value, prefix the value with a zero then an x (0x
followed by a hexadecimal number)
 For general-purpose programming, the decimal system is likely to be the only number system you'll
ever use. However, if you need to use another number system, the following example shows the
correct syntax.
// The number 8, in decimal // The number 8, in binary
byte var1=8; byte x=0b1000;
short var2=8; int x2=0b1000;
int var3=8; long x3= 0b1000L;
long var4=8L; // The number 8, in hexadecimal
// The number 8, in octal int num=0x8;
int y= 010; long num2=0x8L;
long m=010L;

3.4.2.2. Floating-Point Types


 The floating-point types denote numbers with fractional parts. The two floating-point types are shown
in Table 3–1.
 Floating-point numbers, also known as real numbers, are used when evaluating expressions that
require fractional precision.
o 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.
 Java implements the standard (IEEE–754) set of floating-point types and operators.
 The two kinds of floating-point types, float and double, represent single- and double-precision
numbers, respectively.

DBU, Department of Electrical and Computer Engineering, 3th Year 10


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

 The type float specifies a single-precision 32-bit IEEE 754 floating point value that uses 32 bits of
storage.
o Single precision is faster on some processors and takes half as much space as double precision,
but will become imprecise when the values are either very large or very small.
o Variables of type float are useful when you need a fractional component, but don’t require a
large degree of precision.
o For example, float can be useful when representing dollars and cents
o This data type should never be used for precise values, such as currency.
o Use a float (instead of double) if you need to save memory in large arrays of floating point
numbers.
o Note: When a literal value is assigned to a float variable, the value must be suffixed by an f or
F, for example
 The double data type is a double-precision 64-bit IEEE 754 floating point. When you need to maintain
accuracy over many iterative calculations, or are manipulating large-valued numbers, double is the
best choice. By default, literal floating point numbers are of type double, but we can use a d or D suffix.
So both the following are valid:
double x=7.5;
double y=7.5D;
double n=7.5d;
3.4.2.4. Character Type
The character data type, char, is used to represent a single character. It can contain any Unicode (UTF-16)
characters.

 The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and
a maximum value of '\uffff' (or 65,535 inclusive). The range of a char is 0 to 65,536. There are no
negative chars.
 A character literal is a single character enclosed in single quotation marks.
Example of char variables:
char x=65;
char y=’A’;
char x2=’\u0041’;

3.4.2.5. The Boolean Type


The boolean type has two values, false and true. It is used for evaluating logical conditions. You cannot convert
between integers and boolean values.

This data type represents one bit of information, but its "size" isn't something that's precisely defined.

NOTE: In C++, numbers and even pointers can be used in place of boolean values. The value 0 is equivalent to
the bool value false, and a non-zero value is equivalent to true. This is not the case in Java

You can also compare characters. Comparing characters is the same as comparing their Unicodes. For example,
'a' is larger than 'A' because the Unicode of 'a' is larger than the Unicode of 'A' .

A variable that holds a Boolean value is known as a Boolean variable. The boolean data type is used to declare
Boolean variables. A boolean variable can hold one of the two values: true and false. For example, the
following statement assigns true to the variable.

DBU, Department of Electrical and Computer Engineering, 3th Year 11


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

true and false are literals, just like a number such as 10. They are reserved words and cannot be used as
identifiers in your program.

3.5. The String Type


In addition to the eight primitive data types listed above, the Java programming language also provides
special support for character strings via the java.lang.String class. String is actually a predefined class in the
Java library.

 The String class is not technically a primitive data type, but considering the special support given to it
by the language. The String type is not a primitive type. It is known as a reference type. Any Java
class can be used as a reference type for a variable.
 Enclosing your character string within double quotes will automatically create a new String object;
for example, String s = "this is a string";.
 String objects are immutable, which means that once created, their values cannot be changed.
 For the time being, you need to know only how to declare a String variable, how to assign a string to
the variable, and how to concatenate strings.
o The char type represents only one character. To represent a string of characters, use the
data type called String. For example, the following code declares the message to be a string
with value “Welcome to Java”. String message = "Welcome to Java";
o Concatenation: Java, like most programming languages, allows you to use the sign to join
(concatenate) two strings. The plus sign (+) is the concatenation operator if one of the
operands is a string. If one of the operands is a nonstring (e.g., a number), the nonstring
value is converted into a string and concatenated with the other string. Here are some
examples:
o The shorthand += operator can also be used for string concatenation. For example, the
following code appends the string “and Java is fun” with the string “Welcome to Java” in
message.
o To read a string from the console, invoke the next() method on a Scanner object. The next()
method reads a string that ends with a whitespace character. You can use the nextLine()
method to read an entire line of text. The nextLine() method reads a string that ends with
the Enter key pressed.

3.6. Basic Console I/O


To make our example programs more interesting, we want to accept input and properly format the program
output. Java programs perform I/O through streams. A stream is an abstraction that either produces or
consumes information. A stream is linked to a physical device by the Java I/O system. All streams behave in
the same manner, even if the actual physical devices to which they are linked differ. Thus, the same I/O classes
and methods can be applied to any type of device. This means that an input stream can abstract many different
kinds of input: from a disk file, a keyboard, or a network socket. Likewise, an output stream may refer to the
console, a disk file, or a network connection. Java implements streams within class hierarchies defined in the
java.io package. The java.io package provides a large number of classes to handle the different physical I/O
implementations.

 Input is any information that is needed by your program to complete its execution. There are many
forms that program input may take. Some programs use GUI (Graphical User Interface) components
to accept inputs from users. Some other programs get their inputs from a terminal window, a file, a
network connection, or from input devices.

DBU, Department of Electrical and Computer Engineering, 3th Year 12


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

 Output is any information that the program must convey to the user. The information you see on the
screen is being output by one or more programs that are currently running on your computer. There
are many forms of programs outputs.

We will cover only some of the I/O streams for performing I/O from command line. If you want to know more
about any stream, consult the Sun API documentation.

A program is often run from the command line and interacts with the user in the command line
environment. The Java platform supports this kind of interaction in two ways: through the Standard
Streams and through the Console.

3.6.1. Standard Streams


Standard Streams are a feature of many operating systems. By default, they read input from the keyboard and
write output to the display. They are commonly used to provide input to, and output from Java applications.
They also support I/O on files and between programs, but that feature is controlled by the command line
interpreter, not the program.

The Java platform supports three Standard Streams:

 Standard Output: accessed through System.out,


 Standard Input: accessed through System.in, and
 Standard Error: accessed through System.err.
3.6.1.1. Standard Output: Writing Console Output
The System.out object is known as the standard output object. Java uses System.out to refer to the
standard output device. By default the output device is the display monitor. It is often used for writing output
to the console (command window) from console programs as a way to display the result of their execution to
the user.

- In Microsoft Windows, the command window is the Command Prompt.


- In UNIX/Linux/Mac OS X, the command window is called a terminal window or a shell.
- Many programmers call it simply the command line.
Console output is most easily accomplished with print( ) and println( ), described earlier, which are used in
most of the examples in this book. These methods are defined by the class PrintStream (which is the type of
object referenced by System.out).

A. The print() Method


- Is a built-in output subroutines which prints the argument passed to it and retains the cursor at
the same line.
- It is used with one parameter, where the parameter can be a value of any of the primitive types
(byte, short, int, long, float, double, char, or boolean), a String type, or indeed any object.
- To perform console output, i.e., to print output to the “standard output stream”(that is, the
console window), we can call the print() method, as shown below:
System.out.print(parameter);

Where, the parameter can be any expression whose value is of any type whatsoever.
The expression can be a constant, a variable, or even something more complicated
such as 2*distance*time.
Examples:
System.out.print(“Any String”);
System.out.print(12);
System.out.print(12.65);

DBU, Department of Electrical and Computer Engineering, 3th Year 13


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

System.out.print(‘A’);
int x=33;
System.out.print(x);
System.out.print(2*x);
System.out.print(“hello”+x);
System.out.print(); // Wrong Statement!

- Note: There is no version of System.out.print without parameters.


B. The println() Method
- It is a method which prints the argument passed to it and throws the cursor to the next line after
displaying the result.
- It is similar to print() method except that it moves the cursor to the next line after printing the
result.
- It is used when you want the result in two separate lines. If we want the result in two separate
lines, then we should use the println() method.
- To perform console output using the println() method, call it as shown below:
System.out.println(parameter);

Where, the parameter can be any expression whose value is of any type whatsoever.
The expression can be a constant, a variable, or even something more complicated
such as 2*distance*time.
- Note: There is a version of System.out.println that has no parameters. This version simply outputs
a carriage return, and nothing else. A subroutine call statement for this version of the subroutine
looks like “System.out.println(); ”, with empty parentheses.
o Hence, “System.out.println(x);” is exactly equivalent to
“System.out.print(x); System.out.println();”, the carriage return
comes after the value of x.
Difference between print() and println() methods

The difference between System.out.print and System.out.println is that the println version outputs a carriage
return after it outputs the specified parameter value. Both methods are used to display the results on the
monitor.

 The print() method displays the result on the console and retains the cursor in the same line.
o It works only with an argument.
 The println() method also displays the result on the console but moves the cursor to the next line.
o It can also work without arguments.
Examples
1.

public class Example{


public static void main(String[] args){

System.out.print("Hello Java!");
}
}
The expected output:

Hello Java!

DBU, Department of Electrical and Computer Engineering, 3th Year 14


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

2.

public class Example{


public static void main(String[] args){

System.out.print("Hello");
System.out.print(" Java!");
}
}
The expected output:

Hello Java!

3.

public class Example{


public static void main(String[] args){

System.out.println("Hello Java!");
}
}
The expected output:

Hello Java!

4.

public class Example{


public static void main(String[] args){

System.out.println("Hello");
System.out.println("Java!");
}
}
The expected output:

Hello
Java!

3.6.1.2. Standard Input: Reading Input from the Console


The System.in object is the "standard" input stream. This stream is already open and ready to supply input
data. Typically this stream corresponds to keyboard input or another input source specified by the host
environment or user. It is an InputStream which is typically connected to keyboard input of console programs.

DBU, Department of Electrical and Computer Engineering, 3th Year 15


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

- In other words, if you start a Java application from the command line, and you type something on
the keyboard while the console (or terminal) has focus, the keyboard input can typically be read
via System.in from inside that Java application.
- However, Reading from the “standard input stream” isn’t quite as simple. Console input is not
directly supported in Java, but you can use the Scanner class to create an object to read input from
System.in.
The steps for reading Input from the Console using the Scanner class:

1. The Scanner class is defined in the java.util package. Whenever you use a class that is not defined
in the basic java.lang package, you need to use an import directive.
- So, at the beginning of the program, put the following import statement:
import java.util.Scanner; // or
import java.util.*;
2. Then construct a Scanner that is attached to System.in. You can create a Scanner object as
follows:
Scanner input = new Scanner(System.in);
Here, input is a variable whose type is Scanner. You can use any valid
variable name.
3. Display a prompt to the user for the desired input, as:
System.out.print(“Please Enter Some Data:”);
4. Use the scanner object to read input from the user. You can use the methods in the Table below
to read various types of input.
5. Now you can do anything with the input that you need to.
Table: Methods for Scanner Objects
Method Description
nextByte() reads an integer of the byte type
nextShort() reads an integer of the short type
nextInt() reads an integer of the int type
nextLong() reads an integer of the long type
nextBoolean() reads a boolean literal
nextFloat() reads a number of the float type
nextDouble() reads a number of the double type
next() reads a string that ends before a whitespace character
nextLine() reads a line of text (i.e., a string ending with the Enter key pressed)

Example:

import java.util.Scanner; // Don’t forget to import the Scanner class


public class Example{
public static void main(String[] args){
String txt;
int num;
double num2;
boolean b;

// Create a Scanner object

DBU, Department of Electrical and Computer Engineering, 3th Year 16


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

Scanner input = new Scanner(System.in);

System.out.print("Enter a Text: ");


txt=input.nextLine();
System.out.print("Enter a number: ");
num=input.nextInt();
System.out.print("Enter a double: ");
num2=input.nextDouble();
System.out.print("Enter a boolean value: ");
b=input.nextBoolean();

System.out.println("Your Inputs are: ");


System.out.println("txt="+txt);
System.out.println("num="+num);
System.out.println("num2="+num2);
System.out.println("b="+b);
}
}
The expected output:

Enter a Text: Hello


Enter a number: 12
Enter a double: 12.5
Enter a boolean value: true
Your Inputs are:
txt=Hello
num=12
num2=12.5
b=true

3.7. A Closer Look at Literals


Literals were mentioned briefly in Chapter 2. Now that the built-in types have been formally described, let’s
take a closer look at them.

A literal is a constant value that appears directly in a program. It is the source code representation of a fixed
value; literals are represented directly in your code without requiring computation. As shown below, it's
possible to assign a literal to a variable of a primitive type: For example, 34, 0.305, ‘A’, and “Hello” are
literals in the following statements:

int num = 34;


double x=0.305;
byte b = 34;
char c=’A’;
String msg=”Hello”;

3.7.1. Integer Literals


An integer literal can be assigned to an integer variable as long as it can fit into the variable. A compile error
will occur if the literal is too large for the variable to hold. The statement byte b = 128, for example, will cause
a compile error, because 128 cannot be stored in a variable of the byte type. (Note that the range for a byte
value is from to 127.)

DBU, Department of Electrical and Computer Engineering, 3th Year 17


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

- An integer literal is assumed to be of the int type, whose value is between (-2147483648) and
(2147483647).
- Values of the integral type’s byte, short, int, and long can be created from int literals.
- Values of type long that exceed the range of int can be created from long literals.
 To denote an integer literal of the long type, append the letter L or l to it (e.g., 2147483648L).
L is preferred because l (lowercase L) can easily be confused with 1 (the digit one).
- Integer literals can be expressed by different number systems: decimal, binary, octal and hexadecimal.
 By default, an integer literal is a decimal integer number.
 To denote a binary integer literal, prefix the binary value with 0b (zero b).
 To denote an octal integer literal, use a leading 0 (zero).
 To denote a hexadecimal integer literal, use a leading 0x or 0X (zero x).
- For example, the following code displays the decimal value 65535 for hexadecimal number FFFF.
 System.out.println(0xFFFF);
3.7.2. Floating-Point Literals
Floating-point literals are written with a decimal point. By default, a floating-point literal is treated as a double
type value. For example, 5.0 is considered a double value, not a float value. You can make a number a float by
appending the letter f or F, and you can make a number a double by appending the letter d or D. For example,
you can use 100.2f or 100.2F for a float number, and 100.2d or 100.2D for a double number.

The floating point types (float and double) can also be expressed using E or e (for scientific notation), F or f
(32-bit float literal) and D or d (64-bit double literal; this is the default and by convention is omitted).

double d1 = 123.4;
// same value as d1, but in scientific notation
double d2 = 1.234e2;
float f1 = 123.4f;

3.7.3. Boolean Literals


Boolean literals are simple. There are only two logical values that a boolean value can have, true and false.
The values of true and false do not convert into any numerical representation. The true literal in Java does not
equal 1, nor does the false literal equal 0. In Java, they can only be assigned to variables declared as boolean,
or used in expressions with Boolean operators.

3.7.4. Character Literals


Characters in Java are indices into the Unicode character set. They are 16-bit values that can be converted into
integers and manipulated with the integer operators, such as the addition and subtraction operators.

 A literal character is represented inside a pair of single quotes.


o All of the visible ASCII characters can be directly entered inside the quotes, such as ‘a’, ‘z’, and
‘@’.
o There is also a mechanism for directly entering the value of a character in octal or
hexadecimal. "Unicode escape"
 For octal notation, use the backslash followed by the three-digit number. For example,
‘\141’ is the letter ‘a’.
 For hexadecimal, you enter a backslash-u (\u), then exactly four hexadecimal digits.
For example, ‘\u0041’ is the letter ‘A’
o For characters that are impossible to enter directly, there are several escape sequences that
allow you to enter the character you need, such as ‘\’’ for the single-quote character itself and
‘\n’ for the newline character. Table 3.2 shows the character escape sequences.

DBU, Department of Electrical and Computer Engineering, 3th Year 18


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

 Unicode escape sequences may be used elsewhere in a program (such as in field


names, for example), not just in char or String literals.
Escape Sequence Description
Hexadecimal Unicode character (XXXX): \u followed by the hexadecimal Unicode
\uXXXX
code point up to U+FFFF)
\DDD Octal character (DDD) (octal number not exceeding 377, preceded by backslash)
\n New line (also known as line feed)
\r Carriage return
\f Form feed
\\ Backslash
\' Single quote
\" Double quote
\t Tab
\b Backspace
Table 3.2: Characters escapes sequences in character and strings

3.7.5. String Literals


String literals in Java are specified like they are in most other languages—by enclosing a sequence of
characters between a pair of double quotes. They can be any sequence of characters and character escapes
enclosed in double quotes.

Examples of string literals are


“Hello World”
“two\nlines”
“\”This is in quotes\”“
3.7.6. Other Literals
 There's also a special null literal that can be used as a value for any reference type. null may be
assigned to any variable, except variables of primitive types.
 Finally, there's also a special kind of literal called a class literal, formed by taking a type name and
appending ".class"; for example, String.class. This refers to the object (of type Class) that represents
the type itself.

3.8. Type Conversion and Casting


It is fairly common to assign a value of one type to a variable of another type. If the two types are compatible,
then Java will perform the conversion automatically.

Can you perform binary operations with two operands of different types? Yes. If an integer and a floating-
point number are involved in a binary operation, Java automatically converts the integer to a floating-point
value. So, 3 * 4.5 is same as 3.0 * 4.5.

Java’s Automatic Conversions

When one type of data is assigned to another type of variable, an automatic type conversion will take place if
the following two conditions are met:

 The two types are compatible.


 The destination type is larger than the source type.
When these two conditions are met, a widening conversion takes place. For widening conversions,

DBU, Department of Electrical and Computer Engineering, 3th Year 19


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

- the numeric types, including integer and floating-point types, are compatible with each other
- numeric types and char type are not compatible
- numeric types and boolean type are not compatible
- Also, char and boolean are not compatible with each other
For example, the int type is always large enough to hold all valid byte values, so no explicit cast statement is
required. you can assign a long value to a float variable.

As mentioned earlier, Java also performs an automatic type conversion when storing a literal integer constant
into variables of type byte, short, long, or char.

Casting Incompatible Types

You cannot, however, assign a value to a variable of a type with smaller range unless you use type casting.
Casting is an operation that converts a value of one data type into a value of another data type. Casting a
variable of a type with a small range to a variable of a type with a larger range is known as widening a type.
Casting a variable of a type with a large range to a variable of a type with a smaller range is known as
narrowing a type. Widening a type can be performed automatically without explicit casting. Narrowing a
type must be performed explicitly.

For example, what if you want to assign an int value to a byte variable? This conversion will not be performed
automatically, because a byte is smaller than an int. This kind of conversion is sometimes called a narrowing
conversion, since you are explicitly making the value narrower so that it will fit into the target type.

To create a conversion between two incompatible types, you must use a cast. A cast is simply an explicit type
conversion. It has this general form: The syntax is the target type in parentheses, followed by the variable’s
name or the value to be cast.

(target-type) value

For example,

- System.out.println((int) 1.7);
- System.out.println((double) 1 / 2);
- System.out.println(1 / 2);
Casting does not change the variable being cast. For example, d is not changed after casting in the following
code:

double d = 4.5;
int i = (int)d; // i becomes 4, but d is not changed, still 4.5
To assign a variable of the int type to a variable of the short or byte type, explicit casting must be used. For
example, the following statements have a compile error:

int i = 1;
byte b = i; // Error because explicit casting is required
However, so long as the integer literal is within the permissible range of the target variable, explicit casting is
not needed to assign an integer literal to a variable of the short or byte type.

DBU, Department of Electrical and Computer Engineering, 3th Year 20


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

3.9. Overflow an Underflow


When a variable is assigned a value that is too large (in size) to be stored, it causes overflow. For example,
executing the following statement causes overflow, because the largest value that can be stored in a variable
of the int type is 2147483647. 2147483648 is too large.

int value = 2147483647 + 1; // value will actually be -2147483648

Likewise, executing the following statement causes overflow, because the smallest value that can be stored in
a variable of the int type is -2147483648. -2147483649 is too large in size to be stored in an int variable.

int value = -2147483648 - 1; // value will actually be 2147483647

Java does not report warnings or errors on overflow. So be careful when working with numbers close to the
maximum or minimum range of a given type. When a floating-point number is too small (i.e., too close to zero)
to be stored, it causes underflow. Java approximates it to zero. So normally you should not be concerned with
underflow.

3.10. Operators
Now that you've learned how to declare and initialize variables, you probably want to know how to do
something with them. Learning the operators of the Java programming language is a good place to start.

Operators are special symbols that perform specific operations on one, two, or three operands, and
then return a result.
Recall that; An Expression is a piece of program code that represents or computes a value.
 It is an essential part of programming.
 It can be a literal, a variable, a method call, or several of these things combined with operators
such as + and >. That is;
 Literals (such as 674, 3.14, true, and ’X’), variables (such as x, myVariable, y), and
method calls (such as add(x, y); add(3, 6); ) are simple expressions.
 More complex expressions can be built up by using operators to combine simpler
expressions (such as 674+X, 3.14+34, x>y, 14<y, etc.).
 The value of an expression can be assigned to a variable, used as a parameter in a
subroutine/method call, or combined with other values into a more complicated expression.
Java provides a rich operator environment. The rest of this section gives details of operators in Java. The
number of operators in Java is quite large, and I will not cover them all here. Most of the important ones are
here; a few will be covered in later chapters as they become relevant.

3.10.1. Arithmetic Operators


The Java programming language provides operators that perform addition, subtraction, multiplication, and
division. There's a good chance you'll recognize them by their counterparts in basic mathematics. The only
symbol that might look new to you is "%", which divides one operand by another and returns the remainder
as its result. Arithmetic operators are used in mathematical expressions in the same way that they are used in
algebra. The following table lists the arithmetic operators:

Operator Description
+ Additive operator (also used for String concatenation)
- Subtraction operator
* Multiplication operator
/ Division operator
% Remainder operator (Modulus)

DBU, Department of Electrical and Computer Engineering, 3th Year 21


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

++ (Increment)
-- Decrement)

Note:

 The operands of the arithmetic operators must be of a numeric type. i.e. they operate on values of;
- Any integer type: byte, short, int, or long.
- Any real/floating-point type: float, or double.
- Character types: char (since the char type in Java is, essentially, a subset of int, values of
type char are treated as integers in this context; a char is converted into its Unicode code
number when it is used with an arithmetic operator ).
- You cannot use them on boolean types.
 The + operator can also be used for concatenating (joining) two strings together
- It can also be used to concatenate a value of any type onto a String.
- In Java, any type can be automatically converted into type String.
3.10.1.1. The Basic Arithmetic Operators
The usual arithmetic operators (+, -, *, and /) are used in Java for addition, subtraction, multiplication, and
division— all behave as you would expect for all numeric types. They are used in mathematical expressions
in the same way that they are used in algebra.

 The Subtraction/minus operator: Subtracts right-hand operand from left-hand operand.


o It also has a unary form that negates its single operand.
 Unary minus operator negates an expression.
 For example, -X has the same value as (-1)*X.
 For completeness, Java also has a unary plus operator; it indicates positive value
(numbers are positive without this, however)
 As in +X, even though it doesn’t really do anything. +X is the same as X;
 When arithmetic operators are used with two operands/values of same types:
o The answer will be of the same type as the operands.
 If you multiply two int, you get an int;
 If you multiply two doubles, you get a double; etc.
 When arithmetic operators are used with two operands of different types:
o Java automatically converts one of the values from one type to another.
 If an integer and a floating-point number are involved in a binary operation, the
integer converted to a floating-point value. So, 3 * 4.5 is same as 3.0 * 4.5.
o This is called a type conversion. After doing type conversion on one of them, if necessary, the
answer will be of the same type.
 Remember that when the division operator is used, you have to be very careful.
o When you divide two values, the division operator denotes
 Integer division if both arguments are integers, or floating-point division otherwise.
 When you divide two integers, the answer will always be an integer;
 If the quotient has a fractional part, it is discarded.
 For example, the value of 7/2 is 3, not 3.5.
 If N is an integer variable, then N/100 is an integer, and 1/N is equal to zero
for any N greater than one!
 This fact is a common source of programming errors.
 You can force the computer to compute a real number as the answer by
making one of the operands real: For example, when the computer

DBU, Department of Electrical and Computer Engineering, 3th Year 22


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

evaluates 1.0/N, it first converts N to a real number in order to match the


type of 1.0, so you get a real number as the answer.
 Note that integer division by 0 raises an exception, whereas floating-point division
by 0 yields an infinite or NaN result.
3.10.1.2. The Modulus Operator (%)
The modulus operator, %, is an operator for computing the remainder when one operand is divided by
another. It returns the remainder of a division operation. It can be applied to floating-point types as well as
integer types.

 If A and B are integers, then A % B represents the remainder when A is divided by B. (However, for
negative operands, % is not quite the same as the usual mathematical “modulus” operator, since if
one of A or B is negative, then the value of A % B will be negative.)
 A common use of % is to test whether a given integer is even or odd: N is even if N % 2 is zero, and it
is odd if N % 2 is 1. More generally, you can check whether an integer N is evenly divisible by an
integer M by checking whether N % M is zero.
For example, 7 % 2 is 1, while 34577 % 100 is 77, and 50 % 8 is 2.

3.10.1.3. Increment and Decrement Operators


One of the most common operations with a numeric variable is to add or subtract 1. Java, following in the
footsteps of C and C++, has both increment (++) and decrement (--) operators.

 They are unary operators; require only one operand;


 They perform incrementing/decrementing a value by one
o The increment operator increases its operand by one.
o The decrement operator decreases its operand by one.
 These operators can be used on variables belonging to any of the numerical types (byte, short, int,
long, float, or double) and also on variables of type char.
o These operators change the value of a variable, they cannot be applied to numbers
themselves.
o For example, 4++ is not a legal statement.
o They cannot be applied to boolean type variable.
 They can be used in statements like “x++;” or “x--;” "++x;" "--x;” as commands to change the value of
x.
o It is also legal to use x++, ++x, x--, or --x as expressions, or as parts of larger expressions.
 The increment/decrement operators can appear in two forms prefix form and postfix form.
- In prefix forms: the operators precede the operand as ++x, --x,
- In postfix form: they follow the operand as x++, x--; the operator that is placed after the
operand.
 Both forms change the value of the variable by 1. They will both end in result being incremented/
decremented by one.
o For a simple increment/decrement statement, it doesn't really matter which version you
choose. There is no difference between the prefix and postfix forms.
 Statements such as x++; ++x; both performing a simple increment operation which is
equivalent to x=x+1;
 Similarly, you could write x--; (or --x;) to subtract 1 from x. both statements perform
the same computation as x = x - 1. Similarly, you could write x-- (or --x) to subtract 1
from x. That is, x-- performs the same computation as x = x - 1.
o However, when the increment/decrement operators are part of a larger expression, then a
subtle, yet powerful, difference between these two forms appears.

DBU, Department of Electrical and Computer Engineering, 3th Year 23


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

 In the prefix form, the operand is incremented or decremented before the value is
obtained for use in the expression.
 For Example: The statement “y = ++x;” the increment occurs before x is
assigned to y.
 X=x+1;
 Y=x;
 In postfix form, the previous value is obtained for use in the expression, and then
the operand is modified. The statement “y = x++;” The value assigned to y is the old
value of x, before the 1 is added.
It is recommend against using ++ inside other expressions because this often leads to confusing code
and annoying bugs. Use ++ and -- only in stand-alone statements, not in expressions.

3.10.2. Relational Operators


The relational operators determine the relationship that one operand has to the other. Specifically, they
determine equality and ordering. They are used to determine if one operand is greater than, less than, equal
to, or not equal to another operand.

The following table lists the relational operators in Java and presents the meanings of these operators:

Operator Name meanings


== Equal to A == B Is A "equal to" B?
!= Not equal to A != B Is A "not equal to" B?
> Greater than A>B Is A "greater than" B?
Greater than or equal to A >= B Is A "greater than or
>=
equal to" B?
< Less than A<B Is A "less than" B?
Less than or equal to A <= B Is A "less than or equal
<=
to" B?

Keep in mind that Java equality is denoted with two equal signs, not one. You must use "==", not "=",
(Remember: a single equal sign is the assignment operator.)

 The result produced by a relational operator is a boolean value.


 Any type in Java, including integers, floating-point numbers, characters, and Booleans can be
compared using the equality test, ==, and the inequality test,!=.
- The operators == and != can be used to compare boolean values.
- For example, can you figure out what this does: boolean sameSign; sameSign = ((x > 0)
== (y > 0));
 But, only numeric types can be compared using the ordering operators (<, >, <=, and <=). That is,
only integer, floating-point, and character operands may be compared to see which is greater or less
than the other.
- For characters, < and > are defined according the numeric Unicode values of the
characters.
o It is not the same as alphabetical order because all the upper case letters come
before all the lower case letters.
- You cannot do with the relational operators (<, >, <=, and <=) to compare values of type
String.

DBU, Department of Electrical and Computer Engineering, 3th Year 24


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

o But, You can legally use == and != to compare Strings,


 The relational operators are most frequently used in the expressions that control the if statement
and the various loop statements

If you are coming from a C/C++ background, please note the following:

In C/C++, true is any nonzero value and false is zero. Java does not define true and false in the same way as
C/C++. In Java, true and false are nonnumeric values that do not relate to zero or nonzero. Therefore, to test
for zero or nonzero, you must explicitly employ one or more of the relational operators.

3.10.3. Logical Operators


Logical operators, also known as Boolean operators, operate on Boolean values to create a new Boolean
value. The Table below gives a list of Boolean operators in Java.

Operator Name Operation


&& Short-circuit AND logical conjunction
|| Short-circuit OR logical disjunction
! Logical NOT logical negation
& Logical AND logical conjunction
| Logical OR logical disjunction
^ Logical XOR logical exclusion (exclusive or)

 The logical operators (‘&&’, ‘||’, and ‘!’) operate only on boolean operands to form a resultant
boolean value.
o The Logical AND (&&) of two Boolean operands is true if and only if both operands are true.
o The Logical OR (||) of two Boolean operands is true if at least one of the operands is true.
o The Logical NOT (!) operator negates true to false and false to true.
 The logical operators, &, |, and ^, can operate on boolean values or on the bits of an integer. When
they are applied to boolean operands:
o The exclusive or (^) of two Boolean operands is true if and only if the two operands have
different Boolean values.
o The & and | operators are similar to the && and || operators, except that the & and
|operators are not evaluated in “short circuit” fashion. That is, both arguments are first
evaluated before the result is computed.
The following table shows the effect of each logical operation:

Sometimes, whether a statement is executed is determined by a combination of several conditions. You can
use logical operators to combine these conditions.

Short-Circuit Logical Operators

DBU, Department of Electrical and Computer Engineering, 3th Year 25


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

Java provides two interesting Boolean operators not found in many other computer languages. These are
secondary versions of the Boolean AND (&&) and OR (||) operators, and are known as short-circuit logical
operators, which means that the second operand is evaluated only if needed.

 If you use the || and && forms, rather than the | and & forms of these operators, Java will not
bother to evaluate the right-hand operand when the outcome of the expression can be determined
by the left operand alone. This is very useful when the right-hand operand depends on the value of
the left one in order to function properly.
o For Example;
int denom=0;
int sum=12;
if(denom != 0 && num/denom >0){
System.out.println(“No problem!”);
}
Since the short-circuit form of AND (&&) is used, there is no risk of causing a run-time
exception when denom is zero. If this line of code were written using the single & version of
AND, both sides would be evaluated, causing a run-time exception when denom is zero.
 Therefore, && is referred to as the conditional or short-circuit AND operator, and || is referred to as
the conditional or short-circuit OR operator.
 It is standard practice to use the short-circuit forms of AND and OR in cases involving Boolean logic,
leaving the single-character versions exclusively for bitwise operations.
 Caution: the expression like, (1 <= numberOfDaysInAMonth <= 31), is incorrect in Java,
because 1 <= numberOfDaysInAMonth is evaluated to a boolean value, which cannot be
compared with 31.
o Here, two operands (a boolean value and a numeric value) are incompatible.
o The correct expression in Java is as:
(1 <= numberOfDaysInAMonth) && (numberOfDaysInAMonth <= 31)

3.10.4. Bitwise and Bit Shift Operators


The Java programming language also provides operators that perform bitwise and bit shift operations on
integral types. The operators discussed in this section are less commonly used. Therefore, their coverage is
brief; the intent is to simply make you aware that these operators exist.

 The unary bitwise complement operator "~" inverts a bit pattern; it can be applied to any of the
integral types, making every "0" a "1" and every "1" a "0". For example, a byte contains 8 bits;
applying this operator to a value whose bit pattern is "00000000" would change its pattern to
"11111111".
 The signed left shift operator "<<" shifts a bit pattern to the left, and the signed right shift operator
">>" shifts a bit pattern to the right. The bit pattern is given by the left-hand operand, and the
number of positions to shift by the right-hand operand. The unsigned right shift operator ">>>" shifts
a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension.
Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and
byte. Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b = 13; now in
binary format

a = 0011 1100

b = 0000 1101

DBU, Department of Electrical and Computer Engineering, 3th Year 26


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

The following table lists the bitwise operators − Assume integer variable A holds 60 and variable B holds 13
then −

Operator Description Example


Binary AND Operator copies a bit to the result if (A & B) will give 12 which is
& (bitwise and)
it exists in both operands. 0000 1100

Binary OR Operator copies a bit if it exists in (A | B) will give 61 which is


| (bitwise or)
either operand. 0011 1101

Binary XOR Operator copies the bit if it is set in (A ^ B) will give 49 which is
^ (bitwise XOR)
one operand but not both. 0011 0001

(~A ) will give -61 which is 1100


Binary Ones Complement Operator is unary and
~ (bitwise compliment) 0011 in 2's complement form
has the effect of 'flipping' bits.
due to a signed binary number.

Binary Left Shift Operator. The left operands


A << 2 will give 240 which is
<< (left shift) value is moved left by the number of bits
1111 0000
specified by the right operand.

Binary Right Shift Operator. The left operands


>> (right shift) value is moved right by the number of bits A >> 2 will give 15 which is 1111
specified by the right operand.

Shift right zero fill operator. The left operands


value is moved right by the number of bits A >>>2 will give 15 which is
>>> (zero fill right shift)
specified by the right operand and shifted 0000 1111
values are filled up with zeros.

3.10.5. The Assignment Operators


Like the simple assignment operator (=), the operators (+=, -=, *=, /=, %=, and many more) can be used to
form an assignment statement as well as an expression. For example, in the following code, x += 2 is a
statement in the first line and an expression in the second line.

int x=8;
x+=12; // is a statement
System.out.print(x+=2); // Expression

Following are the assignment operators supported by Java language −

Operator Description Example

Simple assignment operator. Assigns values from


= C = A + B will assign value of A + B into C
right side operands to left side operand.

DBU, Department of Electrical and Computer Engineering, 3th Year 27


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

Add AND assignment operator. It adds right


+= operand to the left operand and assign the result C += A is equivalent to C = C + A
to left operand.

Subtract AND assignment operator. It subtracts


-= right operand from the left operand and assign the C -= A is equivalent to C = C – A
result to left operand.

Multiply AND assignment operator. It multiplies


*= right operand with the left operand and assign the C *= A is equivalent to C = C * A
result to left operand.

Divide AND assignment operator. It divides left


/= operand with the right operand and assign the C /= A is equivalent to C = C / A
result to left operand.

Modulus AND assignment operator. It takes


%= modulus using two operands and assign the result C %= A is equivalent to C = C % A
to left operand.

<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2

>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2

^= bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2

|= bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2

3.10.6. Miscellaneous Operators


There are few other operators supported by Java Language.

Conditional Operator (? : )
Conditional operator is also known as the ternary operator. This operator consists of three operands and is
used to evaluate Boolean expressions. The goal of the operator is to decide, which value should be assigned
to the variable. The operator is written as:

expression1 ? expression2 : expression3


Here, expression1 can be any expression that evaluates to a boolean value. If expression1 is true, then
expression2 is evaluated; otherwise, expression3 is evaluated. The result of the ? operation is that of the
expression evaluated. Both expression2 and expression3 are required to return the same type, which can’t be
void.

public class Test {


public static void main(String args[]) {
int a, b;
a = 10;
b = (a == 1) ? 20: 30;

DBU, Department of Electrical and Computer Engineering, 3th Year 28


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

System.out.println( "Value of b is : " + b );


b = (a == 10) ? 20: 30;
System.out.println( "Value of b is : " + b );
}
}

This will produce the following result:

Value of b is : 30
Value of b is : 20

3.10.7. Precedence of Java Operators


Operator precedence determines the grouping of terms in an expression. This affects how an expression is
evaluated. Certain operators have higher precedence than others; for example,

 the multiplication operator has higher precedence than the addition operator −
 For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher precedence
than +, so it first gets multiplied with 3 * 2 and then adds into 7.
 Parentheses raise the precedence of the operations that are inside them. This is often necessary to
obtain the result you desire. For example, consider the following expression:
int x;
x=2*3+1; // here x is assigned 7
x=2*(3+1); // here x is assigned 8

Within an expression, higher precedence operators will be evaluated first. The Table below shows the
precedence of operators. If no parentheses are used, operations are performed in the hierarchical order
indicated. Operators on the same level are processed from left to right, except for those that are right
associative, as indicated in the table.

 For example, because && has a higher precedence than ||, the expression, a && b || c
means (a && b) || c
 Because += associates right to left, the expression, a += b += c means, a += (b +=
c)

DBU, Department of Electrical and Computer Engineering, 3th Year 29


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

3.11. Control Flow Statements


Control flow (or alternatively, flow of control) refers to the order in which the individual statements,
instructions or function calls of an imperative or a declarative program are executed or evaluated. Within an
imperative programming language, a control flow statement is a statement whose execution results in a choice
being made as to which of two or more paths should be followed.

All the programs in the previous sections were constructed from a sequence of statements. Each time a
program was run, the computer would execute the same statements in the same order. A natural question is:
How do you write a program that will allow different statements to be executed under different conditions?
This section introduces the techniques of coding conditions and branching on the result of a condition to
alternative statements in a program.

The statements inside your source files are generally executed in from top to bottom (left to right), in the
order that they appear. Control flow statements, however, break up the flow of execution and cause the flow
of execution to advance and branch based on changes to the state of a program. Programming languages
provide various control structures that allow for more complicated execution paths. Java’s program control
statements can be put into the following categories:

 Decision-Making Statements: also known as Selection or Conditional Statements.


 Looping Statements (or alternatively, iteration)
 Branching Statements (unconditional branch or jump).
3.11.1. The Decision-Making Statements
Also known as Selection or Conditional Statements.
They allow your program to choose different paths of execution based upon the outcome of an
expression or the state of a variable.

DBU, Department of Electrical and Computer Engineering, 3th Year 30


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

Decision making structures have one or more conditions to be evaluated or tested by the program,
along with a statement or statements that are to be executed if the condition is determined to be
true, and optionally, other statements to be executed if the condition is determined to be false.
Like all high-level programming languages, Java provides several selection statements that let you choose
actions with two or more alternative courses. The following types of decision making statements are
supported by Java:

- if statement
- if...else statement
- nested if statement
- switch statement, and
- Conditional expressions (conditional operator ‘? : ‘).
These statements allow you to control the flow of your program’s execution based upon conditions known
only during run time.

Conditions are Boolean expressions.

A. The if Statement
The if statement, (also called if-then statement or one-way if statement), is the most basic of all the control
flow statements. It is Java’s conditional branch statement, i.e., it allows conditional execution of a statement
or a group of statements (block).

It tells your program to execute a certain section of code only if a particular test evaluates to true. If
this test evaluates to false, the control jumps to the end of the if-then statement.

It can be used if we wish to execute a statement only if a condition is true. The basic format of the if statement
is:

if(condition){
statement(s);
}

Here,

The if statement executes the action (statement(s);) if and only if the condition is true.
The condition is any expression that returns a boolean value.
 It must have a boolean type, otherwise a compile-time error occurs.
 It must be surrounded by parentheses.
The statement(s) can be a single statement or a compound statement enclosed in curly braces (that
is, a block).
 The block braces can be omitted if they enclose a single statement.
The execution flow chart is shown in Figure

The if-then statement is executed by first evaluating the condition expression. If the resulting value is
true, then the contained statement(s) is executed; Otherwise, no further action is taken and the control
jumps to the end of the if statement.

NOTE: A block (sometimes called a compound statement) allows you to have more than one (simple)
statement in any Java programming structure. You will often want to execute multiple statements when a
single condition is true. In this case, you use a block statement that takes the form:

DBU, Department of Electrical and Computer Engineering, 3th Year 31


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

{
Statement_1;
Statement_2;
Statement_N;
}

The block braces can be omitted if they enclose a single statement.

Deciding when to omit the braces is a matter of personal taste. Omitting them can make the code more brittle.
If a second statement is later added to the "then" clause, a common mistake would be forgetting to add the
newly required braces. The compiler cannot catch this sort of error; you'll just get the wrong results. Some
programmers find it convenient to include the curly braces when using the if, even when there is only one
statement in each clause. This makes it easy to add another statement at a later date, and you don’t have to
worry about forgetting the braces. In fact, forgetting to define a block when one is needed is a common cause
of errors.

Most often, the expression used to control the if will involve the relational operators. However, this is not
technically necessary. It is possible to control the if using a single boolean variable. For example;

boolean x=false;
if(x){…}
The condition must be surrounded by parentheses. For example, the code in (a) below is wrong.

If x>10{

Example:
import java.util.Scanner;
public class SimpleIfDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter an integer: ");
int number = input.nextInt();
if (number % 5 == 0)
System.out.println("HiFive");
if (number % 2 == 0)
System.out.println("HiEven");
}
}

Expected output:

B. The if-then-else Statement


The if-else statement, (also called if-then-else or two-way if statement), is Java’s more general conditional
branch statement. It can be used to route program execution through two different paths. It provides a
secondary path of execution when an "if" clause evaluates to false. The actions that a two-way if statement
specifies differ based on whether the condition is true or false.

DBU, Department of Electrical and Computer Engineering, 3th Year 32


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

The if-else construct is used if we wish to execute one set of statements if a condition is true, and a
second set of statements if the condition is false.

Here is the syntax for a two-way if statement:

if(condition){
statement_1;
}
else {
statement_2;
}

Here:

If the condition is true, then statement_1 is executed. Otherwise, statement_2 is executed. In no case
will both statements be executed.
Each statement may be a single statement or a compound statement enclosed in curly braces.
As usual, the braces can be omitted if there is only one statement within them.
The condition is any expression that returns a boolean value.
The else part is always optional. An else groups with the closest if.
The else part is always optional. An else groups with the closest if. Thus, in the statement

if (x <= 0) if (x == 0) sign = 0; else sign = -1;

the else belongs to the second if. Of course, it is a good idea to use braces to clarify this code:

if (x <= 0) { if (x == 0) sign = 0; else sign = -1; }

D. Nested if Statements
The statement in an if or if ... else statement can be any legal Java statement, including another if or if ... else
statement. The inner if statement is said to be nested inside the outer if statement. The inner if statement can
contain another if statement; in fact, there is no limit to the depth of the nesting. For example, the following
is a nested if statement:
if (i > k) {
if (j > k)
System.out.println("i and j are greater than k");
}
else
System.out.println("i is less than or equal to k");
The nested if statement can be used to implement multiple alternatives.

A preferred format for multiple alternative if statements is if-else-if statement.

DBU, Department of Electrical and Computer Engineering, 3th Year 33


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

E. The switch Statement


Java provides a switch statement to handle multiple conditions efficiently. It can be used to replace the nested
if statement; Overuse of nested if statements makes a program difficult to read.

The switch statement checks all cases and executes the statements in the matched case.

The syntax for the switch statement:


switch (switch-expression) {
case value1: statement(s)1;
break;
case value2: statement(s)2;
break;
...
case valueN: statement(s)N;
break;
default: statement(s)-for-default;
}
The switch statement observes the following rules:

 The switch-expression must yield a value of char, byte, short, or int type and must always be enclosed
in parentheses.
 The value1, and valueN must have the same data type as the value of the switch-expression. Note that
value1, and valueN are constant expressions, meaning that they cannot contain variables, such as 1 +
x.
 When the value in a case statement matches the value of the switch-expression, the statements
starting from this case are executed until either a break statement or the end of the switch statement
is reached.
 The keyword break is optional. The break statement immediately ends the switch statement.
 The default case, which is optional, can be used to perform actions when none of the specified cases
matches the switch-expression.
 The case statements are checked in sequential order, but the order of the cases (including the default
case) does not matter. However, it is good programming style to follow the logical sequence of the
cases and place the default case at the end.
Caution:

Do not forget to use a break statement when one is needed. Once a case is matched, the statements starting
from the matched case are executed until a break statement or the end of the switch statement is reached.
This is referred to as fall-through behavior. For example, the following code prints character a three times if
ch is 'a' :
DBU, Department of Electrical and Computer Engineering, 3th Year 34
ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

switch (ch) {
case 'a' : System.out.println(ch);
case 'b' : System.out.println(ch);
case 'c' : System.out.println(ch);
}

F. Conditional Expressions
(See section 3.10.6)

3.11.2. Looping Statements


A. The for Statement
The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as
the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The
general form of the for statement can be expressed as follows:
for (initialization; termination; increment) {
statement(s)
}
When using this version of the for statement, keep in mind that:

 The initialization expression initializes the loop; it's executed once, as the loop begins.
 When the termination expression evaluates to false, the loop terminates.
 The increment expression is invoked after each iteration through the loop; it is perfectly acceptable
for this expression to increment or decrement a value.

The following program uses the general form of the for statement to print the numbers 1 through 10 to
standard output:
class ForDemo {
public static void main(String[] args){
for(int i=1; i<11; i++){
System.out.println("Count is: " + i);
}
}
}

The output of this program is:

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10

Notice how the code declares a variable within the initialization expression. The scope of this variable extends
from its declaration to the end of the block governed by the for statement, so it can be used in the termination
and increment expressions as well. If the variable that controls a for statement is not neede d outside of the

DBU, Department of Electrical and Computer Engineering, 3th Year 35


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

loop, it's best to declare the variable in the initialization expression. The names i, j, and k are often used to
control for loops; declaring them within the initialization expression limits their life span and reduces errors.

The three expressions of the for loop are optional; an infinite loop can be created as follows:

// infinite loop
for ( ; ; ) {
// your code goes here
}
B. The while Statement
The while statement continually executes a block of statements while a particular condition is true. Its syntax
can be expressed as:

while (expression) {
statement(s)
}
The while statement evaluates expression, which must return a boolean value. If the expression evaluates to
true, the while statement executes the statement(s) in the while block. The while statement continues testing
the expression and executing its block until the expression evaluates to false. Using the while statement to
print the values from 1 through 10 can be accomplished as in the following WhileDemo program:

class WhileDemo {
public static void main(String[] args){
int count = 1;
while (count < 11) {
System.out.println("Count is: " + count);
count++;
}
}
}
You can implement an infinite loop using the while statement as follows:

while (true){
// your code goes here
}
C. The do-while Statement
The Java programming language also provides a do-while statement, which can be expressed as follows:

do {
statement(s)
} while (expression);
The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop
instead of the top. Therefore, the statements within the do block are always executed at least once, as shown
in the following DoWhileDemo program:

class DoWhileDemo {
public static void main(String[] args){
int count = 1;
do {
System.out.println("Count is: " + count);

DBU, Department of Electrical and Computer Engineering, 3th Year 36


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

count++;
} while (count < 11);
}
}

3.11.3. Branching Statements


A. The break Statement
 The break Statement can be used in loop statements to provide additional controls. You have
used the keyword break in a switch statement. You can also use break in a loop to immediately
terminate the loop.
 The break statement has two forms: labeled and unlabeled.
 An unlabeled break statement: You saw the unlabeled form in the previous discussion
of the switch statement. You can also use an unlabeled break to terminate a switch,
for, while, or do-while loop. It terminates the innermost switch, for, while, or do-while
statement. For Example:
public class MyClass{
public static void main(String[] args){
for(int i=0; i<2; i++){
for(int j=0; j<5; j++){
if(j==3)
break;
System.out.println(j);
}
}
}
}
The expected output
0
1
2
0
1
2

 A labeled break: An unlabeled break statement terminates the innermost switch, for,
while, or do-while statement, but a labeled break terminates an outer statement.
Control flow is transferred to the statement immediately following the labeled
(terminated) statement. For Example:
public class MyClass{
public static void main(String[] args){
for(int i=0; i<2; i++){
for(int j=0; j<5; j++){
if(j==3)
break;
System.out.println(j);
}
}
}
}
The expected output

DBU, Department of Electrical and Computer Engineering, 3th Year 37


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

0
1
2

B. The continue Statement


 The continue statement skips the current iteration of a for, while, or do-while loop.
 Example:
public class MyClass{
public static void main(String[] args){
for(int i=0; i<5; i++){
if(i==3)
continue;
System.out.println(i);
}
}
}
The expected output
0
1
2
4

C. The return Statement


 The last of the branching statements is the return statement. The return statement exits from
the current method, and control flow returns to where the method was invoked. The return
statement has two forms: one that returns a value, and one that doesn't. To return a value,
simply put the value (or an expression that calculates the value) after the return keyword.
 We will cover this in chapter 4 later.

3.12. Arrays
3.12.0. Introduction
Problem (why array?)
Often you will have to store a large number of values during the execution of a program. Suppose, for instance,
that you need to read 100 numbers, compute their average, and find out how many numbers are above the
average. Your program first reads the numbers and computes their average, then compares each number with
the average to determine whether it is above the average. In order to accomplish this task, the numbers must all
be stored in variables. You have to declare 100 variables and repeatedly write almost identical code 100 times.
Writing a program this way would be impractical. So, how do you solve this problem?

Solution
An efficient, organized approach is needed. Java and most other high-level languages provide a data structure,
the array, which stores a fixed-size sequential collection of elements of the same type. In the present case, you
can store all 100 numbers into an array and access them through a single array variable .

3.12.1. Array Basics


An array is used to store a collection of data, but often we find it more useful to think of an array as a collection
of variables of the same type. Instead of declaring individual variables, such as number0, number1, and
number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and
numbers[99] to represent individual variables.

DBU, Department of Electrical and Computer Engineering, 3th Year 38


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

- An array is a container object that holds a fixed number of values of a single type.
- The length of an array is established when the array is created.
- After creation, its length is fixed.

Figure: An array of 10 elements.

- Each item in an array is called an element, and each element is accessed by its numerical index.
- As shown in the preceding illustration, numbering begins with 0. The 9th element, for example,
would therefore be accessed at index 8.
3.12.2. Declaring Array Variables
To use an array in a program, you must declare a variable to reference the array and specify the array’s
element type. Here is the syntax for declaring an array variable:
elementType[] arrayRefVar;

- Like declarations for variables of other types, an array declaration has two
components: the array's type and the array's name.
- Where type is the data type of the contained elements; the brackets are special
symbols indicating that this variable holds an array.
 All elements in the array will have the same data type.
- An array's name can be anything you want, provided that it follows the rules and
conventions as previously discussed.
- Note: You can also use elementType arrayRefVar[] to declare an array variable.
However, the style elementType[] arrayRefVar is preferred.
- For example, the following code declares arrays of various types:
byte[] anArrayOfBytes;
short[] anArrayOfShorts;
int[] anArrayOfInts;
long[] anArrayOfLongs;
float[] anArrayOfFloats;
double[] anArrayOfDoubles;
boolean[] anArrayOfBooleans;
char[] anArrayOfChars;
String[] anArrayOfStrings;
// You can also place the brackets after the array's name:
int myArray []; // But, this form is discouraged

3.12.3. Creating Arrays


The declaration of an array variable creates only a storage location for the reference to an array. It does not
allocate any space in memory for the array. After an array variable is declared, you can create an array by
using the new operator with the following syntax:

arrayRefVar = new elementType[arraySize];

DBU, Department of Electrical and Computer Engineering, 3th Year 39


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

- This statement does two things: (1) it creates an array using new elementType[arraySize] ;
(2) it assigns the reference of the newly created array to the variable arrayRefVar.
- NB:
 You cannot create an array unless it has already been declared.
 You cannot assign elements to an array unless it has already been created.
 If a variable does not contain a reference to an array, the value of the variable is
null.
- Declaring an array variable, creating an array, and assigning the reference of the array to the
variable can be combined in one statement, as shown below:
elementType arrayRefVar = new elementType[arraySize]; // or
elementType arrayRefVar[] = new elementType[arraySize];
- Here is an example of such a statement:
int[] myArray; // declaring
myArray= new int[10]; // creating
// other ways
int[] myArray2=new int[10]; // or
int myArray3 []= new int[10];

- To assign values to the elements, use the syntax:


arrayRefVar[index] = value;
For example, the following code initializes the array:

int[] myArray; // declaring


myArray= new int[4]; // creating

myArray[0]=10;
myArray[1]=20;
myArray[2]=30;
myArray[3]=40;

3.12.4. Array Initializers


Java has a shorthand notation, known as the array initializer, which combines in one statement declaring an
array, creating an array, and initializing, using the following syntax:

elementType[] arrayRefVar = {value0, value1, ..., valuek};

- NB:
 The new operator is not used in the array-initializer syntax.
 Using an array initializer, you have to declare, create, and initialize the array all in
one statement. Splitting it would cause a syntax error.
- Example:
int[] myArray={10, 20, 30, 40}

3.12.5. Array Size and Default Values


 When space for an array is allocated, the array size must be given, specifying the number of elements
that can be stored in it. The size of an array cannot be changed after the array is created. Size can be
obtained using arrayRefVar.length

DBU, Department of Electrical and Computer Engineering, 3th Year 40


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

 When an array is created, its elements are assigned the default value of 0 for the numeric primitive
data types, '\u0000' for char types, and false for boolean types.
3.12.6. Processing Arrays
 The array elements are accessed through the index. Array indices are 0 based; that is, they range from
0 to arrayRefVar.length-1.
 Each element in the array is represented using the following syntax, known as an indexed variable:
arrayRefVar[index];
Note: Some languages use parentheses to reference an array element, as in myList(9) . But
Java uses brackets, as in myList[9] .
 After an array is created, an indexed variable can be used in the same way as a regular variable. For
example, the following code adds the values in myList[0] and myList[1] to myList[2].
int[] myList={10, 20, 30, 40}
myList[2]=myList[0]+myList[1];

To processing array elements, you will often use a for loop. Here are some examples of processing arrays:

1. Initializing arrays with input values: The following loop initializes the array numbers with user input values

import java.util.Scanner;

public class MyClass{


public static void main(String[] args){
int[] numbers=new int[10];
Scanner input=new Scanner(System.in);
System.out.println(“Enter “+numbers.length+” numbers:”);

for(int i=0; i<numbers.length; i++){


numbers[i]=input.nextInt();
}
}
}

2. Displaying arrays: To print an array, you have to print each element in the array using a loop like the
following:

public class MyClass{


public static void main(String[] args){
int[] numbers=new int[5];
numbers[0]=11;
numbers[1]=21;
numbers[2]=31;
numbers[3]=41;
numbers[4]=51;

for(int i=0; i<numbers.length; i++){


System.out.println(numbers[i]);
}
}
}
3. Summing all elements

DBU, Department of Electrical and Computer Engineering, 3th Year 41


ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

public class MyClass{


public static void main(String[] args){
int[] numbers=new int[5];
int total=0;
numbers[0]=11;
numbers[1]=21;
numbers[2]=31;
numbers[3]=41;
numbers[4]=51;

for(int i=0; i<numbers.length; i++){


total+=numbers[i];
}
}
}
4. Finding the largest element: Use a variable named max to store the largest element. Initially max is
numbers[0] . To find the largest element in the array numbers, compare each element with max, and update
max if the element is greater than max.

public class MyClass{


public static void main(String[] args){
int[] numbers=new int[5];

numbers[0]=11;
numbers[1]=21;
numbers[2]=31;
numbers[3]=41;
numbers[4]=51;

int max=numbers[0];

for(int i=0; i<numbers.length; i++){


if (numbers[i] > max) max = numbers[i];
}
}
}

3.12.7. For-each Loops


Java supports a convenient for loop, known as a for-each loop or enhanced for loop, which enables you to
traverse the array sequentially without using an index variable. For example, the following code displays all
the elements in the array numbers:

public class MyClass{


public static void main(String[] args){
int[] numbers=new int[5];

numbers[0]=11;
numbers[1]=21;
numbers[2]=31;
numbers[3]=41;
numbers[4]=51;

int max=numbers[0];

for(int i: numbers){
DBU, Department of Electrical and Computer Engineering, 3th Year 42
ECEG – 3142: Object Oriented Programming (OOP)
(Lecture Notes)
Compiled by: Bushra K/Mariam DBU-ECE/2021

System.out.println(numbers[i]);
}
}
}
In general, the syntax for a for-each loop is:

for (elementType element: arrayRefVar) {


// Process the element
}

DBU, Department of Electrical and Computer Engineering, 3th Year 43

You might also like