Chapter One
Chapter One
Using Java
Chapter One
Fundamental Programming Structures
in Java
Section I
Overview of OOP
2 Belay Kal
Objectives
Learn about programing paradigm
structured Vs object oriented paradigm
Understanding OOP concepts and features
Learn the basics of java programming language:
Tokens: Identifiers, Separators, Operators, keywords &
Literals
Constants, variables and primitive data types
The main() method
Control statements: if, switch
3
Loop statements: while, do…while, for and Jumps in
Belay Kal
Overview of programming
•Programming paradigm is a way of conceptualizing what it means
to perform computation and how tasks to be carried out and
organized on a computer.
I. Structured Programing
Problem solving would involve the analysis of processes in terms
of the procedural tasks carried out and the production of a
system whose representation is based on the procedural flow of
the processes.
data is separate from code.
programmer is responsible for organizing everything in to logical
units of code/data
4 Belay Kal
A procedural program is divided into functions, and (ideally, at least)
each function has a clearly defined purpose & a clearly defined interface
to the other functions in the program.
7 Belay Kal
Basic concepts of OOP
Objects and Classes
A. Object: is a software bundle that has State and
Behavior and it occupies memory
Example: dogs have states (name, color, hungry, breed) and behaviors
(bark, fetch, and wag tail).
•Software Objects are often used to model real world objects.
B. Class: is the template or blueprint that defines
the states and the behaviors common to all objects
of a certain kind.
•It is a collection of objects of similar type.
•Classes are user defined data types & behave like the
built in types of programming language.
8 Belay Kal
Message
Software objects interact and communicate with each other
by sending messages to each other.
The process of programming in object oriented language,
therefore, involves the following three basic steps:
i. Creating classes that define objects and their behavior.
ii. Creating objects from class definitions.
iii. Establishing communication among objects.
10
I. Data Abstraction & Encapsulation
The wrapping up of data and methods into a single unit
(called class) is known as encapsulation.
This insulation of the data from direct access by the
program is called data hiding.
Abstraction refers to the set of representing essential
features without including the background details or
explanations
Classes use the concept of data abstraction, and they are
known as Abstract Data Types (ADT)
II. Inheritance
• Is the process by which objects of one class acquire the properties of
objects of another class.
• It provides the idea of reusability
III. Polymorphism
• Is the ability to take more than one form.
• Plays an important role in allowing objects having different internal
structures to share the same external interface.
Three types of polymorphism:
Overloading methods
Overriding methods, and
Dynamic method binding
12 Belay Kal
Overloaded methods: methods with the same
name signature but either a different number of
parameters or different types in the parameter list
Overridden methods are methods that are
redefined within an inherited or subclass
They have the same signature and the subclass definition
is used
15 Belay Kal
Java Overview
Java is a general purpose, object oriented programming language
developed by Sun Microsystems of USA in 1991.
Java applications are object code portable as long as a Java
virtual machine is implemented for the target machine.
The java object oriented programming framework promotes
reusability of software and code.
The Java foundation class libraries provide for windowing and
graphical user interface programming, network communications,
and Multimedia facilities. Together, they demonstrate the practical
and productive work done in Java.
16 Belay Kal
Java Features
I. Compiled and Interpreted
Java combines both these approaches thus makes it a
two stage system.
Java compiler translates the source code into bytecode
instructions
Java interpreter generates the machine code that can be
directly executed by the machine that is running the
java program.
17 Belay Kal
How it Works?
Compile time Environment Run time Environment
Class
Loader Java
Class
Bytecode Libraries
Java Verifier
Source
(.java)
Just in
Java Java
Time
Bytecodes Interpreter Java
Compiler
move locally Virtual
or through machine
Java
network
Compiler
Runtime System
22 Belay Kal
VII. Multithreaded and interactive
24 Belay Kal
Differences Between Java and C++
Java does not support operator overloading.
Java does not have template classes as in C++.
Java does not support multiple inheritance.
• This is accomplished using a new feature called
“interface”
Java does not support global variables.
• Every variable and method is declared within a class
and forms part of that class.
Java does not use pointers
Java has replaced the destructor function with a finalize()
function
There are not header files in Java.
25 Belay Kal
Java Environment
Java environment includes a large number of development tools
and hundreds of classes and Methods.
The development tools are part of the system known as Java
Development Kit (JDK) and the classes and methods are part of
the Java Standard Library (JSL), also known as Application
Programming Interface (API).
JDK comes with a collection of tools that are used for developing
and running java programs:
appleviewer (for viewing java applets )
javac (java compiler)
java (java interpreter)
javap (java disassembler)
javah (for C header files)
javadoc (for creating HTML documents)
jdb (Java debugger)
26 Belay Kal
Java API
It includes hundreds of classes and methods grouped into
several functional packages.
Most commonly used packages are:
Language Support Package: a collection of classes and methods
required for implementing basic features of java.
Utilities Package: a collection of classes to provide utility functions
such as date and time functions.
Input/output Package: a collection of classes required for input/output
manipulation.
Networking Package: a collection of classes for communicating with
other computers via Internet.
AWT Package (Abstract Window Tool kit package): contains classes
that implements platform independent graphical user interface.
Applet Package: includes set of classes that allows us to create java
applets.
27
Belay Kal
Section III
Overview of Java Programing
Language
28 Belay Kal
Introduction
Java is a general purpose, object oriented programming
language.
We can develop two types of Java programs namely:
Stand alone application
Web applets
29 Belay Kal
Compiler
31 Belay Kal
Let us discuss the program line by line:
• Class Declaration: the first line class Sample declares a
class, which is an object constructor. Class is keyword
and declares a new class definition and Sample is a java
identifier that specifies the name of the class to be
defined.
• Opening Brace “{“: Every class definition in java begins
with an opening brace and ends with a closing brace “}”.
• The main line: the third line public static void
main(String args[]) defines a method named as main.
32 Belay Kal
Note:
A java program can have any number of classes but
only one of them must include the main method to
initiate the execution.
Java applets will not use the main method at all.
35 Belay Kal
Documentation Section
comprises a set of comment lines giving the name of
the program, the author and other details, which the
programmer would like to refer at a later stage.
Java supports three types of comments:
i. Single line comment //
ii. Multiple line comment /*………………
………………*/
iii. Documentation comment /**….*/
• This form of comment is used for generating
36 documentation automatically.
Belay Kal
Package Statement
Is the first statement in Java file and is optional.
It declares a package name and informs the compiler that
the classes defined here belong to this package.
Example: package student;
import statements
Next to package statements (but before any class
definitions) a number of import statements may exist. This
is similar to #include statements in C or C++.
Using import statements we can have access to classes
that are part of other named packages.
Example: import [Link];
37 Belay Kal
interface Statements
An interface is like a class but includes a group of method
declarations.
is also an optional section.
is used only when we wish to implement the multiple
inheritance features in the program
Class Definitions
A Java program may contain multiple class definitions.
Classes are the primary and essential elements of a Java
program.
These classes are used to map objects of real world
problems.
38 Belay Kal
Main Method Class
Since every Java stand alone program requires a main
method as its starting point, this class is the essential part
of a Java program.
A simple Java program may contain only this part.
The main method creates objects of various classes and
establishes communications between them.
On reaching the end of main, the program terminates and
control passes back to the operating system.
39 Belay Kal
Section IV
Java Tokens
40 Belay Kal
Introduction
A class in java is defined by a set of declaration
statements and methods containing executable
statements.
Most statements contain expressions, which describe the
actions carried out on data.
Smallest individual units in a program are known as
tokens.
In simplest terms, a java program is a collection of tokens,
comments, and white
41 spaces.
Belay Kal
1. Keywords
Are essential part of a language definition and can not be
used as names for variables, classes, methods and so on.
Java language has reserved 60 words as keywords.
42 Belay Kal
2. Identifiers
Are programmer designed tokens.
Are used for naming classes, methods, variables,
objects, labels, packages and interfaces in a program.
Java identifiers follow the following rules:
They can have alphabets, digits, and the underscore
and dollar sign characters.
They must not begin with a digit
Uppercase and lowercase letters are distinct.
43
They can be ofBelay
anyKallength.
POP QUIZ
1) $amount 5) score
2) 6tally 6) first Name
3) my*Name 7) total#
4) salary 8) cast
44 Belay Kal
3. Literals
Literals in Java are a sequence of characters(digits,
letters and other characters) that represent constant
values to be stored in variables.
Five major types of literals in Java:
I. Integer Literals: refers to a sequence of digits (decimal integer,
octal integer and hexadecimal integer)
II. Floating point Literals
III. Character Literals
IV. String Literals
45
V. Belay Kal
Boolean Literals
4. Separators
Are symbols used to indicate where groups of code are
divided and arranged.
They basically define the shape and functions of our
code.
Java separators include:
I. Parenthesis ( ) :- used to enclose parameters, to
define precedence in expressions, surrounding cast
types
II. Braces { } :- used to contain the values of
46 Belay Kal
Contd.
III. Brackets [ ] :- are used to declare array types and
for dereferencing array values.
IV. Semicolon ; :- used to separate statements.
V. Comma , :- used to separate consecutive identifiers
in a variable declaration, also used to chain
statements together inside a “for” statement.
VI. Period . :- Used to separate package names from
sub package names and classes; also used to
separate a variable or method from a reference
47 Belay Kal
5. Operators
Are symbols that take one or more arguments
(operands) and operates on them to a produce a result.
Are used to in programs to manipulate data and
variables.
They usually form a part of mathematical or logical
expressions.
int x = 3;
int y = 5;
boolean result;
3) result = (x != x*y);
now result is assigned the value true because the product of
x and y (15) is not equal to x (3)
52 Belay Kal
C. Logical Operators
Symbol Name
&& Logical AND
|| Logical OR
! Logical NOT
Logical operators can be referred to as boolean
operators, because they are only used to combine
expressions that have a value of true or false.
The logical operators && and || are used when we want
to form compound conditions by combining two or
more relations.
An expression which combines two or more relational
expressions is termed as a logical expression or a
compound relational
Belayexpression.
Kal 53
Examples of Logiacal Operators
boolean x = true;
boolean y = false;
boolean result;
int a=110;
float b=23 5;
61 the expression a+b
Belayyields
Kal a floating point number 133 5
Contd.
B. Casting a value: is used to force type conversion.
The general form of a cast is:
(type name)expression;
where type name is one of the standard data types.
Example :
62 Belay Kal
Operator Precedence and Associativity.
Operator Description Associativity Rank
. Member Selection
() Function call
Left to right 1
[] Array elements reference
- Unary Minus
++ Increment
-- Decrement
! Logical negation Right to left 2
~ One’s complement
(type) Casting
* Multiplication
/ Division Left to right 3
% Modulus
63 Belay Kal
Contd.
Operator Description Associativity Rank
+ Addition
Left to right 4
- Subtraction
<< Left Shift
>> Right Shift Left to right 5
>>> Right shift with zero fill
< Less than
<= Less than or equal to
> Greater than Left to right 6
>= Greater than or equal to
instanceof Type comparison
== Equality
!= Inequality Left to right 7
64 Belay Kal
Operator Precedence and Associativity.
Operator Description Associativity Rank
& Bitwise AND Left to right 8
^ Bitwise XOR Left to right 9
| Bitwise OR Left to right 10
&& Logical AND Left to right 11
|| Logical OR Left to right 12
?: Conditional Left to right 13
Operator
= Assignment Left to right 14
operator
Op= Shorthand Left to right 15
assignment
65 Belay Kal
//Demonstration of Java Expressions
public class DemoExpress
{
public static void main(String[] args)
{
[Link]("===== BEGINNING OF THE PROGRAM
=====\n");
//Declaration and Initialization
int a=10,b=5,c=8,d=2;
float x=6 4f,y=3 0f;
//Order of Evaluation
int answer1=a*b+c/++d;
int answer2=--a*(b+++c)/d++;
//Type Conversion
float answer3=a/c;
66 Belay Kal
float answer4=(float)a/c;
//Modulo Operations
int answer6=a%c;
float answer7=x%y;
//Logical Operations
boolean bool1=a>b && c>d;
boolean bool2=a<b && c>d;
boolean bool3=a<b || c>d;
boolean bool4=!(a b==c);
[Link]("Order of Evaluation");
[Link]("a*b+c/++d + "+answer1);
[Link]("--a*(b+++c)/d++ = " +answer2);
[Link]("================");
[Link]("Type Conversion");
[Link](" a/c = "+answer3);
[Link]("(float)a/c = " + answer4);
67 Belay Kal
[Link](" a/y = " + answer5);
[Link]("================");
[Link]("Modulo Operations");
[Link](" a%c = "+answer6);
[Link](" x%y = "+answer7);
[Link]("================");
[Link]("Logical Operations");
[Link](" a>b && c>d = "+bool1);
[Link](" a<b && c>d = "+bool2);
[Link](" a<b || c>d = "+bool3);
[Link](" !(a b==c) = "+bool4);
[Link]("================");
[Link]("Bitwise Operations");
68 Belay Kal
//Shift Operators
int l=8, m=-8,n=2;
[Link](" n & 2= "+(n&2));
[Link](" l | n= "+(l|n));
[Link](" m | n= "+(m|n));
[Link](" l >> 2= "+(l>>2));
[Link](" l >>> 1= "+(l>>>1));
[Link](" l << 1= "+(l<<1));
[Link](" m >> 2= "+(m>>2));
[Link](" m >>> 1= "+(m>>>1));
[Link]("\n===== END OF THE PROGRAM =====");
}
69 Belay Kal
POP QUIZ
1) What is the value of number?
int number = 5 * 3 – 3 / 6 – 9 * 3; -12
71 Belay Kal
Variables
A variable is an identifier that denotes a storage location
used to store a data value.
Unlike constants, that remain unchanged during the
execution of a program, a variable may take different
values at different times during the execution of the
program.
It is good practice to select variable names that give a
good indication of the sort of data they hold:
For example, if you want to record the size of a hat,
hatSize is a good choice for a name whereas qqq
would be a bad choice.
72
Belay Kal
Contd.
Variable names may consist of alphabets, digits, the
underscore (_) and dollar ($) characters, subject to the
following conditions:
1. They should not begin with a digit.
2. Keywords should not be used as a variable name.
3. White spaces are not allowed.
4. Uppercase and lowercase are distinct. i.e. A rose is
not a Rose is not a ROSE.
5. Variable names can be of any length.
73 Belay Kal
Data Types
Every variable in Java has a data type.
Data types specify the size and type of values that can
be stored.
Java is language is rich in the data types.
Java data types are of two type:
Primitive Data Types (also called intrinsic or built in
data types)
Non-Primitive data Types (also known as Derived
or reference types)
74 Belay Kal
Data Types in
Java
Non-
Primitive
Primitive
(Intrinsic)
(Derived)
Interfaces
Floating- Characte
Integer Boolean
Point r
77 Belay Kal
B. Floating-Point Types
Integer types can hold only whole numbers and therefore
we need another type known as floating point type to hold
numbers containing fractional parts.
There are two data types that can be used to store
decimal values (real numbers).
78 Belay Kal
C. Character Type
Is used to store character constants in memory.
Java provides a character data type called char
The char data type assumes a size of 2 bytes but, basically,
it can hold only a single character.
Note that you need to use singular quotation marks while
initializing a variable whose data type is char.
Example:
char firstLetterOfName = 'e' ;
char myQuestion = '?' ;
79 Belay Kal
D. Boolean Type
Boolean is a data type used when we want to test a
particular condition during the execution of the program.
There are only two values that a Boolean can take: true or
false.
Boolean type is denoted by the keyword boolean and uses
only one bit of storage.
All comparison operators return boolean type values.
Boolean values are often used in selection and iteration
statements.
80 Belay Kal
Declaration of Variables
After designing suitable variable names, we must declare them to
the compiler. Declaration does three things:
1. It tells the compiler what the variable name is
2. It specifies what type of data the variable will hold
3. The place of declaration (in the program) declares the scope of the variable.
A variable must be declared before it is used in the program.
The general form of declaration of Variables is:
type variable1, variable2,...., variableN;
Example:
int count, x,y; //Declaration
char firstLetterOfName = 'e' ; // Declaration & initialization
81 Belay Kal
Assigning Values to Variables
A variable must be given a value after it has been declared but before
it is used in an expression in
two ways:
By using an assignment statement
By using a read statement
Assignment Statement
A simple method of giving value to a variable is through
the assignment statement as follows:
variableName = value;
Example: x = 123, y = -34;
It is possible to assign a value to a variable at the time
typeKalvariableName = value;
of declaration as:Belay 82
Keyboard Input
To assign value for variables interactively through the keyboard, we first
create a Scanner object, that is attached to the [Link] data stream
object
E.g. Scanner input = new Scanner([Link]);
Then use the various methods of the Scanner class to read input.
For example, the nextLine() method reads a line of string input
E.g. [Link]("What is your name? ");
String name = [Link]();
nextInt(), nextDouble() etc are methods to read.
We must import [Link].*; package so as to use the Scanner class.
83 Belay Kal
Sample Program for I/O
import [Link].*;
public class InputTest
{
public static void main(String[] args)
{
Scanner in = new Scanner([Link]);
[Link]("What is your name? ");
String name = [Link](); // gets first input
[Link]("How old are you? ");
int age = [Link](); // gets second input
[Link]("Hello, " + name + ". Next year, you'll be " + (age + 1))
;
// display output on console
}
}
84 Belay Kal
Scope of Variables
1. Instance Variables: are declared in a class, but outside a method,
constructor or any block.
•are created when an object is created with the use of the key word 'new' and
destroyed when the object is destroyed.
•They take different values for each object
2. Class Variables: are also known as static variables,
are declared with the static keyword in a class, but outside a method,
constructor or a block.
•Are global to a class and belong to the entire set of objects that class creates.
•Only one memory location is created for each class variable.
3. Local Variables: are variables declared and used
inside methods.
•Can also be declared inside program blocks that are define between { and }.
85 Belay Kal
Section VI
Control Structures
86 Belay Kal
Introduction
The statements inside your source files are generally executed
from top to bottom, in the order that they appear.
Control flow statements, however, break up the flow of
execution by employing decision making, looping, and
branching, enabling your program to conditionally execute
particular blocks of code.
Two types of control structures in Java:
•Decision Making (if, switch, conditional Operator statements )
•Loops (while, do….while and for statements)
87 Belay Kal
Decision Making Statements
allows the code to execute a statement or block of
statements conditionally.
Control the execution flow of a program causing a jump
to any point from its current location.
Java supports types of decision making statements:
• if Statements
• switch Statements
88 Belay Kal
Decision Making with if Statement
The if statement is a powerful decision making statement.
Test False
expression
?
True
93 Belay Kal
4. Nested if … else Statement
if…else statements can be put inside other if…else
statements. such statements are called nested if … else
statements.
Is used whenever we need to make decisions after
checking a given decision.
The syntax of a nested if…else statement is shown in the
next slide.
True block statement 1 1 is executed if both expression 1
and expression 1 1 are true. But if expression 1 is true and
if expression 1 1 is false, then it is False block statement
1 1 which is going to be executed.
94 Belay Kal
}
if (expression 1)
{
statement(s)-1;
if (expression 1 1)
{
True block Statement 1 1
} Nested if
else
{ statement
Falsse block Statement 1 1
}
}
else if (expression 2)
{
statement(s)-2;
}
...
else if (expression n)
{
statement(s)-n;
}
else
default statement;
rest_of_program;
95 Belay Kal
Switch statement
We can design a program with multiple alternatives using
if statements to control the selection.
But the complexity of such programs increases
dramatically when the number alternatives increases.
Java has a multiway decision statement called switch
statement.
The switch statement tastes the value of a given
variable(expression) against a list of case values and
when a match isBelay
96 found,
Kal
a block of statements associated
Switch syntax
switch (expression)
{
case value-1:
statement block 1;
break;
case value-2:
statement block 2;
break;
......
......
default:
default_statement;
break;
}
rest_of_programBelay Kal
97
Contd.
The expression must evaluate to a char, short or int, but
not long, float or double.
The values value-1, value-2, value-3, … are constants or
constant expressions (evaluable to an integral constant)
and are known as case labels.
Each of the case labels should be unique within the
switch statement.
statement block1,statement block2,…. Are statement
lists and may contain
98 zero
Belay Kal
or more statements.
Contd.
There is no need to put braces around the statement blocks of
a switch statement but it is important to note that case labels
end with a colon (:).
When the switch is executed, the value of the expression is
successfully compared against the values value-2, value-2, ….
If a case is found whose value matches with the value of the
expression, then the block of the statement(s) that follows the
case are executed; otherwise the default statement will be
executed.
99 Belayat
The break statement Kalthe end of each block signals the end
The ?: (Conditional)Operator
Is useful for making a two way decisions.
Example:
for(sum=0, i=1; i<20 && sum<100; ++i)
{
sum=sum+i;
}
D. You do not have to fill all three control sections, one or
more sections can be omitted but you must still have
two semicolons.
Example:
int n = 0;
for(;
116 n != 100;) { Belay Kal
Nesting of for loops
You can nest loops of any kind one inside another to any
depth.
Example:
for(int i = 10; i > 0; i--)
{
while (i > 3)
{ Inner Outer
Loop Loop
if(i == 5){
break;
}
[Link](i);
i--;
}
117 [Link](i*2);
Belay Kal
Jumps in Loops
Jump statements are used to unconditionally transfer the
program control to another part of the program.
Java has three jump statements: break, continue, and
return.
1. The break statement
A break statement is used to abort the execution of a loop.
The general form of the break statement is given below:
break label;
It may be used with or without a label.
When it is used without a label, it aborts the execution of
the innermost switch, for, do, or while statement enclosing
the break statement. When used with a label, the break
118 statement aborts theKalexecution of any enclosing statement
Belay
Examples:
1) Outer: for( int k=1; k< 10; k++){
int i=k;
while ( i < 5) {
if(i%5==0) break Outer; // jump out of both loops
[Link](“ “+i);
i++;
}
[Link](“Outer Loop”);
}
2) int i=1;
while ( i < 10) {
if(i%2==0) break;
[Link](“ “+i);
}
[Link](“Out of the while loop”);
119
2. The continue statement
is used to alter the execution of the for, do, and while
statements.
The general form of the continue statement is:
continue label;
It may be used with or without a label. When used without
a label, it causes the statement block of the innermost for,
do, or while statement to terminate and the loop’s boolean
expression to be re evaluated to determine whether the
next loop repetition should take place.
120 Belay Kal
Contd.
When it is used with a label, the continue statement
transfers control to an enclosing for, do, or while
statement matching the label.
Example:
int sum = 0;
for(int i = 1; i <= 10; i++){
if(i % 3 == 0) {
continue;
}
sum += i;
}
What is the value1 of
+ 2sum?
+ 4 + 5 + 7 + 8 + 10 = 37
121 Belay Kal
3. The return Statement
A return statement is used to transfer the program
control to the caller of a method.
The general form of the return statement is given below:
return expression;
If the method is declared to return a value, the
expression used after the return statement must
evaluate to the return type of that method. Otherwise,
the expression is omitted.
122 Belay Kal
//Use of Continue and break Statements
class ContinueBreak
{
public static void main(String [ ]args)
{ *
Loop1: for(int i=1; i<100; i++) ** Outpu
t
{ ***
[Link](" "); ****
if (i>=8) break;
for (int j=1; j<100; j++)
*****
{ ******
[Link]("*"); *******
if (j==i) continue Loop1; Termination by BREAK
}
}
[Link]("Termination by BREAK");
}
123 Belay Kal
Exercise
1. What do the following program print?
Example:
int number[];
float slaray[];
float[] marks;
StringBuffer