Chapter 01 Introduction
Chapter 01 Introduction
Chapter 01
Introduction
1
Objectives
After studying this chapter, students should be able to:
◼ Learn about Programming Paradigms
▪ Structured Vs Object-Oriented paradigm
2
Programming Paradigms
◼ 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
◼ Problem solving would involve the analysis of processes in
terms of the procedural tasks carried out and the production of a
system whose representation is based on the procedural flow of
the processes.
◼ Data was separate from code.
◼ Programmer is responsible for organizing everything in to
logical units of code/data
◼ A procedural program is divided into functions, and (ideally, at
least) each function has a clearly defined purpose & a clearly
defined interface to the other functions in the program.
3
Contd…
Disadvantages of Structured Programming
1. Unrestricted Access
2. Real-World Modeling
◼ Unrelated functions and data, the basics of the procedural paradigm,
provide a poor model of the real world.
4
Contd…
OOP Approach
◼ A modern programming paradigm that allows the Programmer
to model a problem in a real-world fashion as an object.
◼ Major objective is to eliminate some of the flaws encountered in
the procedural approach.
◼ OOP allows us to decompose a problem into number of entities
called objects and then build data and methods (functions)
around these entities.
◼ The data of an object can be accessed only by the methods
associated with the object
◼ Follows bottom-up approach in program design
5
Contd…
Features of OOP
◼ Emphasis is on data rather than procedure.
6
Basic OOP Concepts
The following are the basic OOP concepts:
1. Objects
2. Classes
3. Data Abstraction
4. Data Encapsulation
5. Inheritance
6. Polymorphism
7. Dynamic Binding
8. Message Passing
7
Contd…
1. Object
◼ An object is any real-world entity which may represent place, person,
data item related to program.
◼ An object has state, behavior and identity.
◼ Ex. A ‘Mouse’ object has,
State: moving or working
Behavior: picking or pointing an object on the screen
Identity: color, company, Identification No. etc.
◼ An object is a variable/instance of class.
◼ An object is a run-time entity.
1. Class
◼ Is the template or blueprint that defines the states and the behaviors
common to all objects of a certain kind.
◼ It is a collection of objects of similar type.
◼ Classes are user-defined data types & behave like the built-in types of
programming language.
8
Contd…
3. Data Abstraction
◼ Abstraction means representing essential features without
including the background details or explanations
◼ A classes can use the concept of Abstraction and are defined as
list of abstract data and functions to operate on these data.
◼ Since the classes use the concept of Data Abstraction, they are
known as Abstract Data Type(ADT).
4. Data 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.
9
Contd…
5. Inheritance
◼ Is the process by which objects of one class acquire the
properties of objects of another class.
◼ It provides the idea of reusability( reusing the code)
6. Polymorphism
◼ In polymorphism, ‘Poly’ means many and ‘morph’ means forms,
i.e. many forms.
◼ Is the ability to take more than one form. It allows a function
responding in different ways.
7. Dynamic Binding
◼ It 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.
10
Contd…
8. Message Passing
◼ The process of invoking an operation of an object is called
Massage Passing.
◼ In response to the given massage, the respective method or
operation is called.
◼ OOPs includes objects which communicates by sending/
receiving information with each other.
◼ Message Passing involves specifying the name of the object,
the name of the function (message) and the information to be
sent.
employee.salary (name);
◼ A message for an object is a request for the execution of a
procedure.
11
Overview of Java Programming
What is Java?
◼ Java technology consists of a programming language and a
platform on which programmes can run.
◼ The Java language is object-oriented and programs written in
Java are portable – that is, they can be run on many different
platforms (e.g. Windows, Mac, Linux, Solaris).
◼ Java is different from other programming languages because a
Java program is compiled and interpreted – in many other
languages, the program is either compiled or interpreted.
12
Contd..
◼ The Java compiler translates the program into an
intermediate language called Java bytecodes.
◼ Java bytecodes are platform-independent – this means
they can be run on different operating systems (e.g.
Windows and Mac).
13
Contd..
14
Contd..
◼ Compilation only needs to happen one time, whereas
interpretation happens every time the program is executed.
◼ A .java file can be opened and viewed in any text editor, but a
.class file is bytecode so it cannot be viewed in the same way.
15
Contd..
◼ Every Java interpreter is actually an implementation of
something called the Java VM (Virtual Machine).
16
Contd..
17
Contd..
◼ As mentioned above, Java includes a programming language and a
platform.
◼ A platform refers to the hardware (PCs, servers, printers etc) and
software (operating systems, application software etc) in which a
program is run.
19
Introduction to Java
◼ Java is an Object-Oriented Programming language developed
by Sun Microsystems in the year 1991.
◼ Initially it was named as “Oak” by James Gosling
◼ In 1995, “Oak” is renamed to “Java” because the name “Oak”
did not survive legal registration.
◼ James Gosling and his team members were consuming a lot of
coffee while developing this language.
◼ Good quality of coffee was supplied from a place called “Java
Island’. Hence they fixed the name of the language as Java. The
symbol for Java language is cup and saucer.
◼ Sun formally announced Java at Sun World conference in 1995.
On January 23rd 1996, JDK1.0 version was released.
20
Features of Java (Java Buzzwords)
◼ 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 gives same result on any machine.
21
Contd…
◼ 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 a 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).
22
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)
23
Java API
◼ It includes hundreds of classes and methods grouped into
several functional packages.
◼ Most commonly used packages are:
◼ Language Support Package: a collection of classes and methods required
for implementing basic features of java.
◼ Utilities Package: a collection of classes to provide utility functions such
as date and time functions.
◼ Input/output Package: a collection of classes required for input/output
manipulation.
◼ Networking Package: a collection of classes for communicating with
other computers via Internet.
◼ AWT Package (Abstract Window Tool kit package): contains classes that
implements platform-independent graphical user interface.
◼ Applet Package: includes set of classes that allows us to create java
applets.
24
Control Statements
▪ Generally, the statements inside source programs are executed
from top to bottom, in the order that they appear.
◼ Control flow statements, however, alter the flow of execution
and provide better control to the programmer on the flow of
execution.
◼ In Java control statements are categorized into 3 groups:
1. Selection or Decision Making Statements : allow the program to choose
different parts of the execution based on the outcome of an expression
2. Iteration Statements enable program execution to repeat one or more
statements
3. Jump Statements enable your program to execute in a non-linear fashion
2
Selection Statements
◼ These statements allow us to control the flow of program execution
based on condition.
▪ Java supports 2 selection statements:
▪ if statements
▪ switch statements
If statement:
◼ It performs a task depending on whether a condition is true or false.
Test False
expression
?
True
3
1. Simple if Statement
▪ An if statement consists of a Boolean expression followed by
one or more statements.
2
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. Nested if … else Statement
▪ if…else statements can be put inside other if…else
statements. such statements are called nested if … else
statements.
▪ Is used whenever we need to make decisions after checking
a given decision.
▪ The syntax of a nested if…else statement is shown in the
next slide.
▪ True-block statement 1.1 is executed if both expression 1
and expression 1.1 are true. But if expression 1 is true and
if expression 1.1 is false, then it is False-block statement
1.1 which is going to be executed.
8
if (expression 1)
{
statement(s)-1;
if (expression 1.1)
{
True-block Statement 1.1
} Nested if statement
else
{
False-block Statement
1.1
}
}
else if (expression 2)
{
statement(s)-2;
}
...
else if (expression n)
{
statement(s)-n;
}
else
default-statement;
rest_of_program;
Switch statement
▪ We can design a program with multiple alternatives using if
statements to control the selection.
3
Switch syntax
switch (expression)
{
case value-1:
statement-block 1;
break;
case value-2:
statement-block 2;
break;
......
......
default:
default_statement;
break;
}
rest_of_program
3
Contd…
▪ The expression must evaluate to a char, short or int, but not long,
float or double.
3
Contd…
▪ There is no need to put braces around the statement blocks of a switch
statement but it is important to note that case labels end with a colon
(:).
▪ The break statement at the end of each block signals the end of a
particular case and causes an exit from the switch statement.
3
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.
3
Contd…
▪ For example:
if (x<=40)
if(x<40)
slary=4*x+100; Can be written as:
salary=(x!=40)? (x<40)?
else
(4*x+100):(4.5*x+100)):300;
salary=300;
else
slary=4.5*x+100;
▪ When the conditional operator is used, the code becomes more
concise and perhaps, more efficient. However, the reliability is
poor.
▪ It is better to use if statement when more than a single nesting of
conditional operator is required.
3
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”);
}
}
3
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; 6. Write a Java application program
b) if(num>100 || num<0) that reads the coefficients of a
System.out.prinln(“Out of Range”); quadratic equation
else (ax2+bx+c=0), generates and
sum+=num; display the roots.
Note:
c) If((M>60 && N>60)||T>200)
An appropriate message should be
y=1;
generated when the user types an
else invalid input to the equation.
y=0;
Iterative/Loop Statements
▪ 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 program loop consists of two statements:
▪ Body of the loop.
▪ Control statements.
▪ A looping process, in general, would include the 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. 18
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
19
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.
▪ The basic format of the while statement is:
Example:
initialization; int sum=0,n=1;
while (expression) while(n<=100)
{
{
sum+=n;
Body of the loop;
n++;
}
}
System.out.println(“Sum=“+sum;) 20
Contd…
▪ 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.
▪ 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
Contd…
▪ The execution of the for loop statement is as follows:
1. Initialization of the control variable(s) is done first, using assignment
statement.
2. The value of the control variable is tested using the test condition. The
test condition is a relation operation that determines when the loop will
exit.
▪ If the condition is true, the body of the loop is executed;
otherwise the loop is terminated and the execution continues with
the statement that immediately follows the loop.
3. When the body of the loop is executed, the control is transferred back to
the for statement after evaluating the last statement in the loop.
▪ Now the new value of the control variable is again tested to see
whether it satisfies the loop condition; if it does, the body of the
loop is again executed.
4
Contd…
int sum=0;
Example
for(n=1; n<=100; n++)
{
sum=sum+n;
}
System.out.println(“Sum is:”+sum);
4
Contd…
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);
}
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
Contd…
D. You do not have to fill all three control sections, one or more
sections can be omitted but you must still have two
semicolons.
Example:
int n = 0;
for(; n != 100;) {
System.out.println(++n);
}
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){
break;
}
System.out.println(i); Inner Outer
i--; Loop Loop
}
System.out.println(i*2);
}
5
Jumps in Loops
▪ Jump statements are used to unconditionally transfer the program
control to another part of the program.
▪ Java has three jump statements: break, continue, and return.
1. The break statement
◼ A break statement is used to abort the execution of a loop. The
general form of the break statement is given below:
break label;
◼ It may be used with or without a label.
◼ When it is used without a label, it aborts the execution of the
innermost switch, for, do, or while statement enclosing the break
statement. When used with a label, the break statement aborts the
execution of any enclosing statement matching the label.
◼ A label is an identifier that uniquely identifies a block of code.
5
Examples
1. Outer: for( int k=1; k< 10; k++){
int i=k;
while ( i < 5) {
if(i%5==0) break Outer; // jump out of both loops
System.out.print(“ “+i);
i++;
}
System.out.println(“Outer Loop”);
}
2. int i=1;
while ( i < 10) {
if(i%2==0) break;
System.out.println(“ “+i);
}
System.out.println(“Out of the while loop”);
5
2. The continue statement
◼ is used to alter the execution of the for, do, and while statements.
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.
5
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?
1 + 2 + 4 + 5 + 7 + 8 + 10 = 37
5
3. The return Statement
◼ A return statement is used to transfer the program control to the
caller of a method.
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.
5
Contd…
//Use of Continue and break Statements
class ContinueBreak
{ *
public static void main(String [ ]args)
{ ** Output
Loop1: for(int i=1; i<100; i++) ***
{
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");
}
}
5
Exercise
1. What do the following program print?
public class Mystery3{
public static void main(String args[]){
int row = 10, column;
while(row >= 1){
column = 1;
while(column <= 10){
System.out.print(row % 2 == 1 ? “<” : “>”);
++column;
}
--row;
System.out.println();
}
}
}
5
Contd…
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 could print the following
outputs? c) 5
a) 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 36
Arrays
▪ An array is a group of contiguous or related data items that share a
common name.
▪ is a container object that holds a fixed number of values of a single
type.
▪ Unlike C++ in Java arrays are created dynamically.
▪ An array can hold only one type of data!
Example:
int[] can hold only integers
char[] can hold only characters
◼ A particular values in an array is indicated by writing a number
called index number or subscript in brackets after the array name.
Example:
salary[10] represents salary of the 10th employee.
6
Contd…
◼ The length of an array is established when the array is created.
After creation, its length is fixed.
◼ Array indexing starts from 0 and ends at n-1, where n is the size
of the array.
index values
6
One-Dimensional Arrays
◼ A list of items can be given one variable name using only one
subscript and such a variable is called a single-subscripted
variable or a one-dimensional array.
Creating an Array
▪ Like any other variables, arrays must be declared and created
in the computer memory before they are used.
▪ Array creation involves three steps:
1. Declare an array Variable
2. Create Memory Locations
3. Put values into the memory locations.
6
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).
6
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];
6
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 the
is done using
array subscripts as
follows:
◼ arrayname [subscript] = Value; Example:
number [0]=23;
number[2]=40;
6
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.
6
Contd.
◼ It is also possible to assign an array object to another array object.
Example:
int array1[]= {35,40,23,67,49};
int array2[];
array2= array1;
Array Length
▪ In Java, all arrays store the allocated size in a variable named
length.
▪ We can access the length of the array array1using array1.length.
Example:
int size = array1.length;
6
if (num[i] < num [j])
//sorting of a list of Numbers {
class Sorting //Interchange Values
{ int temp = num[i];
public static void main(String [ ]args)
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(" " + num[ i ] ); System.out.print("SORTED LIST" );
} for (int i=0; i<size; i++)
System.out.print("\n");
//Sorting Begins {
for (int i=0; i<size; i++) System.out.print(" " " + num [i]);
{ }
for (int j=i+1; j<size; j++)
System.out.println(" ");
{
}
}
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
6
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];
7
Contd…
//Application of two-dimensional Array
class MulTable{
final static int ROWS=12;
final static int COLUMNS=12;
public static void main(String [ ]args) {
int pro [ ] [ ]= new int [ROWS][COLUMNS];
int i=0,j=0;
System.out.print("MULTIPLICATION TABLE");
System.out.println(" ");
for (i=1; i<ROWS; i++)
{
for (j=1; j<COLUMNS; j++)
{
pro [i][j]= i * j;
System.out.print(" "+ pro [i][j]);
}
System.out.println(" " );
}
}
} 48
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]
7
Strings
◼ 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.
7
Contd…
◼ In Java, strings are class objects and are implemented using two
classes:
➢ String class
➢ StringBuffer
◼ Once a String object is created it cannot be changed. Strings are
Immutable.
◼ To get changeable strings use the StringBuffer class.
◼ A Java string is an instantiated object of the String class.
◼ Java strings are more reliable and predictable than C++ strings.
◼ A java string is not a character array and is not NULL
terminated.
7
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
7
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”;
7
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)
Ex: char ch;
ch = “abc”.charAt(1); // ch = “b”
7
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
7
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 WEL-COME
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
7
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. compareTo(); method Compares two strings lexicographically.
◼ The result is a negative integer if the first String is less than the second
string.
◼ It returns a positive integer if the first String is greater than the second
string. Otherwise the result is zero.
Syntax : public int compareTo(String anotherString);
public int compareToIgnoreCase(String str);
Ex: (“hello”.compareTo(“Hello”)==0) ? System.out.println(“Equla”);
: System.out.println(“Not Equal”); //prints Not Equal
8
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
8
Contd…
12. 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 "ile“
"smiles".substring(1, 5); //returns "mile“
13. The startsWith(); Tests if this string starts with the specified prefix.
Syntax: public boolean startsWith(String prefix);
Ex: “Figure”.startsWith(“Fig”); // returns true
14. The indexOf(); method returns the position of the first occurrence
of a character in a string either starting from the beginning of the
string or starting from a specific position.
8
Contd.
▪ public int indexOf(int ch); Returns the index of the first
occurrence of the character within this string starting from the
first position.
▪ public int indexOf(String str); - Returns the index of the first
occurrence of the specified substring within this string.
▪ public int indexOf(char ch, int n); - Returns the index of the
first occurrence of the character within this string starting
from the nth position.
Ex: String str = “How was your day today?”;
str.indexOf(‘t’); // prints 17
str.indexOf(‘y’, 17); // prints 21
str.indexOf(“was”); // Prints 4
str.indexOf("day",10)); //Prints 13
8
Contd…
15. The lastIndexOf(); method Searches for the last occurrence of a
character or substring.
▪ The methods are similar to indexOf() method.
16. valueOf(); creates a string object if the parameter or converts the
parameter value to string representation if the parameter is a variable.
Syntax: public String valueOf(variable);
public String valueOf(variable);
Ex: char x[]={'H','e', 'l', 'l','o'};
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
8
Exercise
1. Consider a two-by-three integer two-dimensional array named array3.
a) Write a statement that declares and creates array3.
b) Write a single statement that sets the elements of array3 in row 1 and
column 2 as zero.
c) Write a series of statements that initializes each element of array3 to 1.
d) Write a nested for statement that initializes each element of array3 to
two.
e) Write a nested for statement that inputs the values for the elements of
array3 from the user.
f) Write a series of statements that determines and prints the 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.
8
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.
8
Thank you
Question?