0% found this document useful (0 votes)
19 views84 pages

5 - Java Arrays & Strings

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 84

IS 2104 - Rapid Application Development

Java Arrays & Java Strings


kav@ucsc.cmb.ac.lk
Slides adapted from Mr. Shavindra Wickramathilaka
1
Java Strings

2
What are Strings?
▷ A string in literal terms is a series of characters.
▷ Basic Java String is basically an array of characters.

L U M O S

3
Why use Strings?
▷ One of the primary functions of modern computer science, is processing human
language.
▷ Similarly to how numbers are important to math, language symbols are important to
meaning and decision making.
▷ Although it may not be visible to computer users, computers process language in the
background as precisely and accurately as a calculator.
○ Help dialogs provide instructions.
○ Menus provide choices.
○ And data displays show statuses, errors, and real-time changes to the language.
▷ As a Java programmer, one of your main tools for storing and processing language is
going to be the String class.

4
String Syntax Examples
▷ String txt = "LUMOS";

5
String Concatenation
▷ Joining or combining two string together
▷ Two syntaxes
○ concat()
○ +

6
String Concatenation cont
public class string1 {
public static void main(String[] args) {
String firstName = "John";
String lastName = "Doe";
String fullName= firstName.concat(lastName);

System.out.println(fullName);
}
}

7
String Concatenation cont

8
String Concatenation cont
public class string2 {
public static void main(String[] args) {
String firstName = "John";
String lastName = "Doe";
String fullName= firstName+lastName;

System.out.println(fullName);
}
}

9
String Concatenation cont

10
Important Java String methods
▷ charAt()
▷ concat()
▷ contains()
▷ equals() / equalsIgnoreCase()
▷ indexOf() / lastIndexOf()
▷ length()
▷ matches()
▷ replace() / replaceFirst() / replaceAll()
▷ split()
▷ toLowerCase() / toUpperCase()
▷ trim()

11
charAt()
▷ Returns the character at the specified index in a string.
▷ Indexes start at 0

12
public class string3 {
public static void main(String[] args) {
String firstName = "John";
char thirdLetter= firstName.charAt(2);

System.out.println(thirdLetter);
}
}

13
14
concat()
▷ Join strings together

15
contains()
▷ Checks whether a string contains a sequence of characters.
▷ Returns a boolean.

16
public class string4 {
public static void main(String[] args) {
String name = "John Doe";
System.out.println(name.contains("John"));
System.out.println(name.contains("Doe"));
System.out.println(name.contains("john"));
System.out.println(name.contains("Alice"));
}
}

17
18
equals() / equalsIgnoreCase()
▷ The equals() method compares two strings, and returns true if the strings are equal,
and false if not.
▷ The equalsIgnoreCase() method compares two strings, ignoring lowercase and
uppercase differences.

19
public class string5 {
public static void main(String[] args) {
String input1 = "Yes";
String input2 = "No";

System.out.println(input1.equals("Yes"));
System.out.println(input1.equals("yes"));
System.out.println(input2.equalsIgnoreCase("No"));
System.out.println(input2.equalsIgnoreCase("no"));
}
}
20
21
indexOf() / lastIndexOf()
▷ The indexOf() method returns the position of the first occurrence of specified
character(s) in a string.
▷ The lastIndexOf() method returns the position of the last occurrence of specified
character(s) in a string.

22
public class string6 {
public static void main(String[] args) {
String input1 = "taco cat";

System.out.println(input1.indexOf("c"));
System.out.println(input1.lastIndexOf("c"));
System.out.println(input1.indexOf("o"));
System.out.println(input1.lastIndexOf("o"));

}
}
23
24
length()
▷ Returns the length of a specified string.

25
public class string7 {
public static void main(String[] args) {
String password = "32tFG%IohKY}reGYId'V]YU8Jr^x4b4]!}FLbj.3fr";

System.out.println(password.length());

}
}

26
27
matches()
▷ Returns whether or not this string matches the given regular expression.

28
public class string8 {
public static void main(String[] args) {
String email = "kav@ucsc.cmb.ac.lk";
String email2 = "2022is001@stu.ucsc.cmb.ac.lk";

System.out.println(email.matches("[a-z]{3}+@ucsc.cmb.ac.lk"));
System.out.println(email2.matches("[a-z]{3}+@ucsc.cmb.ac.lk"));

}
}

29
30
replace() / replaceFirst() / replaceAll()
▷ replace()
○ Searches a string for a specified value, and returns a new string where the
specified values are replaced
▷ replaceFirst()
○ Replaces the first occurrence of a substring that matches the given regular
expression with the given replacement
▷ replaceAll()
○ Replaces each substring of this string that matches the given regular expression
with the given replacement

31
public class string9 {
public static void main(String[] args) {
String string1 = "1234567890987654321";

System.out.println(string1.replace("1","a"));
System.out.println(string1.replaceFirst("1","a"));
System.out.println(string1.replaceAll("123","abc"));

}
}

32
33
split()
▷ Splits a string into an array of substrings

34
public class string10 {
public static void main(String[] args) {
String filename = "rad.pdf";

System.out.println(filename.split("\\.")[0]);
System.out.println(filename.split("\\.")[1]);

}
}

35
36
toLowerCase() / toUpperCase()
▷ The toLowerCase() method converts a string to lower case letters.
▷ The toUpperCase() method converts a string to upper case letters.

37
public class string11 {
public static void main(String[] args) {
String name = "John Doe";

System.out.println(name);
System.out.println(name.toLowerCase());
System.out.println(name.toUpperCase());

}
}

38
39
trim()
▷ Removes whitespace from both ends of a string

40
public class string12 {
public static void main(String[] args) {
String name = " John Doe ";

System.out.println(name);
System.out.println(name.trim());

}
}

41
42
Important Points to Note
▷ String is a Final class; i.e once created the value cannot be altered. Thus String objects
are called immutable.
▷ The Java Virtual Machine(JVM) creates a memory location especially for Strings called
String Constant Pool. That’s why String can be initialized without ‘new’ keyword.
▷ String class falls under java.lang.String hierarchy. But there is no need to import this
class. Java platform provides them automatically.
▷ String reference can be overridden but that does not delete the content

43
public class string13 {
public static void main(String[] args) {
String str1 = "RAD";
String str2 = "RAD";
String str3 = new String("RAD");

System.out.println(str1==str2);
System.out.println(str1==str3);
}
}

44
45
public class string14 {
public static void main(String[] args) {
String str1 = "RAD";
String str2 = "RAD";
String str3 = new String("RAD");

System.out.println(System.identityHashCode(str1));
System.out.println(System.identityHashCode(str2));
System.out.println(System.identityHashCode(str3));
}
}
46
47
Java Arrays

48
What is an Array?
▷ An array is a very common type of data structure wherein all elements must be of the
same data type.
▷ Once defined, the size of an array is fixed and cannot increase to accommodate more
elements.
▷ The first element of an array starts with index zero.

49
In simple words, it’s a programming construct which helps to replace this

x0=0;
x1=1;
x2=2;
x3=3;
x4=4;
x5=5;

with this

x[0]=0;
x[1]=1;
x[2]=2;
x[3]=3;
x[4]=4;
x[5]=5;

50
Array Variables
Using an array in your program is a 3 step process -
1) Declaring your Array
2) Constructing your Array
3) Initialize your Array

51
Declaring your Array
▷ Syntax
○ type[] name; //Java Style
or
○ type name[]; // C-style

52
public class array1 {
public static void main(String[] args) {
int[] array1;
int array2[];
}
}

53
Constructing an Array
▷ Syntax
○ arrayname = new dataType[length]

54
public class array2 {
public static void main(String[] args) {
int[] array1;
array1= new int[10];
}
}

55
Declaration and Construction
combined
public class array3 {
public static void main(String[] args) {
int[] array1 = new int[10];
}
}

56
Initialize an Array
▷ ArrayName[Index] = Value;

57
public class array4 {
public static void main(String[] args) {
int[] array1 = new int[10];
array1[0]=1;
System.out.println(array1[0]);
}
}

58
59
Declaring and initialize an Array
▷ DataType Name[] = {Elements , Seperated , With , Commas}

60
public class array5 {
public static void main(String[] args) {
int[] array1 = {1,2,3,4,5,6,7,8,9,10};
System.out.println(array1[0]);
System.out.println(array1[9]);
}
}

61
62
Java Array: Pass by reference
▷ Arrays are passed to functions by reference, or as a pointer to the original. This means
anything you do to the Array inside the function affects the original.

63
Multidimensional arrays
▷ Multidimensional arrays are actually arrays of arrays.
▷ To declare a multidimensional array variable, specify each additional index using
another set of square brackets.
○ Ex: int twoD[ ][ ] = new int[4][5] ;
▷ When you allocate memory for a multidimensional array, you need only specify the
memory for the first (leftmost) dimension.
▷ You can allocate the remaining dimensions separately.
▷ In Java, array length of each array in a multidimensional array is under your control.

64
public class array8 {
public static void main(String[] args) {
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
for (int i = 0; i < myNumbers.length; ++i) {
for(int j = 0; j < myNumbers[i].length; ++j) {
System.out.println(myNumbers[i][j]);
}
}
}
}

65
66
Loop through array
public class array6 {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}
}
}

67
public class array7 {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
}
}
}

68
69
What is ArrayList in Java?
▷ ArrayList is a data structure that can be stretched to accommodate additional
elements within itself and shrink back to a smaller size when elements are removed.
▷ It is a very important data structure useful in handling the dynamic behavior of
elements.

70
Wondering how ArrayList java could be useful, see the below conversation -

71
See the following picture of a man stretching an elastic rubber band.
The actual length of the rubber band is much smaller, but when stretched it can extend a lot
more than its actual length and can be used to hold/bind much larger objects with it.
Now, consider the next picture, that of a simple rope, it cannot stretch and will have a fixed
length.

72
▷ It can grow as, and when required to accommodate the elements it needs to store and
when elements are removed, it can shrink back to a smaller size.
▷ So as our friend has an issue with the array he is using cannot be expanded or made to
shrink, we will be using ArrayList.
▷ Arrays are like the rope shown in the above picture; they will have a fixed length,
cannot be expanded nor reduced from the original length.
▷ So our stretchable rubber-band is much like the Array List whereas the rope can be
considered as the array.
▷ Technically speaking, java Array List is like a dynamic array or a variable-length array.
▷ Let us see and understand the following code snippet that will help you work around
with Array List.

▷ ArrayList<Object> a = new ArrayList<Object>();

73
ArrayList Methods
▷ ArrayList add: This is used to add elements to the Array List. If an ArrayList already
contains elements, the new element gets added after the last element unless the index
is specified.
○ Syntax:
add(Object o);
▷ ArrayList remove: The specified element is removed from the list and the size is
reduced accordingly. Alternately, you can also specify the index of the element to be
removed.
○ Syntax:
remove(Object o);

74
▷ Java array size: This will give you the number of elements in the Array List. Just like
arrays, here too the first element starts with index 0.
○ Syntax:
int size();
▷ ArrayList contains: This method will return true if the list contains the specified
element.
○ Syntax:
boolean contains(Object o);

75
import java.util.ArrayList;

public class arrayList1 {


public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
System.out.println(cars);
System.out.println(cars.get(1));
cars.set(1,"Tesla");
cars.remove(3);
System.out.println(cars);
System.out.println(cars.size());

}
}

76
77
▷ You can loop through ArrayLists using loops.
▷ You can sort ArrayLists using java.util.Collections class

78
import java.util.ArrayList;
import java.util.Collections;

public class arrayList2 {


public static void main(String[] args) {
ArrayList<String> letters = new ArrayList<String>();
letters.add("B");
letters.add("C");
letters.add("A");
letters.add("E");
letters.add("D");
System.out.println(letters);
Collections.sort(letters);
System.out.println(letters);

}
}
79
80
81
Homework
▷ Read and learn about Regular Expressions

82
References
www.w3schools.com
www.javatpoint.com
www.tutorialspoint.com

83

Thank You

84

You might also like