Two Paradigms: Process-Oriented Model
Two Paradigms: Process-Oriented Model
Module 1
An Overview of Java: Object-Oriented Programming (Two Paradigms, Abstraction, The
Three OOP Principles), Using Blocks of Code, Lexical Issues (Whitespace, Identifiers,
Literals, Comments, Separators, The Java Keywords). Data Types, Variables, and Arrays:
The Primitive Types (Integers, Floating-Point Types, Characters, Booleans), Variables, Type
Conversion and Casting, Automatic Type Promotion in Expressions, Arrays, Introducing
Type Inference with Local Variables. Operators: Arithmetic Operators, Relational Operators,
Boolean Logical Operators, The Assignment Operator, The ? Operator, Operator Precedence,
Using Parentheses. Control Statements: Java’s Selection Statements (if, The Traditional
switch), Iteration Statements (while, do-while, for, The For-Each Version of the for Loop,
Local Variable Type Inference in a for Loop, Nested Loops), Jump Statements (Using break,
Using continue, return). Chapter 2, 3, 4, 5
TWO PARADIGMS
All computer programs consist of two elements: code and data.
Process-oriented model: This approach characterizes a program as a series of linear steps
(that is, code). The process-oriented model can be thought of as code acting on data.
Procedural languages such as C employ this model
To manage increasing complexity, the second approach, called object-oriented programming,
was conceived. Object-oriented programming organizes a program around its data (that is,
objects) and a set of well-defined interfaces to that data. An object-oriented program can be
characterized as data controlling access to code.
ABSTRACTION
An essential element of object-oriented programming is abstraction. Humans manage
complexity through abstraction. For example, people do not think of a car as a set of tens of
thousands of individual parts. They think of it as a well-defined object with its own unique
behavior. This abstraction allows people to use a car to drive to the grocery store without
being overwhelmed by the complexity of the parts that form the car. They can ignore the
details of how the engine, transmission, and braking systems work. Instead, they are free to
utilize the object as a whole. A powerful way to manage abstraction is through the use of
hierarchical classifications
In Java, the basis of encapsulation is the class. When you create a class, you will specify the
code and data that constitute that class. Collectively, these elements are called members of
the class. Specifically, the data defined by the class are referred to as member variables or
instance variables. The code that operates on that data is referred to as member methods or
just methods.
Each method or variable in a class may be marked private or public. The public interface of a
class represents everything that external users of the class need to know, or may know. The
private methods and data can only be accessed by code that is a member of the class.
Inheritance
Inheritance is the process by which one object acquires the properties of another object. For
example, a Golden Retriever is part of the classification dog, which in turn is part of the
mammal class, which is under the larger class animal.
If you wanted to describe a more specific class of animals, such as mammals, they would
have more specific attributes, such as type of teeth and mammary glands. This is known as a
subclass of animals, where animals are referred to as mammals’ superclass. Since mammals
are simply more precisely specified animals, they inherit all of the attributes from animals. A
deeply inherited subclass inherits all of the attributes from each of its ancestors in the class
hierarchy
Polymorphism
Polymorphism (from Greek, meaning “many forms”) is a feature that allows one interface to
be used for a general class of actions. The specific action is determined by the exact nature of
the situation. Consider a stack (which is a last-in, first-out list). You might have a program
that requires three types of stacks. One stack is used for integer values, one for floatingpoint
values, and one for characters. The algorithm that implements each stack is the same, even
though the data being stored differs.
A First Simple Program
/*
This is a simple Java program.
Call this file "Example.java".
*/
class Example {
// Your program begins with a call to main().
public static void main(String args[]) {
System.out.println("This is a simple Java program.");
}
}
To compile the Example program, execute the compiler, javac, specifying the name of the
source file on the command line, as shown here: C:\>javac Example.java
The javac compiler creates a file called Example.class that contains the bytecode version of
the program.
To actually run the program, you must use the Java application launcher called java. To do
so, pass the class name Example as a command-line argument, as shown here: C:\>java
Example When the program is run, the following output is displayed:
This is a simple Java program
USING BLOCKS OF CODE
Java allows two or more statements to be grouped into blocks of code, also called code
blocks. This is done by enclosing the statements between opening and closing curly braces.
if(x < y) { // begin a block
x = y;
y = 0;
} // end of block
LEXICAL ISSUES
Java programs are a collection of whitespace, identifiers, literals, comments, operators,
separators, and keywords.
Whitespace
Java is a free-form language. This means that you do not need to follow any special
indentation rules. In Java, whitespace is a space, tab, or newline
Identifiers
Identifiers are used to name things, such as classes, variables, and methods. An identifier may
be any descriptive sequence of uppercase and lowercase letters, numbers, or the underscore
and dollar-sign characters. (The dollar-sign character is not intended for general use.) They
must not begin with a number, lest they be confused with a numeric literal. Again, Java is
case-sensitive, so VALUE is a different identifier than Value.
Literals
A constant value in Java is created by using a literal representation of it. For example, here
are some literals:
100, 98.6, ‘X’, “This is a test”
Comments
There are three types of comments namely Single-line and multiline and documentation
comment. This type of comment is used to produce an HTML file that documents your
program. The documentation comment begins with a /** and ends with a */.
Separators
In Java, there are a few characters that are used as separators. The most commonly used
separator in Java is the semicolon. As you have seen, it is used to terminate statements. The
separators are shown in the following table:
Byte
The smallest integer type is byte. This is a signed 8-bit type that has a range from –128 to
127.
Byte variables are declared by use of the byte keyword. For example, the following declares
two byte variables called b and c:
byte b, c;
short
short is a signed 16-bit type. It has a range from –32,768 to 32,767. It is probably the
leastused Java type. Here are some examples of short variable declarations:
short s;
short t;
int
The most commonly used integer type is int. It is a signed 32-bit type. In addition to other
uses, variables of type int are commonly employed to control loops and to index arrays.
Long
long is a signed 64-bit type and is useful for those occasions where an int type is not large
enough to hold the desired value. The range of a long is quite large. This makes it useful
when big, whole numbers are needed.
FLOATING-POINT TYPES
Floating-point numbers, also known as real numbers, are used when evaluating expressions
that require fractional precision. There are two kinds of floating-point types, float and double,
which represent single- and double-precision numbers, respectively. Their width and ranges
In Java, the data type used to store characters is char. Java uses Unicode to represent
characters. Unicode defines a fully international character set that can represent all of the
characters found in all human languages. It is a unification of dozens of character sets, such
as Latin, Greek, Arabic, Cyrillic, Hebrew, Katakana, Hangul, and many more. . Thus, in Java
char is a 16-bit type.
BOOLEANS
Java has a primitive type, called boolean, for logical values. It can have only one of two
possible values, true or false. This is the type returned by all relational operators, as in the
case of a < b. boolean is also the type required by the conditional expressions that govern the
control statements such as if and for
VARIABLES
The variable is the basic unit of storage in a Java program. A variable is defined by the
combination of an identifier, a type, and an optional initializer. In addition, all variables have
a scope, which defines their visibility, and a lifetime.
Declaring a Variable
In Java, all variables must be declared before they can be used. The basic form of a variable
declaration is shown here:
type identifier [ = value ][, identifier [= value ] …]
Here, type is one of Java’s atomic types, or the name of a class or interface. (Class and
interface types are discussed later in Part I of this book.) The identifier is the name of the
variable.
Dynamic Initialization
Although the preceding examples have used only constants as initializers, Java allows
variables to be initialized dynamically, using any expression valid at the time the variable is
declared.
In addition to assignments, there is another place where certain type conversions may occur:
in expressions. To see why, consider the following. In an expression, the precision required
of an intermediate value will sometimes exceed the range of either operand. For example,
examine the following expression:
The result of the intermediate term a * b easily exceeds the range of either of its byte
operands. To handle this kind of problem, Java automatically promotes each byte, short, or
char operand to int when evaluating an expression. This means that the subexpression a*b is
performed using integers—not bytes. Thus, 2,000, the result of the intermediate expression,
50 * 40, is legal even though a and b are both specified as type byte.
ARRAYS
An array is a group of like-typed variables that are referred to by a common name. Arrays of
any type can be created and may have one or more dimensions. A specific element in an array
is accessed by its index. Arrays offer a convenient means of grouping related information
One-Dimensional Arrays
A one-dimensional array is, essentially, a list of like-typed variables. To create an array, you
first must create an array variable of the desired type. The general form of a one-dimensional
array declaration is
type var-name[ ];
Here, type declares the element type (also called the base type) of the array. The element type
determines the data type of each element that comprises the array. Thus, the element type for
the array determines what type of data the array will hold. For example, the following
declares an array named month_days with the type “array of int”:
int month_days[];
The general form of new as it applies to one-dimensional arrays appears as follows:
array-var = new type [size];
Here, type specifies the type of data being allocated, size specifies the number of elements in
the array, and array-var is the array variable that is linked to the array. That is, to use new to
allocate an array, you must specify the type and number of elements to allocate.
month_days = new int[12];
When you run this program, it prints the number of days in April. As mentioned, Java array
indexes start with zero, so the number of days in April is month_days[3] or 30. It is possible
to combine the declaration of the array variable with the allocation of the array itself, as
shown here:
int month_days[] = new int[12];
Multidimensional Arrays
In Java, multidimensional arrays are actually arrays of arrays. To declare a multidimensional
array variable, specify each additional index using another set of square brackets. For
example, the following declares a twodimensional array variable called twoD:
int twoD[][] = new int[4][5];
This allocates a 4 by 5 array and assigns it to twoD. Internally, this matrix is implemented as
an array of arrays of int
OPERATORS
Java provides a rich operator environment. Most of its operators can be divided into the
following four groups: arithmetic, bitwise, relational, and logical.
Arithmetic Operators
Arithmetic operators are used in mathematical expressions in the same way that they are used
in algebra. The following table lists the arithmetic operators:
can be rewritten as
var op= expression;
The following code fragment demonstrates the >>>. Here, a is set to –1, which sets all 32 bits
to 1 in binary. This value is then shifted right 24 bits, filling the top 24 bits with zeros,
ignoring normal sign extension. This sets a to 255.
int a = -1;
a = a >>> 24;
Relational Operators
The relational operators determine the relationship that one operand has to the other.
Specifically, they determine equality and ordering. The relational operators are shown here:
The ? Operator
The ? has this general form:
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 (or compatible) type, which can’t be void.
OPERATOR PRECEDENCE
The below table shows the order of precedence for Java operators, from highest to lowest.
Operators in the same row are equal in precedence. In binary operations, the order of
evaluation is left to right (except for assignment, which evaluates right to left). Although they
are technically separators, the [ ], ( ), and . can also act like operators.
USING PARENTHESES
Parentheses raise the precedence of the operations that are inside them. For example,
consider the following expression:
a >> b + 3
This expression first adds 3 to b and then shifts a right by that result. That is, this
expression can be rewritten using redundant parentheses like this:
a >> (b + 3)
However, if you want to first shift a right by b positions and then add 3 to that result, you will
need to parenthesize the expression like this:
(a >> b) + 3
In addition to altering the normal precedence of an operator, parentheses can sometimes be
used to help clarify the meaning of an expression. For anyone reading your code, a
complicated expression can be difficult to understand. Adding redundant but clarifying
parentheses to complex expressions can help prevent confusion later.
CONTROL STATEMENTS
A programming language uses control statements to cause the flow of execution to advance
and branch based on changes to the state of a program. Java’s program control statements can
be put into the following categories: selection, iteration, and jump. Selection statements allow
your program to choose different paths of execution based upon the outcome of an expression
or the state of a variable. Iteration statements enable program execution to repeat one or more
statements (that is, iteration statements form loops). Jump statements allow your program to
execute in a nonlinear fashion.
IF
The if statement is Java’s conditional branch statement. It can be used to route program
execution through two different paths. Here is the general form of the if statement:
if (condition)
statement1;
else
statement2;
Here, each statement may be a single statement or a compound statement enclosed in curly
braces (that is, a block). The condition is any expression that returns a boolean value. The
else clause is optional.
NESTED IFS
A nested if is an if statement that is the target of another if or else. Nested ifs are very
common in programming. When you nest ifs, the main thing to remember is that an else
statement always refers to the nearest if statement that is within the same block as the else
and that is not already associated with an else.
A common programming construct that is based upon a sequence of nested ifs is the if-elseif
ladder. It looks like this:
The if statements are executed from the top down. As soon as one of the conditions
controlling the if is true, the statement associated with that if is executed, and the rest of the
ladder is bypassed. If none of the conditions is true, then the final else statement will be
executed. The final else acts as a default condition; that is, if all other conditional tests fail,
then the last else statement is performed. If there is no final else and all other conditions are
false, then no action will take place.
SWITCH
The switch statement is Java’s multiway branch statement. It provides an easy way to
dispatch execution to different parts of your code based on the value of an expression.
ITERATION STATEMENTS
Java’s iteration statements are for, while, and do-while. These statements create what we
commonly call loops. As you probably know, a loop repeatedly executes the same set of
instructions until a termination condition is met.
WHILE
The while loop is Java’s most fundamental loop statement. It repeats a statement or block
while its controlling expression is true. Here is its general form:
The condition can be any Boolean expression. The body of the loop will be executed as long
as the conditional expression is true. When condition becomes false, control passes to the
next line of code immediately following the loop. The curly braces are unnecessary if only a
single statement is being repeated
DO-WHILE
The do-while loop always executes its body at least once, because its conditional expression
is at the bottom of the loop. Its general form is
FOR
Beginning with JDK 5, there are two forms of the for loop. The first is the traditional form
that has been in use since the original version of Java. The second is the newer “for-each”
form.
Here is the general form of the traditional for statement:
The for loop operates as follows. When the loop first starts, the initialization portion of the
loop is executed. Generally, this is an expression that sets the value of the loop control
variable, which acts as a counter that controls the loop. It is important to understand that the
initialization expression is executed only once. Next, condition is evaluated. This must be a
Boolean expression. It usually tests the loop control variable against a target value. If this
expression is true, then the body of the loop is executed. If it is false, the loop terminates.
Next, the iteration portion of the loop is executed. This is usually an expression that
increments or decrements the loop control variable. The loop then iterates, first evaluating the
conditional expression, then executing the body of the loop, and then executing the iteration
expression with each pass. This process repeats until the controlling expression is false.
JUMP STATEMENTS
Java supports three jump statements: break, continue, and return. These statements transfer
control to another part of your program.
Break
In Java, the break statement has three uses. First, as you have seen, it terminates a statement
sequence in a switch statement. Second, it can be used to exit a loop. Third, it can be used as
a “civilized” form of goto.
Using continue
Sometimes it is useful to force an early iteration of a loop. That is, you might want to
continue running the loop but stop processing the remainder of the code in its body for this
particular iteration.
Here is an example program that uses continue to cause two numbers to be printed on each
line:
Return
The last control statement is return. The return statement is used to explicitly return from a
method. That is, it causes program control to transfer back to the caller of the method.
At any time in a method, the return statement can be used to cause execution to branch back
to the caller of the method. Thus, the return statement immediately terminates the method in
which it is executed.
Questions:
1. List out the 2 paradigms of programming
2. What is type casting illustrate with examples
3. Explain initialization of 1D, 2D arrays in java
4. Explain the OOP concepts
5. Illustrate for each with example
6. Demonstrate the usage of Jump statements
7. Exaplin javas selection commands
8. Bring out the difference between >>, >>>, <<