0% found this document useful (0 votes)
15 views

Java 1& 2

Uploaded by

umar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Java 1& 2

Uploaded by

umar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 145

Object-Oriented Programming

(OOP) Using Java


CHAPTER ONE
FUNDAMENTAL PROGRAMMING
STRUCTURES IN JAVA

4/15/2024 BY SHIMELIS A. 1
Chapter One & Two

Overview of O O P

4/15/2024 BY SHIMELIS A. 2
Syllabus
Programming fundamentals O-O programming
✓ Variable ✓ classes
✓ Data types ✓ Objects
✓ Operators ✓ Abstraction
✓ Encapsulation
✓ Conditions
✓ Inheritance
✓ Loops
✓ Polymorphism
✓ methods
✓ Abstract classes
✓ Interfaces

4/15/2024 BY SHIMELIS A. 3
INTRODUCTION

• Program(software)
• Set instruction that tell a computer what to do
✓ We use program to interact/ talk with computers.
✓ To write program we use a programing language
✓ Computers are machines that don’t understand human languages
✓ Programs are written in the language computer can understand by
using programming language

4/15/2024 BY SHIMELIS A. 4
Machine Language …CONTD
❖ A computers native language
❖ Use zeros and ones (0/1) i.e. binary language.
❖ Machine dependent
❖ Ever instruction should be written in machine language before it can be executed.
✓ All instruction written in other programming languages must be translated to machine
code instruction
Assembly language
❖ Was developed to make instruction easier Cant be executed
❖ Introduce keywords such as add, sub, ….
❖ Example to add 2 and 3 and get the result: add 2, 3 , result
✓ A program called assembler translate assembly code to machine code.

4/15/2024 BY SHIMELIS A. 5
…CONTD
High Level Programming Language
❖ A new generation of programming language
❖ Use English like word which makes it easy to learn and use
❖ Machine independent i.e. program will run on different machines
❖ A program written in a high level language is called a source program or a
source code
❖ To add 2 and 3 and get the result : sum = 2 + 3;
❖ A compiler or an interpreter is used to translate source code to machine code
✓ What is the difference between compiler and interpreter?

4/15/2024 BY SHIMELIS A. 6
Why we learn Java?
❖ High-level, General purpose, O-O programming Language

✓ Easy and used to develop any kind of program

❖ Very popular

✓ A huge online community for getting help

❖ Can be used in android development

❖ C based language

✓ Learn C/C++/C# easier

4/15/2024 BY SHIMELIS A. 7
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.
✓ Structured programming
✓ O-O programming

I. Structured Programing
❖ involve the analysis of processes, the production of a system and tasks
carried out is based on the procedural flow of the processes.

4/15/2024 BY SHIMELIS A. 8
...CONTD
II. O O P Approach
❖ Is a paradigm that employs “Objects” and their interaction as a
primary basis for software development.
❖ An object can be anything that can be conceived and be represented in
a computer
❖ A software object resembles so much like a real world object – it will
have the following three things:
✓ identity
✓ state and
✓ behavior

4/15/2024 BY SHIMELIS A. 9
...CONTD
Identity
❖ The identity is unique and may not be shared between different objects,
even at different time and does not change during the object lifetime
State
❖ The object state represents the different possible internal conditions
that the object may experience during its lifetime
Behavior
❖ The object behavior is the way a particular object will respond to
received messages
Eg. Radio
✓ State – On, Off, current channel, current volume
✓ Behavior – Turn Off/ On, Change Channel etc

4/15/2024 BY SHIMELIS A. 10
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.

4/15/2024 BY SHIMELIS A. 11
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.

4/15/2024 BY SHIMELIS A. 12
…CONTD
Class Structure
Class class_name {
Code block
}

keyword

4/15/2024 BY SHIMELIS A. 13
…CONTD

Attributes
❖ Attributes (or variables) refer to the characteristics of the object.

❖ Appearance, state, and other qualitative traits are common object

attributes.

❖ Class attributes in combination with object instances differentiate

objects from one another.

4/15/2024 BY SHIMELIS A. 14
…CONTD
Method:
✓ A group of instruction to perform specific tasks
✓ Written inside class
✓ Example a method to add two integer.
Method Structure
✓ Each method consists of 4 main parts
return_type method_name (parameters) {
Code block;
}
Note: every method is written inside a class i.e. class is a container for
method

4/15/2024 BY SHIMELIS A. 15
…CONTD
Calling Method:
❖ Is basically using a method
method_name (give parameters);
❖ The code block of this method will be executed.
Note:
✓ The main ( ) method is automatically called when we run our java
program
✓ It is the first method that is called
✓ It is the starting point of our execution

4/15/2024 BY SHIMELIS A. 16
…CONTD
Access Modifiers
❖ The keywords that specify how to access class and method
✓ Public: Visible to the world public.
✓ Private: Visible to the class only private.
✓ Protected: Visible to the package and all subclasses.
✓ Default: Visible to the package.

4/15/2024 BY SHIMELIS A. 17
…CONTD
Naming convention
❖ How to write name in programming language
✓ Pascal case convention
MyFatherName –used to name class
✓ camel case convention
MyFatherName –used to name methods and variable
✓ snake case convention
My_father_name

4/15/2024 BY SHIMELIS A. 18
Java program structure
public Class main {
public static void main (String [] args) {
Code block
}
}

4/15/2024 BY SHIMELIS A. 19
OOP’s fundamental building blocks:

✓ Data abstraction and encapsulation


✓ Inheritance
✓ polymorphism

4/15/2024 BY SHIMELIS A. 20
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 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)
✓ They hide the private data structure details and communicate with the
outside using public methods which act as interfaces
4/15/2024 BY SHIMELIS A. 21
…CONTD
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

4/15/2024 BY SHIMELIS A. 22
…CONTD
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
✓ Overriding
• methods, and

4/15/2024 BY SHIMELIS A. 23
❖ 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 with a given procedure
call is not known until the time of the call at runtime.
✓ Memory is allocated at runtime not at compile time.

4/15/2024 BY SHIMELIS A. 24
Basics of J av a Programing
Language

4/15/2024 BY SHIMELIS A. 25
J a v a 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.

4/15/2024 BY SHIMELIS A. 26
Java Features
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.

4/15/2024 BY SHIMELIS A. 27
J a v a 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.
❖ TheJVM 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.
4/15/2024 BY SHIMELIS A. 28
Advantage of java
❖ Platform independent and Portable
✓ compile once and execute many times in many platforms”

❖ Object-oriented
✓ Java is true object-oriented programming language.
❖ Robust and Secure
❖ Distributed
❖ Simple, Small and Familiar
❖ Multithreaded and interactive
❖ Dynamic and Extensible

4/15/2024 BY SHIMELIS A. 29
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)
4/15/2024 BY SHIMELIS A. 30
Java API
❖ APIs are important software components bundled with the JDK.
❖ APIs in Java include classes, interfaces, and user Interfaces.
❖ They enable developers to integrate various applications and websites and
offer real-time information
❖ 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.
4/15/2024 BY SHIMELIS A. 31
Overview of J ava Programing
Language

4/15/2024 BY SHIMELIS A. 32
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.
4/15/2024 BY SHIMELIS A. 33
Two Ways of writing Java Programs

Compiler

4/15/2024 BY SHIMELIS A. 34
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 [])
{
System.out.print(“Java is better than C++.”);
}
}

4/15/2024 BY SHIMELIS A. 35
❖ 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.
❖ Is the starting point for the interpreter to begin the execution of the
program.

4/15/2024
36 BY SHIMELIS A.
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.
❖ Main must always be declared as static since the interpreter uses this
method before any objects are created.
❖ void : states that the main method does not return any value (but prints some
text to the screen.)

4/15/2024 BY SHIMELIS A. 37
…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
System.out.println (“Java is better than C++.”);
❖ The println method is a member of the out object, which is a static data member of
System class.

4/15/2024 BY SHIMELIS A. 38
Java Program Structure

4/15/2024 BY SHIMELIS A. 39
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 documentation automatically.

4/15/2024 BY SHIMELIS A. 40
…CONTD
Package Statements
❖ 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 java.lang.Math;

4/15/2024 BY SHIMELIS A. 41
…CONTD
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.
⦁ The number of classes depends on the complexity of the problem.

4/15/2024 BY SHIMELIS A. 42
…CONTD
M a i n Method C l a s s
❖ 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.


❖ Themain 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.

4/15/2024 BY SHIMELIS A. 43
J ava Tokens

4/15/2024 BY SHIMELIS A. 44
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.


❖ Insimplest terms, a java program is a collection of tokens, comments, and white
spaces.

❖ Java has five types of tokens: Reserved Keywords, Identifiers, Literals, Separators and
Operators .

4/15/2024 BY SHIMELIS A. 45
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.

4/15/2024 BY SHIMELIS A. 46
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.
✓ They can be of any length.
4/15/2024 BY SHIMELIS A. 47
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

4/15/2024 BY SHIMELIS A. 48
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
II. Floating-point Literals
III. Character Literals
IV. String Literals
V. Boolean Literals

4/15/2024 BY SHIMELIS A. 49
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 automatically initialized arrays and
to define a block of code for classes, methods and local scopes.

4/15/2024 BY SHIMELIS A. 50
…Contd
III. Brackets[ ]:- are used to declare array types and for
IV.dereferencing array values.
V. Semicolon;:- used to separate statements.
VI. Comma,:- used to separate consecutive identifiers in a variable
declaration, also used to chain statements together inside a “for”
statement.

VII.Period.:- Used to separate package names from sub- package names


and classes; also used to separate a variable or method from a
reference variable.

4/15/2024 BY SHIMELIS A. 51
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.

4/15/2024 BY SHIMELIS A. 52
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
✓ Special operators
4/15/2024 BY SHIMELIS A. 53
A. Arithmetic Operators
❖ Java has five basic arithmetic operators

❖ 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.
❖ Order of operations (or precedence) when evaluating an expression is the same
as you learned in school (BODMAS).

4/15/2024 BY SHIMELIS A. 54
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 program.

4/15/2024
55 BY SHIMELIS A.
…CONTD
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)

4/15/2024 BY SHIMELIS A. 56
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 trueor 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 expression.

4/15/2024 BY SHIMELIS A. 57
Examples of Logiacal Operators
boolean x = true;
boolean y = false;
boolean result;
1. Let result = (x && y);
now resultis assigned the value false
(see truth table!)

2. Let result = ((x || y) && x);


3. (x || y) evaluates to true
4. (true && x) evaluates to true
5. now result is assigned the value true

4/15/2024 BY SHIMELIS A. 58
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 expression.
❖ The 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);
y *= 7;is equivalent to y = y * 7;

4/15/2024 BY SHIMELIS A. 59
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 -- are unary operators.

4/15/2024 BY SHIMELIS A. 60
…CONTD
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 value 15 numOranges has value 6

4/15/2024 BY SHIMELIS A. 61
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 follows:
✓ exp1 is evaluated first. If it is nonzero (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
x=(a>b)? a:b; will assign the value of b to x. i.e. x=b=15;

4/15/2024 BY SHIMELIS A. 62
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.
❖ They may not be applied to float or double data types.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ One’s complement
<< Shift left
>> Shift right
>>> Shift right with zero fill

4/15/2024 BY SHIMELIS A. 63
7. Special Operators
⦁ Javasupports some special operators of interestsuch as instance of
operator and member selection operator(.).
Instance of 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 instance of student; is true if the object person belongs to the class
student; otherwise it is false
Dot Operator: is used to access the instance variables and methods of class
objects.
Example:
person.age; // Reference to the variable age.
person1.salary(); // Reference to the method salary.

4/15/2024 BY SHIMELIS A. 64
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;
✓ The expression a+b yields a floating point number 133.5 since the ‘higher’ type
here is float.

4/15/2024 BY SHIMELIS A. 65
…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)7.5; will assign 7 to x
a=(int)21.3/(int)3.5; a will be 7

4/15/2024 BY SHIMELIS A. 66
//Demonstration of Java Expressions
public class DemoExpress
{
public static void main(String[] args)
{
System.out.println("===== 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;
float answer4=(float)a/c; float answer5=a/y;

4/15/2024 BY SHIMELIS A. 67
//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);
System.out.println("Order of Evaluation");
System.out.println("a*b+c/++d + "+answer1);
System.out.println("--a*(b+++c)/d++ = " +answer2);
System.out.println("================");
System.out.println("Type Conversion");
System.out.println(" a/c = "+answer3);
System.out.println("(float)a/c = " + answer4);
System.out.println(" a/y = " + answer5);
4/15/2024 BY SHIMELIS A. 68
System.out.println("================");
System.out.println("Modulo Operations");
System.out.println(" a%c = "+answer6);
System.out.println(" x%y = "+answer7);
System.out.println("================");
System.out.println("Logical Operations");
System.out.println(" a>b && c>d = "+bool1);
System.out.println(" a<b && c>d = "+bool2);
System.out.println(" a<b || c>d = "+bool3);
System.out.println(" !(a-b==c) = "+bool4);
System.out.println("================");
System.out.println("Bitwise Operations");
4/15/2024 BY SHIMELIS A. 69
//Shift O perators
int l=8, m=-8,n=2;
System.out.println(" n & 2= "+(n&2));
System.out.println(" l | n= "+(l|n));
System.out.println(" m | n= "+(m|n));
System.out.println(" l >> 2= "+(l>>2));
System.out.println(" l >>> 1= "+(l>>>1));
System.out.println(" l << 1= "+(l<<1));
System.out.println(" m >> 2= "+(m>>2));
System.out.println(" m >>> 1= "+(m>>>1));
System.out.println("\n===== END OF THE PROGRAM =====");
}
}
4/15/2024 BY SHIMELIS A. 70
POP QUIZ

1)What is the value of number?


-12
int number = 5 * 3 – 3 / 6 – 9 * 3;
2) What is the value of result?
int x = 8;
int y = 2; false
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;
27
int numGreenCars = 10;
int numCars = numGreenCars++ + numBlueCars +
++numGreeenCars;
4/15/2024 BY SHIMELIS A. 71
Variables and Primitive Data
Types

4/15/2024 BY SHIMELIS A. 72
Variables
❖ Is an identifier that denotes a storage location used to store a data value.
❖ May have constant value or may take different values at different times during
the execution of the program.
⦁ 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.

4/15/2024 BY SHIMELIS A. 73
Data Types
❖ Every variable in Java has a data type.
❖ Data types specify the size and type of values that can be stored.
❖ Java data types are of two type:
✓ Primitive Data Types
✓ Non-Primitive data Types

4/15/2024 BY SHIMELIS A. 74
Data Types
❖ Every variable in Java has a data type.
❖ Data types specify the size and type of values that can be stored.
❖ Java data types are of two type:
✓ Primitive Data Types
✓ Non-Primitive data Types

4/15/2024 BY SHIMELIS A. 75
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'sdeclared type does not change over the course of the
program.

4/15/2024 BY SHIMELIS A. 76
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;

4/15/2024 BY SHIMELIS A. 77
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 of declaration as:
type variableName = value;
81

4/15/2024 BY SHIMELIS A. 78
Keyboard Input(By using a read statement)

❖ To assign value for variables interactively through the keyboard, we first create a
Scanner object, that is attached to the System.in data stream object
✓ E.g. Scanner input = new Scanner(System.in);
❖ 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. System.out.print("What is your name? ");
String name = in.nextLine();
✓ nextInt(), nextDouble() etc are methods to read.
❖ We must import java.util.*; package so as to use the Scanner class.

4/15/2024 BY SHIMELIS A. 79
Sample Program for I/O
import java.util.*;
public class InputTest
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("What is your name? "); String
name = in.nextLine(); // gets first input
System.out.print("How old are you? ");
int age = in.nextInt(); // gets second input
System.out.println("Hello, " + name + ". Next year, you'll be " +
(age + 1));
// display output on console
}
}
4/15/2024 BY SHIMELIS A. 80
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 }.
4/15/2024 BY SHIMELIS A. 81
Control Structures

4/15/2024 BY SHIMELIS A. 82
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)
✓ Loops (while, do… .while and for statements)

4/15/2024 BY SHIMELIS A. 83
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

4/15/2024 BY SHIMELIS A. 84
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.

❖ The if statement may be implemented in different forms depending on the


complexity of conditions to be tested.

4/15/2024 BY SHIMELIS A. 85
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 will jump
to the rest_of_program

4/15/2024 BY SHIMELIS A. 86
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.
4/15/2024 BY SHIMELIS A. 87
3. If… else if (else if Ladder) Statement
❖ Is used when multiple decisions are involved.
❖ The syntax of an if … . else if statement is:
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;
4/15/2024 BY SHIMELIS A. 88
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:

4/15/2024 BY SHIMELIS A. 89
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 is found, a block of statements associated with
that case is executed.
❖ The syntax of switch statement:

4/15/2024 BY SHIMELIS A. 90
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 is found, a block of statements associated with
that case is executed.
❖ The syntax of switch statement:

4/15/2024 BY SHIMELIS A. 91
...Contd
❖ The expression must evaluate to a char, short or int, but not long, float or double.
❖ The values value-1, value-2, … 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 zero
or more statements.
❖ 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 (:).
❖ The break statement at the end of each block signals the end of a particular
case and causes an exit from the switch statement.
4/15/2024 BY SHIMELIS A. 92
class Main {
public static void main(String[] args) {
int number = 44;
String size;
// switch statement to check size
switch (number) {
case 42:
size = "Medium";
break;
// match the value of week
case 44:
size = "Large";
break;
default:
size = "Unknown";
break;
}
System.out.println("Size: " + size);
}
}
4/15/2024 BY SHIMELIS A. 93
Exercise
1. Find out Errors in the following program and discuss ways for correction.
a) //Errors.java
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;
System.out.println("x % y = "+x % y); boolean b = 1 ;
if (b) System.out.println(“b is true”);
else System.out.println(“b is false”);
}
}

4/15/2024 BY SHIMELIS A. 94
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 using compound relations:
a) if(grade<=59 && grade>=50) second+=1;
b) if(num>100 || num<0) System.out.prinln(“Out of 6. Write a Java application program that
Range”); else reads the coefficients of a quadratic equation
(ax2+bx+c=0), generates and display the roots.
sum+=num;
Note:
c) If((M>60 && N>60)||T>200) An appropriate message should be generated when
y=1; the user types an invalid input to the equation.
Else
y=0;
4/15/2024 BY SHIMELIS A. 95
Looping

4/15/2024 BY SHIMELIS A. 96
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 some conditions from the
termination of the loop are satisfied.

4/15/2024 BY SHIMELIS A. 97
…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.

4/15/2024 BY SHIMELIS A. 98
…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:

4/15/2024 BY SHIMELIS A. 99
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.

4/15/2024 BY SHIMELIS A. 100


...CONTD
❖ The basic format of the while statement is:
Example:
initialization; int sum=0,n=1;
while (expression) while(n<=100)
{ {
Body of the loop; sum+=n; n++;
} }
System.out.println(“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.
4/15/2024 BY SHIMELIS A. 101
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.
4/15/2024 BY SHIMELIS A. 102
...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);
System.out.println(“Sum=“+sum;

4/15/2024 BY SHIMELIS A. 103


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; update)
{
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.
4/15/2024 BY SHIMELIS A. 104
...CONTD
Example
int sum=0;
for(n=1; n<=100; n++)
{
sum=sum+n;
}
System.out.println(“Sum is:”+sum);

4/15/2024 BY SHIMELIS A. 105


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)
{
System.out.println(i * j);
}

4/15/2024 BY SHIMELIS A. 106


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;
}

4/15/2024 BY SHIMELIS A. 107


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)
{
if(i == 5){
Inner O uter
break; Loop Loop
}
System.out.println(i); i--;
}
System.out.println(i*2);
}

4/15/2024 BY SHIMELIS A. 108


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.

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.
✓ A label is an identifier that uniquely identifies a block of code.

4/15/2024 109 BY SHIMELIS A. 109


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.

4/15/2024 110 BY SHIMELIS A. 110


…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 value of sum?
ANS:- 1 + 2 + 4 + 5 + 7 + 8 + 10 = 37
4/15/2024 BY SHIMELIS A. 111
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.

4/15/2024 112 BY SHIMELIS A. 112


//Use of Continue and break Statements class
ContinueBreak
{
public static void main(String [ ]args)
*
{
Loop1: for(int i=1; i<100; i++)
** Output
{ ***
System.out.println(" "); if (i>=8) ****
break;
*****
for (int j=1; j<100; j++)
******
{
System.out.print("*"); *******
if (j==i) continue Loop1; Termination by BREAK
}
}
System.out.print("Termination by BREAK");
}
}
4/15/2024 BY SHIMELIS A. 113
Exercise
1. W hat 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){
System.out.print(row % 2 == 1 ? “<” :“>”);
++column;
}
--row;
System.out.println();
}
}
}

4/15/2024 BY SHIMELIS A. 114


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 number from the n digit]
4. Using a two-dimensional array, write codes that print the following outputs.

a) c) 5
$ $ $ $ $ 454
$ $ $ $ 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

4/15/2024 BY SHIMELIS A. 115


Arrays, Strings and Vectors

4/15/2024 116 BY SHIMELIS A. 116


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.
❖ 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:
slaray[10] represents salary of the 10th employee.

4/15/2024 117 BY SHIMELIS A. 117


...CONTD
❖ The length of an array is established when the array is created.
❖ After creation, its length is fixed.
❖ Each item in anarray 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.

4/15/2024 BY SHIMELIS A. 118


One-DimensionalArrays
❖ 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.

4/15/2024 BY SHIMELIS A. 119


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 and null for references (any non primitive types).

4/15/2024 BY SHIMELIS A. 120


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];
Example:
int num[ ] = new int[10];

4/15/2024 BY SHIMELIS A. 121


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;
Note:
✓ Unlike C, java protects arrays from overruns and underruns.
✓ Trying to access an array beyond its boundaries will generate an error.

4/15/2024 BY SHIMELIS A. 122


...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:
int number[]= {35,40,23,67,49};

4/15/2024 BY SHIMELIS A. 123


...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 Le n gth
❖ In Java, all arrays store the allocated size in a variable named length.
❖ We can access the length ofthe array array1 using array1.length.
Example:
int size = array1.length;

4/15/2024 BY SHIMELIS A. 124


//sorting of a list of N umbers if (num[i] < num [j])
class Sorting {
{ //InterchangeValues
public static void main(String [ ]args) int temp = num[i];
{ num [i] = num [j];
int num[ ]= {55, 40, 80, 12, 65, 77}; num [j] = temp;
int size = num.length; }
System.out.print(“Given List:“); for (int i=0; }
i<size;i++) }
{ System.out.print("SORTED LIST" );
System.out.print(" " + num[ i ] ); for (int i=0; i<size;i++)
} {
System.out.print("\n"); System.out.print(" " " + num [i]);
//Sorting Begins }
for (int i=0;i<size;i++) System.out.println(" ");
{ }
for (int j=i+1;j<size;j++) }
{
4/15/2024 BY SHIMELIS A. 125
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:
int myarray[][]= int [3][4];

4/15/2024 BY SHIMELIS A. 126


...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,
int value = myarray[1][2];

4/15/2024 BY SHIMELIS A. 127


//Application of two-dimensionalArray
class MulTable{
final static int RO W S=12;
final static int C O LUMNS=12;
public static void main(String [ ]args) {
int pro [ ] [ ]= new int [RO W S][C O LUMNS]; int i=0,j=0;
System.out.print("MULTIPLIC ATIO N TABLE");
System.out.println(" ");
for (i=1;i<RO W S; i++)
{
for (j=1;j<COLUMNS; j++)
{
pro [i][j]= i * j; System.out.print(" "+ pro
[i][j]);
}
System.out.println(" " );
}
}
}

4/15/2024 BY SHIMELIS A. 128


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 array having different
length for each row as shown below:
x[0][1]
X[0]

X[1]

X[2] x[1][3]

x[2][2]
4/15/2024 BY SHIMELIS A. 129
Strings in Java

4/15/2024 BY SHIMELIS A. 130


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 operations
❖ we may like to perform on strings.
4/15/2024 BY SHIMELIS A. 131
...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 N ULL terminated.

4/15/2024 BY SHIMELIS A. 132


...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:
firstName.length(); //returns 4

BY SHIMELIS A. 133
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”;

4/15/2024 BY SHIMELIS A. 134


String Methods
1. The length(); method returns the length of the string. Eg:
System.out.println(“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)
Example:
char ch;
ch = “abc”.charAt(1);//ch = “b”

4/15/2024 BY SHIMELIS A. 135


...CONTD
3. The equals(); method returns ‘true’ if two strings are equal.
Syntax : public boolean equals(Object anObject)
Ex: String str1=“Hello”,str2=“hello”;
(str1.equals(str2))? System.out.println(“Equal”); : System.out.println(“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 (str1.equalsIgnoreCase(str2)) System.out.println(“Equal”);
System.out.println(“Not Equal”); // prints Equal as an output

4/15/2024 136 BY SHIMELIS A. 136


...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”;
System.out.println(str1.toLowerCase()); // prints hello there
6. The toUpperCase(); method converts all of the characters in a
String to upper case.
Syntax : : public String toUpperCase( );
Ex: System.out.println(“wel-come”.toUpperCase()); //prints W E L - C O M E
7. The trim(); method removes white spaces at the beginning and end of a string.
Syntax : public String trim( );
Ex: System.out.println(“ wel-come ”.trim()); //prints wel-come

4/15/2024 BY SHIMELIS A. 137


...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”;
System.out.println(str1.replace(‘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.
✓ positive integer if the first String is greater than the second string.
✓ Otherwise the result is zero.
Syntax : public int compareTo(String anotherString);
Ex: (“hello”.compareTo(“Hello”)==0) ? System.out.println(“Equla”); :
System.out.println(“Not Equal”); //prints N o t Equal

4/15/2024 BY SHIMELIS A. 138


...CONTD
10. The concat(); method concatenates the specified string to the end of this string.
Syntax : public String concat(String str)
Ex: System.out.println("to".concat("get").concat("her“)); //returns together
11. The 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 "iles“
"smiles".substring(1, 5); //returns "mile“

4/15/2024 139 BY SHIMELIS A. 139


...CO NTD
12.The startsWith(); Tests if this string starts with the specified prefix.
Syntax: public boolean startsWith(String prefix);
Ex: “Figure”.startsWith(“Fig”); // returns true
13.The indexOf(); method returns the position of the first occurrence of a
character in a string either starting from the beginning of the string or starting
from a specific position.

4/15/2024 140 BY SHIMELIS A. 140


...CO NTD
❖ 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?”;
str.indexOf(‘t’); // prints 17
str.indexOf(‘y’, 17); // prints 21
str.indexOf(“was”); // Prints 4
str.indexOf("day",10)); //Prints 13

4/15/2024 BY SHIMELIS A. 141


...CO NTD
14. The lastIndexOf(); method Searches for the last occurrence of a
character or substring.
✓The methods are similar to indexOf() method.
15. 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);
Ex: char x[]={'H','e', 'l', 'l','o'};
System.out.println(String.valueOf(x));//prints Hello
System.out.println(String.valueOf(48.958)); // prints 48.958
17. endsWith(); Tests if this string ends with the specified suffix.
Syntax: public boolean endsWith(String suffix);
Ex: “Figure”.endsWith(“re”); //true
4/15/2024 BY SHIMELIS A. 142
Assignment (5%)
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 smallest value in array3.

g) Write a statement that displays the elements of the first row of array3.

h) Write a statement that totals the elements of the third column array3.

4/15/2024 BY SHIMELIS A. 143


...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.

NOTICE:
✓ submission date is 26-04-2024
✓ Being late will nullify your result

4/15/2024 BY SHIMELIS A. 144


THE END
THANK YOU

You might also like