0% found this document useful (0 votes)
3 views154 pages

Chapter One

This document provides an overview of Object-Oriented Programming (OOP) using Java, detailing fundamental programming structures, OOP concepts, and features. It covers the basics of Java, including its programming paradigm, key concepts like classes and objects, and the advantages of Java as an object-oriented language. Additionally, it discusses Java's features, environment, and differences from C++, along with a simple Java program example.

Uploaded by

majiokgatwech8
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views154 pages

Chapter One

This document provides an overview of Object-Oriented Programming (OOP) using Java, detailing fundamental programming structures, OOP concepts, and features. It covers the basics of Java, including its programming paradigm, key concepts like classes and objects, and the advantages of Java as an object-oriented language. Additionally, it discusses Java's features, environment, and differences from C++, along with a simple Java program example.

Uploaded by

majiokgatwech8
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Object-Oriented Programming (OOP)

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.

Programs with Structural Programming


1. Unrestricted Access
 Functions have unrestricted access to global data.
2. Real-World Modeling
 Unrelated functions and data, the basics of the procedural paradigm,
provide a poor model of the real world.
3. Difficult of Creating New Data Types
 Traditional languages are not extensible because they will not let you
create new data types.
5 Belay Kal
II. OOP Approach
 A modern programming paradigm that allows the
Programmer to model a problem in a real world fashion
as an object.
 Major objective is to eliminate some of the unfavorable
features encountered in the procedural approach.
 Ties data more closely to the functions that operate on it
and protects it from unintentional modification by other
functions.
 Allows
6 us to decompose
Belay Kal a problem into a number of
Object oriented paradigm features
•Emphasis is on data rather than procedure
•Programs are divided into what are known as objects
•Methods that operate on the data of an object are tied together in the data structure
•Data is hidden and can’t be accessed by external functions
•Objects may communicate with each other through methods
•New data and methods can be easily added whenever necessary
•Follows bottom up approach in program design
•First, the individual base elements of a program are specified (Objects with their data
structures and methods)
•Then they are linked together to form larger subsystems (using algorithm)
•Structured approach is top down (algorithm comes first, then the data structure)

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.

•A message for an object is a request for execution of a


procedure, and therefore will invoke a method (procedure)
Belay Kalthat generates the desired result.
in the receiving object
9
OOP’s fundamental building blocks:
I. Data Abstraction and
Encapsulation
II. Inheritance
III. Polymorphism

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

Dynamic binding means that the code associated

13 with a given procedure call is not known until the


Object Orientation
 is a set of tools and methods that enable software engineers
to build reliable, user friendly, and maintainable, well
documented, reusable software systems that fulfills the
requirements of its users.
 It is claimed that object orientation provides software
developers with new mind tools to use in solving a wide
variety of problems.
 A software system is seen as a community of objects that
cooperate with each other by passing messages in solving a
problem.
14 Belay Kal
Section II
Basics of Java Programing Language

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

Java Operating System


Bytecode
(.class )
Hardware
18
Belay Kal
Java Virtual Machine (JVM)
 Java compiler produces an intermediate code known as bytecode
for a machine that does not exist. This machine is known as Java
Virtual Machine (JVM) & it exists only inside computer memory.
 It is a simulated computer within the computer and does all major
functions of the real computer.
 The JVM is responsible in interpreting bytecode to machine
understandable code (Machine code).
 Just In Time compiler (JIT), part of the JVM, is responsible for
compiling code as it is needed, during
execution.
19 Belay Kal
II. Platform independent and Portable
 “compile once and execute many times in many platforms”
 Most significant contribution of java over other languages is its
portability. i.e. Java programs can be easily moved from one
computer system to another, anywhere and anytime.
 Changes and upgrades in operating systems, processors and
system resources will not force any changes in java programs.
 Java ensures portability in two ways:
i. Java compiler generates bytecode instructions that can be
implemented on any machine
ii. The size of the primitive data types are machine independent
20 Belay Kal
III. Object oriented
 Java is true object oriented programming language.
 All program code and data reside within objects and classes.
IV. Robust and Secure
 It has strict compile time and run time checking for data types.
 It is designed as a garbage collected language relieving the
programmers virtually all memory management problems.
 It also incorporates the concept of exception handling which
captures serious errors and eliminates any risk of chasing the
system.
 Java systems ensure that no viruses are communicated within
applet programs
21 Belay Kal
V. Distributed
 Java is designed as a distributed language for creating applications
on networks.
 It has the ability to share both data and programs.
 Java applications can open and access remote objects on Internet
as easily as they can do in a local system.
VI. Simple, Small and Familiar
 Java is a small and simple language even easier than C and C++.
 Java doesn’t use pointers, preprocessor header files, goto
statement and many others. To make the language look familiar to
the existing programmers, java uses many constructs of C and C++.

22 Belay Kal
VII. Multithreaded and interactive

 Multithreaded means handling multiple tasks simultaneously.


 Java supports multithreaded programs: We don’t need to wait for the
application to finish one task before beginning another task.
 The java runtime comes with tools that support multiprocessor
synchronization and construct smoothly running interactive
systems.
VIII. Dynamic and Extensible

 Java allocates memory at runtime not at compile time.


 Java is capable of dynamically linking in new class libraries, methods, and
objects.
 Java program supports functions written in other languages such as C and
C++. Such functions are know as native methods
 Native methods are linked dynamically at runtime.
23 Belay Kal
Disadvantages of Java
 Running bytecode through the interpreter is not as fast
as running machine code, which is specific to that
platform.
 Because it is platform independent, it is difficult to use
platform specific features (e.g., Windows taskbar, quick
launch) in Java.
 Java interpreter must be installed on the computer in
order to run Java programs.

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

 Executing stand alone Java program involves two steps:


•Compiling source code into byte code javac compiler.
•Executing the bytecode program using java interpreter.
 Applets are small programs developed for Internet applications.
 An applet located on a distant computer (server) can be
downloaded via Internet and executed on a local computer
(client) using a Java capable browser.

29 Belay Kal
Compiler

Two Ways of writing Java Programs


30 Belay Kal
Simple Java Program
The simplest way to learn a new language is to write a
few simple example programs and execute them.

public class Sample


{
public static void main (String args [])
{
[Link](“Java is better than C++.”);
}
}

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.

 The third line uses a number of keywords: public, static


and void
 Public: is an access specifier that declares the main
method as “unprotected” and therefore making it
accessible to all other classes.
 static: declares that this method as one that belongs to
the entire class and not a part of any objects of the
class.
33  Main must always be declared as static since the
Belay Kal
Contd.
 All parameters to a method are declared inside a pair of
parenthesis. Here, String args[ ] declares a parameter
named args, which contains array of objects of the class
type String.
 The Output Line: The only executable statement in the
program is [Link](“Java is better than C++.”);
 This is similar to cout<< constructor of C++.
 The println method is a member of the out object,
which is a staticBelay Kalmember of System class.
34
data
Java Program Structure

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

Which of the following are valid Identifiers?

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.

Expressions can be combinations of variables,


primitives and operators that result in a value.
48 Belay Kal
Java Operators
There are 8 different groups of operators in Java:
Arithmetic operators
Relational operators
Logical operators
Assignment operator
Increment/Decrement operators
Conditional operators
Bitwise operators
49 Special operators
Belay Kal
A. Arithmetic Operators
Java has five basic arithmetic operators
Operator Meaning
+ Addition or unary plus
– Subtraction or unary minus
* Multiplication
/ Division
% Modulo division

They all work the same way as they do in other


languages.
We cannot use these operators on boolean type .
Unlike C and C++, modulus operator can be applied to
the floating point data.
50 Belay Kal(or precedence) when evaluating
Order of operations
B. Relational Operators
Relational operators compare two values
Produces a boolean value (true or false) depending on the
relationship.
Java supports six relational operators:
Operator Meaning
< Is less than
<= Is less than or equal to
> Is greater than
>= Is greater than or equal to
== Is equal to
!= Is not equal to

Relational expressions are used in decision statements such


as, if and while to decide the course of action of a running
51 program. Belay Kal
Examples of Relational Operations

int x = 3;
int y = 5;
boolean result;

1) result = (x > y);


now result is assigned the value false because
3 is not greater than 5

2) result = (15 == x*y);


now result is assigned the value true because the product of
3 and 5 equals 15

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;

1. Let result = (x && y);

now result is assigned the value false


(see truth table!)
2. Let result = ((x || y) && x);
(x || y) evaluates to true
(true && x) evaluates to true
54 now result isBelay
assigned
Kal the value true
4. Assignment Operator
Are used to assign the value of an expression to a
variable.
In addition to the usual assignment operator(=), java
has a set of ‘shorthand’ assignment operators which
are used in the form:
var op = expr ;
Where var is a variable, op is a binary operator and expr is an
[Link] operator op= is known as shorthand assignment
operator.
The assignment statement: var op= expr; is
equivalent to var=var op(expr);
Examples:
x += y + 5; is equivalent to x = x+(y+5);
55 Belay Kal
y *= 7; is equivalent to y = y * 7;
5. Increment/Decrement Operators
count = count + 1;
can be written as:
++count; or count++;

++ is called the increment operator.


count = count - 1;
can be written as:
--count; or count--;

-- is called the decrement operator.


Both ++ and --
56
are
Belay Kal unary operators.
The increment/decrement operator has two forms:
The prefix form ++count, --count
first adds/subtracts1 to/from the variable and then continues
to any other operator in the expression
int numOranges = 5;
int numApples = 10;
int numFruit;
numFruit = ++numOranges + numApples;
numFruit has value 16
numOranges has value 6

The postfix form count++, count--


first evaluates the expression and then adds 1 to the variable
int numOranges = 5;
int numApples = 10;
int numFruit;
numFruit = numOranges++ + numApples;
numFruit has valueBelay
15 Kal 57
numOranges has value 6
6. Conditional Operators
The character pair ?: is a ternary operator available in
java.
It is used to construct conditional expression of the
form:
exp1 ? exp2: exp3;
where exp1, exp2 and exp3 are expressions.
The operator ?: works as follwos:
exp1 is evaluated first. If it is nozero (true), then the
expression exp2 is evaluated and becomes the value of
the conditional expression. exp3 is evaluated and becomes
the value of the conditional expression if exp1 is false.
Example:
Given a=10, b=15 the expression
58 Belay Kal
6. Bitwise Operators
One of the unique features of java compared to other high-
level languages is that it allows direct manipulation of
individual bits within a word.
Bitwise operators are used to manipulate data at values of
bit level.
They are used for testing the bits, or shifting them to the
right or left.
Operator Meaning
They may not be applied to float or double data types.
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ One’s complement
<< Shift left
>> Shift right
>>> Shift right with zero fill
59 Belay Kal
7. Special Operators
Java supports some special operators of interest such as
instanceof operator and member selection operator(.).

71 instanceof Operator: is an object reference operator and returns


true if the object on the left hand side is an instance of the class
given on the right hand side.
Example :
person instanceof student;
is true if the object person belongs to the class student;
otherwise it is false
72 Dot Operator: is used to access the instance variables and
methods of class objects.
Example:
[Link]; // Reference to the variable age.
[Link]();Belay
// Reference
Kal to the method salary.
Type Conversion in Expressions
A. Automatic Type Conversion: If the operands of an
expression are of different types, the ‘lower’ type is
automatically converted to the ‘higher’ type before the
operation proceeds. That is, the result is of the ‘higher’
type.
Example :

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 :

x=(int)75; will assign 7 to x


a=(int)21 3/(int)3 5; a will be 7

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

2) What is the value of result?


int x = 8; false
int y = 2;
boolean result = (15 == x * y);

3) What is the value of result?


boolean x = 7; true
boolean result = (x < 8) && (x > 4);

4) What is the value of numCars?


int numBlueCars = 5;
int numGreenCars = 10; 27
70 Belay Kal
int numCars = numGreenCars++ + numBlueCars + ++numGreeenCars;
Section V
Variables and Primitive Data Types

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)

Non- Classe Array


Numeric
Numeric s s

Interfaces
Floating- Characte
Integer Boolean
Point r

Data Types in Java


75 Belay Kal
Primitive Data Types
 There are eight built in data types in Java:
•4 integer types (byte, short, int, long)
• 2 floating point types (float, double)
• Boolean (boolean)
• Character (char)
 All variables must be declared with a data type
before they are used.
 Each variable's declared type does not change over
the course of the program.
76 Belay Kal
A. Integer Data types
 There are four data types that can be used to store
integers.
 The one you choose to use depends on the size of the
number that we want to store.

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.

 It is basically a two way decision making statement and is used


in conjunction with an expression.

Test False
expression
?
True

 The if statement may be implemented in different forms


depending on the complexity of conditions to be tested:
89 Belay Kal
1. Simple if Statement
 An if statement consists of a Boolean expression followed by
one or more statements.
 The syntax of an if statement is:
if (expression)
{
statement block;
}
rest_of_program;

•If expression is true, statement block is executed and then


rest_of_program.
•If expression is false, statement block will be skipped & the
execution
90 will jumpBelay
to the
Kal
rest_of_program
2. if … else Statement
 The syntax of an if statement is:
if (expression)
{
True block statement(s);
}
else
{
False block statement(s);
}
rest_of_program;

 If expression is true, True block statement is executed and


followed by rest_of_program block.
 If expression is false, False block Statement is excuted followed
by rest_of_program block.
91 Belay Kal
3. if … else if (else if Ladder) Statement
 Is used when multiple decisions are involved.
 A multiple decision is a chain of ifs in which the which the
statement associated with each else is an if.
 The conditions are evaluated from the top(of the ladder),
downwards.
 As soon as the true condition is found, the statement
associated with it is executed and the control will skip the rest
of the ladder.
 When all the conditions become false, then the final else
containing the default statement will be executed.
 The syntax of an if …. else if statement is:
92 Belay Kal
if (expression 1)
{
statement(s)-1;
}
else if (expression 2)
{
statement(s)-2;
}
...
else if (expression n)
{
statement(s)-n;
}
else
default statement;
rest_of_program;

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.

 This operator is a combination of ? and : and takes three


operands.
General formula:
conditional expression ? Expression1:expression2;
 The conditional expression is evaluated first. If the result
is true, expression1 is evaluated and is returned as the
value of the conditional expression. Otherwise,
expression2 is evaluated
100 Belay Kal and its value is returned.
Contd.
 For example:
if (x<=40)
if(x<40) Can be written as:
slary=4*x+100; salary=(x!=40)? ((x<40)? (4*x+100):
else (4 5*x 100)):300;
salary=300;
else
slary=4 5*x+100;
 When the conditional operator is used, the code
becomes more concise and perhaps, more efficient.
However, the reliability is poor.
 It is better to use if statement when more than a single
nesting of conditional
101 operator is required.
Belay Kal
Exercise
1. Find out Errors in the following program and discuss ways for
correction.
a) //[Link]
public Class Errors{
public void main(String [] args){
int i, j = 32768;
short s = j;
double m = 5 3f, n = 2 1f;
float x = 5 3, y = 2 1;
byte z = 128;
[Link]("x % y = "+x % y);
boolean b = 1 ;
if (b) [Link](“b is true”);
else [Link](“b is false”);
}
102
} Belay Kal
2. Write a Java application program that asks the user to enter two numbers
obtains the numbers from the user and prints the sum, product, difference
and quotient of the numbers?
3. Write a Java application program that asks the user to enter two integers,
obtains the numbers from the user and displays the larger number
followed by the words “is larger than “ the smaller number in the screen. If
the numbers are equal, print the message “These numbers are equal.”
4. Write four different Java statements that each add 1 to integer variable x.
5. Rewrite each of the following without 6.
usingWrite
compound relations:
a Java application
a) if(grade<=59 && grade>=50) program that reads the
second+=1; coefficients of a quadratic
b) if(num>100 || num<0) equation (ax2+bx+c=0),
[Link](“Out of Range”); generates and display the roots.
Note:
else An appropriate message should
sum+=num; be generated when the user
c) If((M>60 && N>60)||T>200) types an invalid input to the
y=1; equation.
103 else Belay Kal
Section VI
Decision Making and Looping

104 Belay Kal


Introduction
 The process of repeatedly executing a block of
statements is known as looping.
 A loop allows you to execute a statement or block of
statements repeatedly.
 The statements in the block may be executed any
number of times, from zero to infinite number.
 If a loop continues forever, it is called an infinite loop.

 In looping, a sequence of statements are executed until


105
some conditions from
Belaythe
Kal termination of the loop are
Contd.
 A program loop consists of two statements:
1. Body of the loop.
2. Control statements.
 The control statement tests certain conditions and then directs
the repeated execution of the statements contained in the body
of the loop.
 A looping process, in general, would include the ff. four steps:
1. Setting and initialization of a counter .
2. Execution of the statements in the loop.
3. Test for a specified condition for execution of the loop.
4. Increment/Decrement the counter.
106 Belay Kal
Contd.
 Depending on the position of the control statement in the loop, a
control structure can be either as the entry controlled loop or as exit-
controlled loop.
 In entry controlled loop, the control conditions are tested before the
start of the loop execution.
 In exit controlled loop, the test is performed at the end of the body
of the loop and therefore the body is executed unconditionally for
the first time.
 Three types of loops in java:
1. while loops:
2. do …while loops:
3. for loops:
107 Belay Kal
1. The while loop
 Is the simplest of all the looping structures in Java.

 The while loop is an entry controlled loop statement.

 The while loop executes as long as the given logical


expression between parentheses is true. When
expression is false, execution continues with the
statement immediately after the body of the loop block.
 The expression is tested at the beginning of the loop, so
if it is initially false, the loop will not be executed at all.
108 Belay Kal
Contd.
 The basic format of the while statement is:
Example:
initialization; int sum=0,n=1;
while (expression) while(n<=100)
{ {
sum+=n;
Body of the loop; n++;
} }
[Link](“Sum=“+sum;
 The body of the loop may have one or more statements.
 The braces are needed only if the body contains two or more
statements. However it is a good practice to use braces even
if the body has only
one statement.
109 Belay Kal
2. The do…while loop
 Unlike the while statement, the do… while loop executes the body of the loop
before the test is performed.
initialization;
do
Syntax for do…while {
loop
Body of the loop;
}
while (expression);
 On reaching the do statement, the program proceeds to evaluate the body of
loop first.
 At the end of the loop, the test condition in the while statement is evaluated. If
it is true, the program continues to evaluate the body of the loop once again.
110 Belay Kal
Contd.
 When the condition becomes false, the loop will be
terminated and the control goes to the statement that
appears immediately after the while statement.
 The while loop is an exit controlled loop statement.
Example:
int sum=0,n=1;
do
{
sum+=n;
n++;
} while(n<=100);
[Link](“Sum=“+sum;
111 Belay Kal
3. The for loop
 Is another entry controlled loop that provides a more concise loop
controlled structure.
 Syntax for the for loop is:
for(initialization; test condition; increment)
{
Body of the loop;
}
 We use the for loop if we know in advance for how many times the
body of the loop is going to be executed.
 But use do…. while loop if you know the body of the
loop is going to be executed at least once.
112 Belay Kal
Contd.
 The execution of the for loop statement is as follows:
1. Initialization of the control variable(s) is done first, using
assignment statement.
2. The value of the control variable is tested using the test
condition. The test condition is a relation operation that
determines when the loop will exit.
 If the condition is true, the body of the loop is executed;
otherwise the loop is terminated and the execution
continues with the statement that immediately follows
113 Belay Kal
the loop.
Contd.
3. When the body of the loop is executed, the control is
transferred back to the for statement after evaluating the
last statement in the loop.
 Now the new value of the control variable is again tested
to see whether it satisfies the loop condition; if it does,
the body of the loop is again executed.
Example
int sum=0;
for(n=1; n<=100; n++)
{
sum=sum+n;
}
[Link](“Sum is:”+sum);
114 Belay Kal
Additional Features of for loop
A. More than one variable, separated by comma, can be
initialized at a time in the for statement.
Example:
for(sum=0, i=1; i<=100; i++)
{
sum=sum+i;
}
B. Increment section may also have more than one part.
Example:
for(i=0, j=0; i*j < 100; i++, j+=2)
{
[Link](i * j);
115
} Belay Kal
C. The test condition may have any compound relation and
the testing need not be limited only to the loop control
variable.

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?

public class Mystery3{


public static void main(String args[]){
int row = 10, column;
while(row >= 1){
column = 1;
while(column <= 10){
[Link](row % 2 == 1 ? “<” : “>”);
++column;
}
--row;
[Link]();
}
}
124
} Belay Kal
2. Write a Java application program that asks the user to enter an integer
number from the keyboard and computes the sum of the digits of the
number.
[ Hint: if the user types 4567as input , then the output will be 22 ]
3. Given a number, write a program using while loop to reverse the digits of
the number. [ Hint: Use Modulus Operator to extract the last digit and the integer
division by 10 to get the n-1 digit numberc)
from the n digit]
a) 5
4. Using a two dimensional array, write codes that
4 5 4print the following outputs.
$ $ $ $ $
$ $ $ $ 34543
$ $ $ 2345432
$ $ 123454321
$
b) 1
d) 1 2 3 4 5 4 3 2 1
1 2 1234321
1 2 3 12321
1 2 3 4 121
1 2 3 4 5 1
125 Belay Kal
Section VII
Arrays, Strings and Vectors

126 Belay Kal


Arrays
An array is a group of contiguous or related data items that
share a common name.
is a container object that holds a fixed number of values of a
single type.
Unlike C++ in Java arrays are created dynamically.
An array can hold only one type of data!
Example:
int[] can hold only integers
char[] can hold only characters
A particular values in an array is indicated by writing a number
called index number or subscript in brackets after the array
name.
Example:
127 Belay Kal
Contd.
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.
Array indexing starts from 0 and ends at n-1, where n is
the size of the array. index values

primes[0] primes[1] primes[2] primes[3] primes[4] primes[9]

128 Belay Kal


One-Dimensional Arrays
A list of items can be given one variable name using
only one subscript and such a variable is called a
single subscripted variable or a one dimensional array.
Creating an Array
Like any other variables, arrays must be declared and
created in the computer memory before they are used.
Array creation involves three steps:
1. Declare an array Variable
2. Create Memory Locations
3. Put values into the memory locations.
129 Belay Kal
1. Declaration of Arrays
Arrays in java can be declared in two ways:
i. type arrayname [ ];
ii. type[ ]arrayname;

Example:
int number[];
float slaray[];
float[] marks;

when creating an array, each element of the array


receives a default value zero (for numeric types) ,false for
boolean
130 and nullBelay
for references
Kal (any non primitive types).
2. Creation of Arrays
After declaring an array, we need to create it in the
memory.
Because an array is an object, you create it by using the
new keyword as follows:
arrayname =new type[ size];
Example:
number=new int(5);
marks= new float(7);
It is also possible to combine the above to steps ,
declaration and creation, into on statement as follows:
type arrayname =new type[ size];
131 Belay Kal
3. Initialization of Arrays
Each element of an array needs to be assigned a value;
this process is known as initialization.
Initialization of an array is done using the array subscripts
as follows:
arrayname [subscript] = Value;
Example:
number [0]=23;
number[2]=40;
Unlike C, java protects arrays from overruns and underruns.
Trying to access an array beyond its boundaries will
generate an error.
132 Belay Kal
Contd.
Java generates an ArrayIndexOutOfBoundsException
when there is underrun or overrun.
The Java interpreter checks array indices to ensure that
they are valid during execution.
Arrays can also be initialized automatically in the same
way as the ordinary variables when they are declared, as
shown below:
type arrayname [] = {list of Values};
Example:
133 Belay Kal
Contd.
It is also possible to assign an array object to another
array object.
Example:
int array1[]= {35,40,23,67,49};
int array2[];
array2= array1;
Array Length
In Java, all arrays store the allocated size in a variable
named length.
We can access the length of the array array1using array1.
length. Example:
int size = [Link];
134 Belay Kal
//sorting of a list of Numbers if (num[i] < num [j])
class Sorting {
{ //Interchange Values
public static void main(String [ ] int temp = num[i];
args) num [i] = num [j];
{ num [j] = temp;
int num[ ]= {55, 40, 80, 12, 65, }
77};
}
int size = [Link];
}
[Link](“Given List: “);
[Link]("SORTED LIST" );
for (int i=0; i<size; i++)
for (int i=0; i<size; i++)
{
{
[Link](" " + num[ i ] )
[Link](" " " + num [i])
;
;
}
}
[Link]("\n");
[Link](" ");
//Sorting Begins
}
135for (int i=0; i<size; i++)Belay Kal }
Two-Dimensional Arrays
A 2-dimensional array can be thought of as a grid (or
matrix) of values.
Each element of the 2-D array is accessed by providing
two indexes: a row index and a column index
A 2-D array is actually just an array of arrays.
A multidimensional array with the same number of
columns in every row can be created with an array
creation expression:
Example:
136 Belay Kal
Contd.
Like the one dimensional arrays, two dimensional arrays
may be initialized by following their declaration with a list
of initial values enclosed in braces. For example,
int myarray[2][3]= {0,0,0,1,1,1};
or
int myarray[][]= {{0,0,0},{1,1,1}};
We can refer to a value stored in a two dimensional array
by using indexes for both the column and row of the
corresponding element. For Example,
137
int value = myarray[1][2];
Belay Kal
//Application of two dimensional Array
class MulTable{
final static int ROWS=12;
final static int COLUMNS=12;
public static void main(String [ ]args) {
int pro [ ] [ ]= new int [ROWS][COLUMNS];
int i=0,j=0;
[Link]("MULTIPLICATION TABLE");
[Link](" ");
for (i=1; i<ROWS; i++)
{
for (j=1; j<COLUMNS; j++)
{
pro [i][j]= i * j;
[Link](" "+ pro [i][j]);
}
[Link](" " );
}
138 } Belay Kal
Variable Size Arrays
Java treats multidimensional array as “array of arrays”.
It is possible to declare a two dimensional array as
follows:
int x[][]= new int[3][];
x[0] = new int[2];
x[1] = new int[4];
x[2] = new int[3];
This statement creates a two dimensional xarray
[0][1] having
X[0]
different length
X[1]
for each row as shown below:
X[2] x[1][3]
x[2][2]
139 Belay Kal
Strings in Java

140 Belay Kal


Introduction
Strings represent a sequence of characters.
The easiest way to represent a sequence of characters in
Java is by using a character:
char ch[ ]= new char[4];
ch[0] = ‘D’;
ch[1] = ‘a’;
ch[2] = ‘t;
ch[3] = ‘a;
This is equivalent to String ch=“Hello”;
Character arrays have the advantage of being able to
query their length.
But they are not good enough to support the range of
141 Belay Kal
operations we may like to perform on strings.
Contd.
In Java, strings are class objects and are implemented
using two classes:
 String class

 StringBuffer

Once a String object is created it cannot be changed.


Strings are Immutable.
To get changeable strings use the StringBuffer class.
A Java string is an instantiated object of the String class.
Java strings are more reliable and predictable than C++
strings.
A java string is not a character array and is not NULL
142 Belay Kal
Contd.
In Java, strings are declared and created as follows:
String stringName;
stringName= new String(“String”);
Example:
String firstName;
firstName = new String(“Jhon”);
The above two statements can be combined as follows:
String firstName= new String(“Jhon”);
The length() method returns the length of a string.
Example: [Link]();
143 Belay Kal //returns 4
String Arrays
It is possible to create and use arrays that contain strings
as follows:
String arrayname[] = new String[size];
Example:
String item[]= new String[3];
item[0]= “Orange”;
item[1]= “Banana”;
item[2]= “Apple”;
It is also possible to assign a string array object to
another string array object.
144 Belay Kal
String Methods
1. The length(); method returns the length of the string.
Eg: [Link](“Hello”.length()); // prints 5
 The + operator is used to concatenate two or more
strings.
Eg: String myname = “Harry”
String str = “My name is” + myname+ “.”;
2. The charAt(); method returns the character at the
specified index.
Syntax : public char charAt(int index)
Ex: char ch;
145 Belay Kal
ch = “abc”.charAt(1); // ch = “b”
Contd.
3. The equals(); method returns ‘true’ if two strings are
equal.
Syntax : public boolean equals(Object anObject)
Ex: String str1=“Hello”,str2=“hello”;
([Link](str2))? [Link](“Equal”); : [Link](“Not
Equal”); // prints Not Equal
4. The equalsIgnoreCase(); method returns ‘true’ if two
strings are equal, ignoring case consideration.
Syntax : public boolean equalsIgnoreCase(String str)
Ex: String str1=“Hello”,str2=“hello”;
if ([Link](str2))
146 Belay Kal
[Link](“Equal”);
Contd.
5. The toLowerCase(); method converts all of the characters
in a String to lower case.
Syntax : public String toLowerCase( );
Ex: String str1=“HELLO THERE”;
[Link]([Link]()); // prints hello there
6. The toUpperCase(); method converts all of the characters
in a String to upper case.
Syntax : : public String toUpperCase( );
Ex: [Link](“wel come”.toUpperCase()); // prints WEL-
COME
7. The trim(); method removes white spaces at the
beginning and end of a string.
147 Syntax : publicBelay
String
Kal trim( );
Contd.
8. The replace(); method replaces all appearances of a
given character with another character.
Syntax : public String replace( ‘ch1’, ’ch2’);
Ex: String str1=“Hello”;
[Link]([Link](‘l’, ‘m’)); // prints Hemmo
9. comparetTo(); method Compares two strings
lexicographically.
The result is a negative integer if the first String is less than the
second string.
It returns a positive integer if the first String is greater than the
second string. Otherwise the result is zero.
Syntax : public int compareTo(String anotherString);
public int compareToIgnoreCase(String str);
148 Belay Kal
Contd.
10. The concat(); method concatenates the specified string
to the end of this string.
Syntax : public String concat(String str)
Ex: [Link]("to".concat("get").concat("her“)); // returns
together
11. comparetTo(); method Compares two strings
lexicographically.
The result is a negative integer if the first String is less than the
second string.
It returns a positive integer if the first String is greater than the
second string. Otherwise the result is zero.
Syntax : public int compareTo(String anotherString);
public int compareToIgnoreCase(String str);
149 Belay Kal
Ex: (“hello”.compareTo(“Hello”)==0) ? [Link](“Equla”
Contd.
[Link] substring(); method creates a substring starting from
the specified index (nth character) until the end of the
string or until the specified end index.
Syntax : public String substring(int beginIndex);
public String substring(int beginIndex, int endIndex);
Ex: "smiles".substring(2); //returns "ile“
"smiles".substring(1, 5); //returns "mile“
13. The startsWith(); Tests if this string starts with the specified
prefix.
Syntax: public boolean startsWith(String prefix);
Ex: “Figure”.startsWith(“Fig”); // returns true
14. The indexOf(); method returns the position of the first
occurrence of a character
150 Belay Kal in a string either starting from the
Contd.
 public int indexOf(int ch); Returns the index of the first
occurrence of the character within this string starting
from the first position.
 public int indexOf(String str); - Returns the index of the
first occurrence of the specified substring within this
string.
 public int indexOf(char ch, int n); - Returns the index of
the first occurrence of the character within this string
starting from the nth position.
Ex: String str = “How was your day today?”;
[Link](‘t’); // prints 17
[Link](‘y’, 17); // prints 21
[Link](“was”);
151
// Prints
Belay Kal
4
[Link]("day",10)); //Prints 13
Contd.
15. The lastIndexOf(); method Searches for the last occurrence of
a character or substring.
 The methods are similar to indexOf() method.

16. valueOf(); creates a string object if the parameter or converts


the parameter value to string representation if the parameter is a
variable.
Syntax: public String valueOf(variable);
public String valueOf(variable);
Ex: char x[]={'H','e', 'l', 'l','o'};
[Link]([Link](x));//prints Hello
[Link]([Link](48 958)); // prints 48 958
17. endsWith(); Tests if this string ends with the specified suffix.
Syntax: public boolean
152 Belay Kal endsWith(String suffix);
Exercise
1. Consider a two by three integer two dimensional array named
array3.
a) Write a statement that declares and creates array3.
b) Write a single statement that sets the elements of array3 in
row 1 and column 2 as zero.
c) Write a series of statements that initializes each element of
array3 to 1.
d) Write a nested for statement that initializes each element of
array3 to two.
e) Write a nested for statement that inputs the values for the
elements of array3 from the user.
f) Write a series of statements that determines and prints the
153 smallest value in array3.
Belay Kal
Contd.
2. Write a Java application program which adds all the numbers ,
except those numbers which are multiples of three, between
1 and 100. (Hint: use continue statement)
3. Write a program which reads the values for two matrices
and displays their product.
4. Write a program, which will read a string and rewrite it in
alphabetical order.
5. Write a java application program which reads a paragraph
and displays the number of words within the paragraph.
154

You might also like