Download as pdf or txt
Download as pdf or txt
You are on page 1of 57

COMP 250

INTRODUCTION TO COMPUTER SCIENCE


3 – Strings & Arrays

Hsiu-Chin Lin

Material by Giulia Alberini and Michael Langer


WHAT ARE WE GOING TO DO TODAY?

▪ Last Time ▪ Today


▪ Operators ▪ Continue with Type Casting
▪ If-else, while, for ▪ Strings
▪ Primitive Data types ▪ Arrays
▪ Char ▪ Reference Types
QUESTIONS FROM THE LAST LECTURE

do {
▪ Is there a do-while in Java?
statement(s)
▪ Yes, it looks like other language
} while (expression);

double d = 3.0 ;
▪ How do we initialize float?
float f = 3.0f ;
TYPE CASTING
TYPECASTING

▪ Typecasting: convert back and forth between variables of different types.


(or casting, for short)

int x = 3; // x is an integer
double y = 4.56; // y is a double
int n = (int) y; // convert y to integer
double m = (double) x; // convert x to double

▪ What are the values of n, and m?


➢ n = 4, m = 3.0
PRIMITIVE TYPE CONVERSION – INT & DOUBLE
▪ When going from int to double, an explicit cast is NOT necessary
because double is "wider" than int

int x = 3; // x is an integer
double m = (double) x; // convert x to double
double n = x; // it's ok to skip (double)

▪ When going from double to int, you will get a compile-


time error if you don't have an explicit cast.
PRIMITIVE TYPE CONVERSION – IN GENERAL
type number of bits

double 64
float 32
long 64
wider narrower
int 32
Here, wider usually
(but not always)
char 16
means more bytes. short 16
byte 8

Widening and narrowing change the bit representation (Details in ECSE 222 and
324)
NOTE: char is "special"... see the following slides.
EXAMPLES
int i = 3;
double d = 4.2;

d = i; // widening (implicit casting)

d = 5.3 * i; // widening(by "promotion")

i = (int)d; // narrowing (by casting)


float f = (float) d; // narrowing (by casting)

• For narrowing, you get a compilation error if you don't cast.


EXAMPLES WITH CHAR
char c = 'q';
int x = c // widening

c = (char) x; // narrowing

short y = 12;

c = y; // compile time error! (need explicit casting)

y = c; // compile time error! Narrowing need explicit


casting
STRINGS
STRING

▪ A String is sequence of characters.

▪ String is a Class and a string literal is an Object.


(more on classes and objects in the following weeks)

▪ We cannot use operators on Strings (e.g., *, -, /, ==, !=)

▪ There's a set of methods provided to manipulate characters and they


can be called on values of type String.
DOCUMENTATION

You can find it here:


https://docs.oracle.com/java
se/7/docs/api/java/lang/Stri
ng.html
COMPARING STRINGS
▪ To compare two strings, you can use one of the following methods

▪ There's no keyword static!


This means that the methods need to be called on a specific value/variable of
type String and not on the name of the class (like, for instance, the method
abs from the Math library).
String course = "ECSE 250" ;
String course2 = "ecse 250" ;
boolean a = course.equals(course2);
COMPARING STRINGS
▪ equals is case sensitive, use equalsIgnoreCase if you don't want to
distinguish between upper and lower case.

String course = "ECSE 250" ;


String course2 = "ecse 250" ;
boolean a = course.equals(course2);
boolean b = course.equalsIgnoreCase(course2);

▪ What are a and b?


▪ The value of a is false
▪ The value of b is true
COMMON MISTAKES

String course = "ECSE 250";


String course2 = "ecse 250";
if (course == course2) { ….

▪ If you try to use == or != on Strings


▪ you program will compile and run.
▪ It will not do what you think it's doing though.

▪ Always use equals or equalsIgnoreCase if you want to


compare strings.
OTHER METHODS
Let s be a variable of type String. Then some useful methods include:
▪ s.length()
It takes no inputs and returns the number of characters in the String s.

String s = "Another string"; What prints?


System.out.println(s.length()); ➢ 14
OTHER METHODS
▪ s.charAt(i)
▪ returns the character in the String s which has index equal to i
▪ the first character is in index 0
▪ If there's no character with index i, then we will get a run-time error.
(StringIndexOutOfBoundsException)

String s = "Another string"; What prints?


System.out.println(s.charAt(2)); ➢o

String s = "Another string"; What prints?


System.out.println(s.charAt(0)=='a'); ➢ false
REVIEW – METHODS FROM THE STRING CLASS

String s = "Review";

Example – method call Input type Return type Return value


s.equals("review") String boolean false
s.equalsIgnoreCase("review") String boolean true
s.length() none int 6
s.charAt(2) int char 'v'
s.toLowerCase() none String "review"
s.toUpperCase() none String "REVIEW"
CONVERTING TYPES WITH STRINGS
You cannot use a cast when converting from a String.
➢ To convert from int/double to a String, just concatenate the
number with the empty String ("").

String s = "" + 4;
➢ To convert from a String to an int, use:
int x = Integer.parseInt("54");
String s = "5";
int y = Integer.parseInt(s);

➢ To convert from a String to a double, use:


double z = Double.parseDouble("5.4");
ARRAYS
ARRAYS

▪ An array is like a container that holds a fixed number of values of the


same type.
▪ This values can be access using the same variable name.
▪ The length of the array is fixed when the array is created, and it
cannot be changed.
▪ All the elements of an array must be of the same type.

▪ The values in the array are called elements.

▪ The list of elements is indexed, the order matters.


ARRAYS –DECLARATION

To create an array, we first have to declare a variable with an array type:

type[] variable_name;

All the elements of the The square brackets indicate


array must have this type. that this is an array variable
ARRAYS –DECLARATION

▪ To create an array, we first have to declare a variable with an array type:

type[] variable_name;
NOTE: The declaration
creates a variable, but
▪ Examples: we still need to
String[] days; create the actual
array object itself!
int[] grades;
double[] heights;
String[] args;
ARRAYS –EXAMPLE
Here is a list of the days of the week:

Note that we start


0. Monday
counting at 0!!
1. Tuesday
2. Wednesday
3. Thursday
4. Friday
5. Saturday
6. Sunday

We would like to use an array to store them all.


ARRAYS –INITIALIZATION METHOD 1
▪ Using curly brackets, we can assign values to all elements in the array at
the same time as we declare the array:
// days is an array of String values of length 7.
String[] days = {"Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "Sunday"};
0x00FF Monday
▪ Order matters!!
days Tuesday
▪ What is the index of "Tuesday"?
Wednesday
Thursday ▪ Only works if you know the values of
Friday the array before the program runs.

Saturday
Sunday
ARRAYS –INITIALIZATION METHOD 2
▪ Step 1: use the new operator to create an array of a certain size.

Examples:
0x00FF null
String[] days = new String[7];
days null
null
String[] days;
days = new String[7]; null
null
int numOfDays = 7; null
String[] days; null

days = new String[numOfDays];


ARRAYS –INITIALIZATION METHOD 2

▪ Step 2: populate the entries one at a time, later in the program.

Examples
days[1] = "Tuesday"; 0x00FF Monday
days[0] = "Monday";
days Tuesday
days[6] = "Sunday";
days[5] = "Saturday"; Wednesday
days[2] = "Wednesday"; Thursday
days[3] = "Thursday";
Friday
days[4] = "Friday";
Saturday
Sunday
DEFAULT VALUES

▪ As soon as we create an array object and initialize the variable, java


assigns default values to each position in the array. Thus, if we don't
assign any values to the array, it will have the values assigned by default.

▪ The default values are:


▪ For numerical arrays: 0
▪ For String/reference type arrays: null
▪ For char arrays: the character with ASCII value 0
▪ For boolean arrays: false.
SIZE OF AN ARRAY

▪ When we create an array of size n, n contiguous places in memory are


reserved in order to store n values of the same type.

▪ The size of an array cannot be changed after it has been assigned.

▪ Any integer expression can be used for the size of an array as long as the
value is nonnegative. If negative: NegativeArraySizeException.
ACCESSING ELEMENTS

▪ Elements in an array can be access using the name of the array variable
and the index of the element inside square brackets.
▪ days[0] = "Sunday";
The value "Sunday" is assigned to days at index 0
▪ String lastDay = days[6];
The value in days at index 6 is assigned to the variable lastDay
▪ days[0] = days[6];
The value in days at index 6 is assigned to days at index 0.

▪ If we use an index that is negative or grater than the size of the array
minus 1, the result is an ArrayIndexOutOfBoundsException.
ARRAYS AND LOOPS Note the
difference!

▪ When we wanted to traverse a String s, we would loop through all the


indices up to (and not including) s.length()
▪ Similarly, we can access the length of an array using grades.length

double sum = 0;
for (int i = 0; i < grades.length; i++) {
sum += grades[i];
}
double avg = sum/grades.length;
COMMON MISTAKES

▪ Forgetting to initialize the entries of your array.

int[] a = new int[5];

System.out.println(a[0]);

▪ Output: 0
COMMON MISTAKES

▪ Referring to an index that doesn't exists.

String[] petNames = {"Rex", "Sparky", "Bilbo", "Small cat"};


System.out.println(petNames[5]);
System.out.println(petNames[-2]);

▪ ArrayIndexOutOfBounds exception
COMMON MISTAKES

▪ Trying to create an array with negative size.

int size = -3 % 5;
String[] petNames = new String[size];

▪ NegativeArraySizeException exception
COMMON MISTAKES

public static void printDifferences(int[] a) {


for( int i=0; i < a.length; i++ ) {
System.out.println(a[i+1] – a[i]);
}
}

The above code is supposed to loop through an array and print


the difference between adjacent elements.
It contains an error. What is it?
THE JAVA MAIN METHOD
public static void main(String[] args)

You can pass String arguments into your main function

public class Echo {


public static void main (String[] args) {
for ( int i = 0 ; i < args.length ; i++ ) {
System.out.println("Argument " + i + ": " + args[i] );
}
}
}

java Echo Drink Hot Java


java.util.Arrays
As A JAVA CLASS
HOW TO CHECK EQUALITY?

▪ What does the program print?


int[] x = {1,2,3};
false
int[] y = {1,2,3};
System.out.println( x == y );

0x00FF 1 0x0EFE 1
x 2 y 2
3 3

"x == y" compares the "addresses" and "0x00FF != 0x0EFE"


HOW TO CHECK EQUALITY?

int[] x = {1,2,3};
int[] y = {1,2,3};
System.out.println(x.equals(y));

▪ What do you think the program will print?

false
HOW TO CHECK EQUALITY?

int[] x = {1,2,3};
int[] y = {1,2,3}; true

System.out.println(java.util.Arrays.equals(x,y));

▪ Java.util.Arrays.equals compares the content of the two arrays.

▪ Java.util.Arrays
▪ Arrays is a class that contains methods for manipulating arrays.
▪ Arrays is part of the java.util package.
▪ https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html
THE IMPORT STATEMENT
▪ The import statement for the Arrays class:

import java.util.Arrays;

▪ This statement allows us to refer to Arrays in the program without having to


refer to the full package name (java.util.Arrays). It makes sure that the
compiler knows which class we are referring to.

▪ All import statements are at the beginning of the file, before the class
definition.
THE IMPORT STATEMENT

import java.util.Arrays ;

Public class Hello { true

Public static void main(String[] args) {


int[] x = {1,2,3};
int[] y = {1,2,3};
System.out.println(Arrays.equals(x,y));
}
}
java.lang

▪ Exception to the import rule: all classes in the java.lang are


imported by default.

▪ Remember the Math class? It is part of the java.lang package,


therefore we did not need to import it in order to use it.
OTHER USEFUL METHODS?

In the Arrays class you can find:


▪ Arrays.equals(x,y)
It returns a Boolean value indicating whether the content of
the two arrays is the same.

▪ Arrays.toString(x)
It returns the content of an array as a String.

▪ Arrays.sort(x)
It sorts the input array in increasing order.
MULTIDIMENSIONAL
ARRAYS
ARRAYS

▪ We have seen arrays with a fixed length containing elements of the


same type.

▪ What if the elements where of array-type?

▪ How do we create arrays of arrays?


2D ARRAYS – HOW TO CREATE THEM

There are 3 ways to create arrays of arrays:

1. int[][] numbers = {{1}, {1, 2}, {1, 2, 3}};

2. int[][] numbers = new int[3][2];

3. int[][] numbers = new int[3][];


2D ARRAYS – HOW TO CREATE THEM

int[][] numbers = {{5}, {1, 2, 3}, {1, 2}};

This creates an array of length 3, containing integer arrays

The first element is an array of


0 5
length 1 (with value 5)

0 0 1
numbers 1 the second an array of length 3
1 2
(with values 1, 2, 3)
2 2 3

0 1 the third an array of length 2


1 2 (with values 1, 2)
2D ARRAYS – HOW TO CREATE THEM

int[][] numbers = new int[3][2]; 0 0

1 0
0
numbers 1 0 0
2 1 0
▪ This creates an array of length 3.
▪ Each element is an integer array of length 2. 0 0

▪ You can think of it as a 3 by 2 matrix. 1 0

▪ All the elements of the integer arrays are initialized to 0


2D ARRAYS – HOW TO CREATE THEM

int[][] numbers = new int[3][]; 0 null


numbers 1 null
2 null
▪ This creates an array of length 3.
▪ Each element will be an integer array.
▪ For the moment the elements are initialized by default to null.
▪ To populate the element of numbers we need to create 3 integer
arrays and assign them to the elements of numbers one at a time.
2D ARRAYS – TWO EQUIVALENT ARRAYS

Numbers[0] = new int[1] ;


Numbers[0][0] = 5 ; 0 5

0 0 1
numbers 1 1 2
2 2 3
int[] second = {1,2,3};
int[] third = {1, 2} ; 0 1

numbers[1] = second; 1 2

numbers[2] = third ;
MUTABLE V.S. IMMUTABLE

▪ arrays are mutable


▪ you change the element inside of an array
2D ARRAYS

int[][] num = {{1, 2, 3},{0, 0},{5}};

0 1

1 2
num 0 2 3
1
0 0
2
1 0

0 5
2D ARRAYS

int[][] num = {{1, 2, 3},{0, 0},{5}};


num[1][0] = -6

0 1

1 2
num 0 2 3
1
0 -6
2
Note: 1 0
• We changed an element of num[1]. num[1]
is an array and arrays are mutable → the
reference stored in num[1] did not change! 0 5
NOTE ON EQUALITY

▪ If you try to use Arrays.equals(array1, array2) on two arrays of


arrays, it will not compare the elements of the inner arrays.

▪ If you want to compare the elements of the inner arrays you should use

Arrays.deepEquals(array1, array2)
MULTIDIMENSIONAL ARRAYS
▪ You can create arrays with as many dimensions as you like.

int[][][] matrix3D = new int[3][3][3];

String[][][][] string4D = new String[2][][][];

▪ In practice, anything higher than 3D is rarely used.


▪ Today ▪ Next Lecture
▪ Type Casting ▪ Reference Types
▪ Strings ▪ Errors & Exceptions
▪ Arrays

You might also like