0% found this document useful (0 votes)
47 views86 pages

Chapter 1 - Part II

Uploaded by

alsenlegesse
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)
47 views86 pages

Chapter 1 - Part II

Uploaded by

alsenlegesse
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
You are on page 1/ 86

Object Oriented Programming

Chapter - 1
Introduction to Object Oriented Programming
and Java
Compiled By Yohans Samuel(MSc)
1
Contents

PART - II : INTRODUCTION TO JAVA PROGRAMMING

1. Introduction
2. Basic Elements of Programming
3. Control Statements
4. Arrays
5. Strings

2
Introduction (1)
• Java is popular high-level, class-based object oriented programming
language originally developed by Sun Microsystems and released in
1995.
• Currently Java is owned by Oracle and more than 3 billion devices run
Java. Java runs on a variety of platforms, such as Windows, Mac OS,
and the various versions of UNIX.
• Java is used to develop numerious types of software applications like
Mobile apps, Web apps, Desktop apps, Games and much more.
• Java is a general-purpose programming language intended to let
programmers Write Once, Run Anywhere (WORA).
• This means that compiled Java code can run on all platforms that
support Java without the need to recompile.

3
Introduction (2)
• Java is an object oriented programming language by which
we can develop computer program.
• It was designed to have the "look and feel" of the C++
language, but it is simpler to use than C++ and enforces an
object-oriented programming model.
• Java can be used to create complete applications that may
run on a single computer or be distributed among servers
and clients in a network.
• Java is a Platform independent: We can run java program
on any of OS (Windows, Unix or MAC) if the appropriate
JVM is installed on the machine.

4
Introduction (3)
There are three major steps to writing and executing a
java program
1. Writing java code using any text editor [Notepad,
Eclipse, NetBeans,IntelliJ IDEA, VS Code]
– save it with an extension(.java)
2. Compile the written program using java compiler
– the output of java compiler is called Byte Code (.class)
3. Convert the byte code into machine language.
– JVM (Java virtual machine) helps us to make the conversion.

5
Introduction (4)
• The first step, we need to have a java source code and need to save it
with the .java extension.
• Secondly, we need to use a compiler so that it compiles the source code
which in turn gives out the java bytecode and that needs to have
a .class extension.
• The Java bytecode is a redesigned version of the java source codes, and
this bytecode can be run anywhere irrespective of the machine on
which it has been built.
• Later on, we put the java bytecode through the JVM which is an
interpreter that reads all the statements thoroughly step by step from
the java bytecode which will further convert it to the machine-level
language so that the machine can execute the code.
• We get the output only after the conversion is through.

6
Introduction (5)

7
Features of Java (1)
• Simple: Learning and practicing Java is easy because of resemblance
with C and C++.
• Object Oriented: Unlike C++, Java is “purely” OOP.
• Distributed: Java is designed for use on network; it has an extensive
library which works in agreement with TCP/IP.
• Secure: Java is designed for use on Internet. Java enables the
construction of virus-free, tamper free systems.
• Robust (Strong/ Powerful): Java programs will not crash because of its
exception handling and its memory management features.
• Portable: Java does not have implementation dependent aspects and it
yields or gives same result on any machine.

8
Features of Java (2)
• Interpreted: Java programs are compiled to generate the byte
code(.class file). This byte code can be interpreted by the interpreter
contained in JVM.
• Architectural Neutral Language: Java byte code is not machine
dependent, it can run on any machine with any processor and with any
OS.
• High Performance: Along with interpreter there will be JIT (Just In
Time) compiler which enhances the speed of execution.
• Multithreaded: Executing different parts of program simultaneously is
called multithreading. This is an essential feature to design server side
programs.
• Dynamic: We can develop programs in Java which dynamically change
on Internet (e.g.: Applets).

9
Java Environment (1)
• 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)
10
Java Environment (2)
• Java is a general-purpose programming language that is
concurrent, class-based, object-oriented, etc.
• Java applications are typically compiled to bytecode that can run
on any Java virtual machine (JVM) regardless of computer
architecture.
• The latest version is Java 21.
• JVM, JRE, and JDK three are all platform-dependent because the
configuration of each Operating System is different.
• But, Java is platform-independent.

11
Java Environment (3)
• JDK(Java Development Kit): JDK is intended for software
developers and includes development tools such as the Java
compiler, Javadoc, Jar, and a debugger.
• JRE(Java Runtime Environment): JRE contains the parts of
the Java libraries required to run Java programs and is
intended for end-users.
– JRE can be viewed as a subset of JDK.
• JVM(Java Virtual Machine) is an abstract machine. It is a
specification that provides a runtime environment in which
java bytecode can be executed.
– JVMs are available for many hardware and software platforms.

12
Reading Assignment
• How JVM works
• differences between JDK vs JRE vs JVM

13
Java Packages (1)
• Java 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.

14
Java Program Structure (1)
• In Java:
– A program is made up of one or more classes
– A class contains one or more methods
– A method contains program statements
• First we need to import the required packages. By default,
java.lang.* is imported. Java has several such packages in its library.
• A package is a kind of directory that contains a group of related
classes and interfaces. A class or interface contains methods.
• Since Java is purely an Object Oriented Programming language, we
cannot write a Java program without having at least one class or
object.
• So, it is mandatory to write a class in Java program. We should use
class keyword for this purpose and then write class name.
15
Java Program Structure (2)
// comments about the class
class header
public class MyProgram
{

// comments about the method


public static void main (String[] args)
class body
{
method header
method body
}

Comments can be placed almost anywhere

16
Basic Elements of Programming in Java (1)
The following elements are basic terms in every
programming language.
– Syntax
– Data types
– Keywords
– Identifiers
– Variables
– Comments
– Operators

17
Basic Elements (2)
SYNTAX
• Syntax is a rule that we should follow to write a computer
program, it depends on the programming language.
KEYWORDS
• Reserved words or keywords are words that have a specific
meaning to the compiler and cannot be used for other purposes in
the program.
• We cannot use keywords as an identifier.
• Java has many keywords, among them:
– All data types;
– Words for conditional statement (if , else);
– Words for looping statement (while, do, for) etc.

18
Basic Elements (3)
IDENTIFIERS
• Identifiers are a name given for items such as
variables,functions, arrays etc. while coding.
Rules for naming identifiers
• Starts with small letters or capital letters or underscore.
• It cannot start with digits or special characters.
• Keywords cannot be an identifier.
• Space between an identifier is not allowed.

19
Basic Elements (4)
VARIABLES
• Variables are name of memory space that we represent while
coding.
• In order to use variables we should declare them before.
• The variable declaration tells the compiler to allocate appropriate
memory space for the variable based on its data type.
• Example: int count;
double radius;
• Every variable has a scope. The scope of a variable is the part of
the program where the variable can be referenced.

20
Basic Elements (5)

21
Basic Elements (6)
NAMED CONSTANT
• A named constant is an identifier that represents a permanent value.
• The value of a variable may change during the execution of a program,
but a named constant, or simply constant, represents permanent data
that never changes.
• The word final is a Java keyword for declaring a constant.
• Example: final double PI = 3.14159;
LITERALS
• A literal is a constant value that appears directly in a program.
• For example, 34 and 0.305 are literals in the following statements:
• int numberOfYears = 34;
• double weight = 0.305;
• String str = “Hello”;
22
Basic Elements (7)
COMMENT
• Comments are documents that describes what the program is and
how the program is constructed.
• Comments help programmers to communicate and understand the
program.
• Comments are not programming statements and thus are ignored
by the compiler.
• In Java, there are three types of comments:
ü Single Line comment: is used to comment texts on one line.
//this line prints the value of var1
ü Multiple Line comment: Anything enclosed by the pair /* and
*/ is considered a comment.
ü Javadoc Comment: javadoc comments begin with /** and end
23
with */.
Basic Elements (8)
DATA TYPE
• Data types are divided into two: Primitive and Non-Primitive
(Reference ) Data Type.
• Primitive data types specify the size and type of variable values.
• They are the building blocks of data manipulation and cannot be
further divided into simpler data types.
• Non-primitive data types or Reference data types refer to
instances or objects.
• They cannot store the value of a variable directly in memory.
• They store a memory address of the variable.
• Unlike primitive data types, which are defined by Java, non-
primitive data types are user-defined.

24
Basic Elements (9)

25
Basic Elements (10)
Numeric Data Types
– The following lists are the six numeric data types, their ranges,
and their storage sizes.

26
Basic Elements (11)
Character Data Type
– A character data type represents a single character.
– Example;
• char letter = 'A';
• char numChar = '4' ;
– A string literal must be enclosed in quotation marks (" ").
– A character literal is a single character enclosed in single quotation marks
(' ').
– Therefore, "A" is a string, but 'A' is a character.
Boolean Data Type
– A boolean data type declares a variable with the value either true or false.
– For example:
• boolean n = true;
• boolean a = false;
27
Basic Elements (12)
The String Type
– A string is a sequence of characters.
– The char type represents only one character.
– To represent a string of characters, use the data type called
String.
– For example: String message = "Welcome to Java";
– String is a predefined class in the Java library, just like the
classes System, JOptionPane, and Scanner.
– The String type is a reference type, not a primitive type.

28
Operators (1)

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

29
Operators (2)
Assignment Operator (=)
– The assignment operator causes the operand on the left side of
the assignment statement to have its value changed to the value
on the right side of the statement.
Example:
x=12;
x = y;
x = y+2;

30
Operators (3)
Arithmetic Operators
– The operators for numeric data types include the standard
arithmetic operators:

31
Operators (4)
Relational Operators
– Java provides six comparison operators or relational operators.
– The following table shows the equality and relational operators.

32
Operators (5)
Logical Operators
– The logical operators can be used to create a compound
Boolean expression.
– The NOT (! ) operator, which negates true to false and false to
true.
– The AND (&&) of two Boolean operands is true if and only if
both operands are true.
– The OR (||) of two Boolean operands is true if at least one of
the operands is true.
– The EXCLUSIVE OR (^) of two Boolean operands is true if
and only if the two operands have different Boolean values.

33
Operators (6)
Augmented Assignment Operators
– The arithmetic operators can be combined with the
assignment operator to form augmented operators.

34
Operators (7)
Increment and Decrement Operators
– The increment (++) and decrement (– –) operators are for
incrementing and decrementing a variable by 1.

35
Operators (8)
Example: Consider the following code:
int i = 10;
int newNum = 10 * i++;
System.out.print("i is " + i + ", newNum is
" + newNum); // The output newNum is 100

int i = 10;
int newNum = 10 * (++i);
System.out.print("i is " + i + ", newNum is
" + newNum); // The output newNum is 110

double x = 1.0;
double y = 5.0;
double z = x-- + (++y); // The output of z is 7
36
Operators (9)
Evaluating Expressions and Operator Precedence:
– Java expressions are evaluated in the same way as arithmetic
expressions.
– When more than one operator is used in an expression, the following
operator precedence rule is used to determine the order of evaluation.
• Multiplication, division, and remainder operators are applied first.
If an expression contains several multiplication, division, and
remainder operators, they are applied
from left to right.
• Addition and subtraction operators are applied last. If an
expression contains several addition and subtraction operators,
they are applied from left to right.
• read more https://introcs.cs.princeton.edu/java/11precedence/

37
Operators (10)
Example:

38
38
Operators (11)
Special Operators: Java supports some special operators of interest such
as new, instanceof operator and member selection
operator(.).
– The new operator: is used to create an object from a class.
• instanceof Operator: is used to test whether the object is an
instance of the specified type (class)..
– Example : person instanceof 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.

39
Separators (1)
• 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:
• Parenthesis ( ) :- used to enclose parameters, to define
precedence in expressions, surrounding cast types
• Braces { } :- used to contain the values of automatically initialized
arrays and to define a block of code for classes, methods and
local scopes.

40
Separators (2)
• Brackets [ ] :- are used to declare array types and for
dereferencing array values.
• Semicolon ; :- used to separate statements.
• Comma , :- used to separate consecutive identifiers in a variable
declaration, also used to chain statements together inside a “for”
statement.
• Period . :- Used to separate package names from sub-package
names and classes; also used to separate a variable or method
from a reference variable.

41
Type Conversions (1)
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.

42
Type Conversions (2)

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

43
Naming Conventions (1)
• Following the Java naming conventions makes your programs easy
to read and avoids errors.
• Listed below are the conventions for naming variables, methods, and
classes.
– Use lowercase for variables and methods. If a name consists of
several words, concatenate them into one, making the first word
lowercase and capitalizing the first letter of each subsequent word,
for example, the variables radius and area and the method
showMessageDialog.
– Capitalize the first letter of each word in a class name, for example,
the class names ComputeArea, System, and JOptionPane.
– Capitalize every letter in a constant, and use underscores between
words—for example, the constants PI and MAX_VALUE.

44
Naming Conventions (2)

45
Control Statements
• Generally, the statements inside source programs are executed
from top to bottom, in the order that they appear sequentially.
• Control flow statements, however, alter the flow of execution and
provide better control to the programmer on the flow of execution.
• There are three main categories of control statements:
– Selection statement (branching statement) : used to execute
different set of statements based on some condition. { If, If….else,
Switch }
– Looping statement (iterative statement) : used to execute
statements repeatedly. { While, Do…while, for }
– Jumping statement (transfer statement) : used to jump
operations . { Break, Continue }

46
Selection Statements (1)
Simple if Statements
• An if statement executes the statements if the condition is true
• A one-way if statement executes an action if and only if the
condition is true.
• The syntax for a one-way if statement is:

if (boolean-expression) {
statement(s);
}

47
Selection Statements (2)
if-else Statements
• An if-else statement decides which statements to execute based on
whether the condition is true or false.
• The syntax for a two-way if-else statement:
if (boolean-expression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}

48
Selection Statements (3)
if-else if (else if Ladder) Statements
• 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 for an if …. else if statement is in the next slide:

49
Selection Statements (4)
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;

50
Selection Statements (5)
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 if statement is in the next slide:

51
Selection Statements (6)
if (expression 1) {
statement(s)-1;
if (expression 1.1) {
True-block Statement 1.1
}
else {
False-block Statement 1.1
}
}
...
else if (expression n) {
statement(s)-n;
}
else
default-statement;
rest_of_program;
52
Selection Statements (7)
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 multi-way decision statement called switch
statement.
• T h e s w i tc h state m e nt ta ste s t h e va l u e o f a g i ve n
variable(expression) against a list of case values and when a
match is found, a block of statements associated with that
case is executed.

53
Selection Statements (8)
Switch statement
• Overuse of nested if statements makes a program difficult to read.
• Due to this problem, Java provides a switch statement to simplify
coding for multiple conditions.
• A switch statement executes statements based on the value of a
variable or an expression.

54
Selection Statements (9)
Syntax:
switch (switch-expression) {
case value1: statement(s)1;
break;
case value2: statement(s)2;
break;
...
case valueN: statement(s)N;
break;
default: statement(s)-for-default;
}

55
Selection Statements (10)
• The switch statement observes the following rules:
– The switch-expression must yield a value of char, byte,
short, int, or String type and must always be enclosed in
parentheses.
– The value1, . . ., and valueN must have the same data
type as the value of the switch-expression.
– Note that value 1, . . ., a nd value N a re c onsta nt
expressions, meaning that they cannot contain variables,
such as 1 + x.

56
Selection Statements (11)
• When the value in a case statement matches the value of
the switch-expression, the statements starting from this
case are executed until either a break statement or the
end of the switch statement is reached.
• The default case, which is optional, can be used to
perform actions when none of the specified cases matches
the switch-expression.
• The keyword break is optional. The break statement
immediately ends the switch statement.

57
Selection Statements (12)
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 and its value is returned.
• Example: y = (x > 0) ? 1 : -1;

58
Iterative Statements (1)
• 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 until a termination condition is met.
• 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.
• A looping process, in general, would include the four steps:
– Setting and initialization of a counter .
– Execution of the statements in the loop.
– Test for a specified condition for execution of the loop.
– Increment/Decrement the counter.

59
Iterative Statements (2)
The while Loop
– A while loop executes statements repeatedly while the condition is true.
– The syntax for the while loop is:

while (condition) {
Statement(s);
}
The do-while Loop
– A do-while loop is the same as a while loop except that it executes the loop
body first and then checks the loop condition.
– The do-while loop is a variation of the while loop.
– Its syntax is:
do {
Statement(s);
} while(condition);

60
Iterative Statements (3)
The for Loop
• A for loop has a concise syntax for writing loops.
• In general, the syntax of a for loop is:
for (initialization; condition; increment) {
Statement(s);
}
• More than one variable, separated by comma, can be initialized at a time in the
for statement.
– for(sum=0, i=1; i<=100; i++) { sum=sum+i; }
• Increment section may also have more than one part.
– for(i=0, j=0; i*j < 100; i++, j+=2) { System.out.println(i * j); }
• The test condition may have any compound relation and the testing need not be
limited only to the loop control variable.
– for(sum=0, i=1; i<20 && sum<100; ++i) { sum=sum+i; }

61
Iterative Statements (4)
for-each Loop or enhanced for loop
– Java supports a convenient for loop, known as a for-each loop, which enables
you to traverse the array sequentially without using an index variable.
– The syntax for a for-each loop is:
for (elementType element: arrayRefVar) {
// Process the element
}
– For example, the following code displays all the elements in the array myList:
– double[] myList = {1.5,5.5,3.4,0.5,7.9};

for (double u: myList) {


System.out.println(u);
}
– You can read the code as “for each element u in myList, do the following.”

62
Iterative Statements (5)
Nested Loops
– A loop can be nested inside another loop.
– Nested loops consist of an outer loop and one or more inner
loops.
for (int j = 1; j <= 9; j++)
System.out.print(" " + j);
System.out.println("\n ----------------------------------------------------------");
for (int i = 1; i <= 9; i++) {
System.out.print(i + " | ");
for (int j = 1; j <= 9; j++) {
System.out.print(i * j);
}
System.out.println();
}

63
Jump Statements (1)
• 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.
• It is used without a label, it aborts the execution of the innermost
switch, for, do, or while statement enclosing the break statement.
The continue statement
• It causes the statement block of the innermost for, do, or while
statement to terminate and the loop’s boolean expression to be
reevaluated to determine whether the next loop repetition should
take place.

64
Jump Statements (2)
• 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.

65
Array (1)
• 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!
– 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: salary[10] represents salary of the 10th employee.

66
Array (2)
• 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.

67
1D Array (3)
• 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:
– Declare an array Variable
– Create Memory Locations
– Put values into the memory locations.

68
1D Array (4)
Declaration of Arrays
• Arrays in java can be declared in two ways:
– type arrayname [ ];
– type[ ]arrayname;
• Example:
– int number[];
– float salary[];
– 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).

69
1D Array (5)
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]; 70
1D Array (6)
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.

71
1D Array (7)
• 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};
• 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;

72
2D Array (1)
• 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];

73
2D Array (2)
• 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];

74
Strings (1)
• 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.

75
Strings (2)
• In Java, strings are class objects and are implemented using
three classes:
– String class
– StringBuffer
– StringBuilder
• 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
terminated.

76
Strings (3)
• 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

77
Strings (4)
• 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.

78
Strings (5)
The StringBuilder and StringBuffer Classes
– The StringBuilder and StringBuffer classes are similar to the
String class except that the String class is immutable.
– In general, the StringBuilder and StringBuffer classes can be
used wherever a string is used.
– StringBuilder and StringBuffer are more flexible than String.
– Yo u c a n a d d , i n s e r t , o r a p p e n d n e w c o n t e n t s i n t o
StringBuilder and StringBuffer objects, whereas the value of
a String object is fixed once the string is created.

79
Strings (6)
• The StringBuilder class is similar to StringBuffer except that the methods
for modifying the buffer in StringBuffer are synchronized, which means
that only one task is allowed to execute the methods.
• Use StringBuilder if the class might be accessed by multiple tasks
concurrently.
• Using StringBuffer is more efficient if it is accessed by just a single task.
• Example: To modify strings in the StringBuilder and StringBuffer is:
String str = "Welcome";
StringBuilder sb = new StringBuilder(str);
StringBuffer sbf = new StringBuffer(str);
sb.append("To HrU");
sbf.append(“To Haramaya University");
System.out.println(sb);
System.out.println(sbf);

80
Strings (7)

81
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+ “.”;
The charAt(); method returns the character at the
specified index.
• Syntax : public char charAt(int index)
• Ex: char ch;
ch = “abc”.charAt(1); // ch = “b”

82
String Methods (2)
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
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

83
String Methods (3)
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
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 WEL-COME
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

84
String Methods (4)
The startsWith(); Tests if this string starts with the specified prefix.
• Syntax: public boolean startsWith(String prefix);
• Ex: “Figure”.startsWith(“Fig”); // returns true

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

85
Questions?

86

You might also like