You are on page 1of 54

String Methods

 A String is a variable for series of characters.


 Use double quotation for initialization.
 Example
J h an e
 String name= “Jhane”
0 1 23 4
 Characters are accessed by their index.
 But this string is not simple variable datatype like
primitive data types.
 We can use the string Object to access the
predefined methods in string class.

12/10/2019
String Length Method- length()
2

 length() method :- returns the number of


characters contained in the string object
 Example
public class StringDemo {
public static void main(String args[]) {
String number = “Number of Character";
int len = number.length();
System.out.println( "String Length is : " + len );
}
String Length is : 19
}

12/10/2019
Concatenating Methods-concat()
3

 string1.concat(string2); :-returns a new string that is


string1 with string2 added to it at the end.
 Example
public class StringDemo {
public static void main(String args[]) {
String string1 = "String One";
String string2="String two";
String string3=string1.concat(string2)
System.out.println(string3);
} String One String two
}

12/10/2019
charAt(index)
4

 charAt(index):- Returns the character at the


specified index from the string.
 Example
public class StringDemo {
public static void main(String args[]) {
String str = "Hello World";
char A=str. charAt(6);
System.out.println( "Character at index 6 is "+ A);
}
Character at index 6 is W
}

12/10/2019
indexOf(substring/char)
5

 Returns the index within this string of the first


occurrence of the specified character or first
occurrence of the specified substring. Returns -1 if not
matched
 Example
World Starts at index 6
public class StringDemo { o Occured at index 4
public static void main(String args[]) {
String str = "Hello World";
int A=str. indexOf("World");
int B=str. indexOf('o');
System.out.println(" World Starts at index "+ A);
System.out.println(" o Occured at index "+ B);}
}
12/10/2019
indexOf(substring,index)
6

 Returns the index within this string of the first occurrence of


the specified substring, starting at the specified index.

 Example
public class StringDemo
public static void main(String[] args) {
String str = “Java is Programming Language";
int A=str.indexOf(“is",4 );
int B=str. indexOf('F');
System.out.println(" is Starts at index "+ A);
System.out.println(" F occured at index "+ B);
}}
World Starts at index 5
F occured at index -1
12/10/2019
Substring Methods
7

 substring(beginIndex):- Returns this string’s


substring that begins with the character at the
specified beginIndex and extends to the end of the
string
 substring(beginIndex, endIndex):-Returns this
string’s substring that begins at the specified
beginIndex and extends to the character at index
endIndex – 1

12/10/2019
8

 toLowerCase():- Returns a new string with all


characters converted to lowercase
 toUpperCase():- Returns a new string with all
characters converted to uppercase
 Example
 String str=“Welcome to Java”.
 String low=str.toLowerC ase();// welcome to java
 String up=str.toUpperCase();// WELCOME TO JAVA

12/10/2019
Example
9
public class Example {
public static void main(String[] args) {

String Sentence= "Text Processing is Hard";


int position =Sentence.indexOf("Processing");
System.out.println(Sentence);
System.out.println(position);
Sentence=Sentence.substring(position,19)+"easy";
Sentence=Sentence.toUpperCase();
System.out.println("The changed String is:- "+Sentence);
Sentence=Sentence.substring(14)+ " programming";
int x=Sentence.length();
System.out.println(x);
System.out.println(Sentence);
Sentence=Sentence.toLowerCase();
int index= Sentence.indexOf("E");
System.out.println(Sentence);
System.out.println(index); }}
12/10/2019
10

T e x t P r o c e s s i n g i s H a r d
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22

P R O C E S S I N G I S E A S Y

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
E A S Y p r o g r a m m i n g
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Text Processing is Hard


5
The changed String is:- PROCESSING IS EASY
16
EASY programming
easy programming
-1

12/10/2019
Data type Conversion
11

Type Conversion and Casting


 Sometimes, you need to convert numeric data of one type to
another.
 E.g. convert a double value to an integer, or vice versa.
 Some conversions can be done automatically/implicitily if the
two numbers are compatible.
 Others are done using a technique called casting.
Casting
 To create a conversion between two incompatible types, you
must use a cast.
 A cast is simply an explicit type conversion.
 Casting is similar to conversion, but isn’t done automatically.
 Casting does not change the variable being cast

12/10/2019
12

 Syntax is:
variable = (data-type) value;
 Here, data-type specifies the desired type to convert the specified value to.
Example:-
Conversion of int to byte.
byte b; i and b 257 1
int i = 257;
double d = 323.142;
Conversion of double to int.
System.out.println("\nConversion of int to byte.");
d and i 323.142 323
b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("\nConversion of double to int."); Conversion of double to
i = (int) d; byte.
System.out.println("d and i " + d + " " + i); d and b 323.142 67
System.out.println("\nConversion of double to byte.");
b = (byte) d;
System.out.println("d and b " + d + " " + b);

12/10/2019
string to a primitive type Conversion
13

 To convert a string to a primitive type, you use a


parse method of the appropriate wrapper class.

12/10/2019
14

 To convert numeric data types to string datatype


toString method.
 Integer.toString(int i): This returns a String object
representing the specified integer.

 Example
int a=1234;
String str=Integer.toString(a);

12/10/2019
Control Structure
15

 The statements inside your Java codes 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.

 There are three basic Control flow statements:


 Decision making or selection statement (if, if-else, switch)
 Looping or Iteration statement (while, for, do-while)
 Breaking or Jumping statement (break, continue)

12/10/2019
if Statement
16

 The syntax of if-then statement in Java is:


if (expression)
{
// statements
}

 expression is a boolean expression (returns either true or


false)
 If the expression is evaluated to false, statement(s) inside the
body of if are skipped from execution.
 If the expression is evaluated to true, statement(s) inside the
body of if (statements inside parenthesis) are executed.

12/10/2019
17

Example:
Public class IfStatement {
public static void main(String[] args) {
int number = 10; if (number > 0) {
System.out.println("Number is positive."); }
System.out.println("This statement is always executed."); }
}

12/10/2019
18

 The syntax of if-then-else statement is:


if (expression) {
// codes }
else {
// some other code }
 How it Works?

12/10/2019
Example
19

public class Specify {


public static void main(String[] args) { Number is positive.
int number = 10; This statement is always executed.
if (number > 0) {
System.out.println("Number is positive.");
}
else
{
System.out.println("Number is not positive.");
}
System.out.println("This statement is always executed.");
}}

12/10/2019
if..else if..else Statement
20

if (expression1)
{
// codes
}
else if(expression2)
{
// codes
}
.
.
else
{
// codes
}

12/10/2019
Example
21

public class Ladder {


public static void main(String[] args) {
Number is 0.
int number = 0;
int b=number++;
if (b> 0) {
System.out.println("Number is positive.");
}

else if (b< 0) {
System.out.println("Number is negative.");
}
else {
System.out.println("Number is 0.");
}
}

12/10/2019
Nested if..else Statement
22

 It's possible to have if..else statements inside a


if..else statement in Java. It's called nested if...else
statement
 Example Write A java program that will find the
largest of three numbers.

12/10/2019
Solution
23

if (n1 >= n2) {


import java.util.Scanner; if (n1 >= n3) {
Public class Number { largestNumber = n1;
public static void main(String[] args) { }
double n1,n2 ,n3, largestNumber; else {
Scanner obj = new Scanner(System.in); largestNumber = n3;
System.out.println(“Enter Three }}
Numbers”); else {
n1=obj.nextDouble(); if (n2 >= n3) {
n2=obj.nextDouble(); largestNumber = n2; }
n3=obj.nextDouble(); else {
largestNumber = n3; } }
System.out.println("Largest
number is " +
largestNumber);
}}

12/10/2019
Exercise
24

 Write java program that rearrange three input


integers in increasing order.

 Sample:
Enter three integers
45
32
-1
The numbers in creasing order is:- -1,32,45

12/10/2019
Switch
25

 Switch provides an easy way to dispatch execution to different parts of


your code based on the value of an expression.
 The switch statement can have a number of possible execution paths.
 Syntax:
switch (expression) {
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
...
default:
// default statement sequence
}

12/10/2019
26

Public class Day {


public static void main(String[] args) {
int week = 4; String day;
Output:
switch (week) { Wednesday
case 1: day = "Sunday"; break;
case 2: day = "Monday"; break;
case 3: day = "Tuesday"; break;
case 4: day = "Wednesday"; break;
case 5: day = "Thursday"; break;
case 6: day = "Friday"; break;
case 7: day = "Saturday"; break;
default: day = "Invalid day"; break; }
System.out.println(day); } }

12/10/2019
27

 Write a java program that prompts a user for two


integer and prompts the user to enter an option as
follows.
1---to add the numbers
2---to subtract the second from the first
3---to multiple the first by the second
4-----to divide the first by the second
 Display an error Message if the user enters an option
other than 1-4 or if the user chooses the divide
option and enter 0 for the second number.

12/10/2019
Loops
28

 Loop is used in programming to repeat a specific


block of code until certain condition is met (test
expression is false).
 Java programming language provides mainly three
iteration statements such as :
forstatement
 while statement
 do-while statement

12/10/2019
for loop
29

 The syntax of for Loop in Java is:

for (initialization; testExpression; update)


{
// codes inside for loop's body
}

12/10/2019
How for loop works?
30

1. The initialization expression is executed only once.


2. Then, the test expression is evaluated. Here, test expression is
a boolean expression.
3. If the test expression is evaluated to true,
 Codes inside the body of for loop is executed.
 Then the update expression is executed.
 Again, the test expression is evaluated.
 If the test expression is true, codes inside the body of for
loop is executed and update expression is executed.
 This process goes on until the test expression is evaluated to
false.
4. If the test expression is evaluated to false, for loop terminates.

12/10/2019
for loop flow chart
31

12/10/2019
Example:
32

 Write program that checks if a number is prime or not


int num = 14;
boolean isPrime = true;
for(int i=2; i <= num/2; i++) {
if((num % i) == 0) {
isPrime = false;
break;
}}
if(isPrime == True)
{
System.out.println(“It is prime”);
}
else
{
System.out.println(“It is not prime”);
}

12/10/2019
infinite for Loop
33

 If the test expression is never false, for loop will run


forever. This is called infinite for loop.
 Example:
class Infinite {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 10; --i) {
System.out.println("Hello");}}}

 Infinite
for ( ; ; ) { }

12/10/2019
while loop
34

 The syntax of while loop is:


while (testExpression) {
// codes inside body of while loop
}
How while loop works?
 The test expression inside parenthesis is a Boolean expression.
 If the test expression is evaluated to true, statements inside the
while loop are executed. Then, the test expression is evaluated
again.
 This process goes on until the test expression is evaluated to
false.
 If the test expression is evaluated to false, while loop is
terminated.

12/10/2019
35

// Program to print line 10 times


class Loop {
public static void main(String[] args) { Line 1
Line 2
int i = 1; Line 3
Line 4
while (i <= 10) { Line 5
System.out.println("Line " + i); Line 6
Line 7
++i; Line 8
Line 9
} Line 10
}
}
12/10/2019
do…while
36

 The do...while loop is similar to while loop with one


key difference. The body of do...while loop is
executed for once before the test expression is
checked
 The syntax of do..while loop is:
do {
// statements
} while (testExpression);

12/10/2019
Flow Chart of do..while()
37

Example
 Write calculates the sum of numbers entered by the
user until user enters 0.

12/10/2019
Solution
38

import java.util.Scanner;
public class Sum {
public static void main(String[] args) {
Double number, sum = 0.0;
Scanner input = new Scanner(System.in);
do {
System.out.print("Enter a number: ");
number = input.nextDouble();
sum += number;
} while (number != 0.0);
System.out.println("Sum = " + sum);
}
}

12/10/2019
39

 Write a java program that prompts a user to enter


your name and reverse it;

 Example
Enter Your Name: Abebe
The reversed name is: ebebA

12/10/2019
Solution
40

import java.util.Scanner;
public class Reverse {

public static void main(String[] args)


{
System.out.print("Enter Your Name:");

Scanner read = new Scanner(System.in);


String name = read.next();

System.out.print("Reversed Name is:");


for(int i = name.length() - 1; i >= 0; i--)
{
System.out.print(name.charAt(i));
}
System.out.println();
}

12/10/2019
break Statement
41

 using break statement, you can force immediate termination of


a loop.
 When a break statement is encountered inside a loop, the loop
is terminated
 Example: terminate loop if i is 10
public static void main(String args[]) {
for(int i = 0; i < 100; i++) {
if(i == 10)
break;
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}

12/10/2019
continue Statement
42

 Sometimes it is useful to force an early iteration of a loop.


 This forces the abortion of current iteration of a loop and
continue to the next iteration.
 Example: add number between 0 -100 excluding numbers from 40-60
double sum = 0;
for(int t = 1; t < 100; t++) {
if(t >= 40 && t <= 60)
continue;
sum = sum + t;
}

12/10/2019
Example
43

public class ContinueTest{


public static void main(String [] args)
{
for(int count= 1; count < =10; count ++)
{
if(count==5)
continue;
System.out.printf(“%d”,count)
}
}
} 1 2 3 4 6 7 8 9 10
12/10/2019
Array
44

 An array is a container that holds data (values) of


one single type.
 Declaration
dataType[] arrayName;
 dataType can be a primitive data type like: int, char,
Double, byte etc. or string or an object
 arrayName is an identifier.
 Example double [] data;
 data is an array that can hold values of type Double

12/10/2019
45

 Use new keyword for memory location creation


 Example int [] num= new int[10];
 Use brace for initialization of arrays.
 Ex:- int [] age={21,23,24,26,78};

12/10/2019
Accessing Elements of Array
46

 Use index number to access array Elements


 Example:- int[] age = new int[5];

 first element of array is age[0], second is age[1] and


so on

12/10/2019
One Dimensional Array
47

 Loops provide a way to iterate over arrays.


 One of the most common ways to process an array is with a for loop.
 Example: a program that stores numbers from 1-100 on an array
int[] numbers = new int[100];
for (int i = 0; i < 100; i++)
numbers[i] = i;

 And here’s a loop that fills an array of player names with strings entered by
the user:
String scientist[] = new String[10];
Scanner sc=new Scanner(new System.in)
for (int i = 0; i < scientist.length; i++) {
System.out.print(“Enter scientist’s name: “);
scientist[i] = sc.next(); // sc is a Scanner
}

12/10/2019
Multidimensional Arrays
48

 In Java, multidimensional arrays are actually


arrays of arrays.
 When the elements of an array are themselves,
arrays, we say that the array is multidimensional.
 If the number of dimensions is only two, then the
array is called a two-dimensional array.
 Multidimensional arrays are often used to
represent tables of values consisting of information
arranged in rows and columns.

12/10/2019
49

 For example, the following declares a two-dimensional


array variable
int [][] Matrix = new int [5][4];
 Here’s an example that initializes the Matrix array:
int [][] Matrix= {
{2, 6, 3, 4},
{5, 2,9, 1},
{7, 0, 2,3},
{9, 3, 4, 3}
{3, 3, 9, 4}};

12/10/2019
50

 Write a java program a that prompt the user to enter


two matrixes and it display the sum.
Soln
import java.util.Scanner;
public class MatrixAddition {
public static void main(String args[])
{
int m, n, c, d;
Scanner in = new Scanner(System.in);

12/10/2019
51

System.out.println("Enter the number of rows and columns of matrix");


m = in.nextInt();
n = in.nextInt();

int first[][] = new int[m][n];


int second[][] = new int[m][n];
int sum[][] = new int[m][n];
System.out.println("Enter the elements of first matrix");

for (c = 0; c < m; c++){


for (d = 0; d < n; d++){
first[c][d] = in.nextInt();}}

12/10/2019
52

System.out.println("Enter the elements of second matrix");

for (c = 0 ; c < m; c++){


for (d = 0 ; d < n; d++){
second[c][d] = in.nextInt();
}}
for (c = 0; c < m; c++){
for (d = 0; d < n; d++)
{
sum[c][d] = first[c][d] + second[c][d];
}}

12/10/2019
53

System.out.println("Sum of the matrices:");


for (c = 0; c < m; c++)
{
for (d = 0; d < n; d++)
{
System.out.print(sum[c][d] + "\t");
}
System.out.println(); } } }

12/10/2019
54

Question?

12/10/2019

You might also like