Professional Documents
Culture Documents
Chapter 3
Chapter 3
Chapter 3
(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.
/**
* 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!");
}
}
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.
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).
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.
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
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.
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 '='.
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;
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
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;
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:
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);
int x;
x=1;
System.out.println(x);
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.
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 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:
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;
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.
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.
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
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;
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’;
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.
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.
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.
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.
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.
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);
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!
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.
System.out.print("Hello Java!");
}
}
The expected output:
Hello Java!
2.
System.out.print("Hello");
System.out.print(" Java!");
}
}
The expected output:
Hello Java!
3.
System.out.println("Hello Java!");
}
}
The expected output:
Hello Java!
4.
System.out.println("Hello");
System.out.println("Java!");
}
}
The expected output:
Hello
Java!
- 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:
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:
- 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;
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.
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 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.
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.
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.
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.
Operator Description
+ Additive operator (also used for String concatenation)
- Subtraction operator
* Multiplication operator
/ Division operator
% Remainder operator (Modulus)
++ (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.
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.
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.
The following table lists the relational operators in Java and presents the meanings of these operators:
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.)
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.
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.
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)
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
The following table lists the bitwise operators − Assume integer variable A holds 60 and variable B holds 13
then −
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
int x=8;
x+=12; // is a statement
System.out.print(x+=2); // Expression
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:
Value of b is : 30
Value of b is : 20
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)
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 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.
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:
{
Statement_1;
Statement_2;
Statement_N;
}
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:
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.
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
the else belongs to the second if. Of course, it is a good idea to use braces to clarify this code:
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.
The switch statement checks all cases and executes the statements in the matched case.
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)
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);
}
}
}
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
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);
count++;
} while (count < 11);
}
}
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
0
1
2
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 .
- 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.
- 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
- 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];
myArray[0]=10;
myArray[1]=20;
myArray[2]=30;
myArray[3]=40;
- 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}
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;
2. Displaying arrays: To print an array, you have to print each element in the array using a loop like the
following:
numbers[0]=11;
numbers[1]=21;
numbers[2]=31;
numbers[3]=41;
numbers[4]=51;
int max=numbers[0];
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: