0% found this document useful (0 votes)
8 views38 pages

Java Strings and Arrays Guide

The document discusses strings and arrays in Java. It covers string manipulation including length, indexing, substring, and formatting output. It also covers arrays, including one-dimensional and two-dimensional arrays. Example code is provided to count the number of words in a string and print a formatted shopping receipt.

Uploaded by

Vijji Vijay
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)
8 views38 pages

Java Strings and Arrays Guide

The document discusses strings and arrays in Java. It covers string manipulation including length, indexing, substring, and formatting output. It also covers arrays, including one-dimensional and two-dimensional arrays. Example code is provided to count the number of words in a string and print a formatted shopping receipt.

Uploaded by

Vijji Vijay
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

Strings and Arrays

Hendrik Speleers
Strings and Arrays


Overview
– Characters and strings

String manipulation

Formatting output
– Arrays

One-dimensional

Two-dimensional
– Container classes

List: ArrayList and LinkedList

Iterating over a list

NMCGJ
2020-2021
Strings and Arrays


Characters and strings
– A character (char primitive)

Based on Unicode

Indicated by single quotation

– A string (String object) is a container of characters



Indicated by double quotation

Operator + : concatenation of strings into a new string

char c = 'a';
String str = "UNICODE for a is " + (int) c;
if (c < 'W') {...}

NMCGJ
2020-2021
Strings and Arrays


Characters and strings
– Special characters: using an escape sequence (with backslash)
Code Meaning
\t tab
\b backspace
\n newline
\r carriage return
\' single quote
\" double quote
\\ backslash

NMCGJ
2020-2021
Strings and Arrays


Characters and strings
– Some useful String methods

<integer> = <string> . length () ;


<char> = <string> . charAt (<integer>) ;
<integer> = <string> . indexOf (<char>) ;
<string> = <string> . substring (<integer>, <integer>) ;
<boolean> = <string> . equals (<object>) ;

– Every object can be converted to a string (default)

<string> = <object> . toString () ;

NMCGJ
2020-2021
Strings and Arrays


Java program: string manipulation
– Task

Counting the number of words in a string

– Algorithm

Running over characters

Counting each transition from blanc to non-blanc characters

– Input
String text = "Twinkle twinkle little star";

NMCGJ
2020-2021
Strings and Arrays


Java program: string manipulation
– Counting the number of words in a string

int i = 0, wordCount = 0;

while (i < [Link]()) {

while ([Link](i) == ' ') // skip blanc chars


i++;

while ([Link](i) != ' ') // skip non-blanc chars


i++;
wordCount++;

}
NMCGJ
2020-2021
Strings and Arrays


Java program: string manipulation
– Counting the number of words in a string

T
int i = 0, wordCount = 0;

while (i < [Link]()) {


EC
RR
while ([Link](i) == ' ') // skip blanc chars

O
i++;

i++;
T C
while ([Link](i) != ' ') // skip non-blanc chars

} NO
wordCount++;

NMCGJ
2020-2021
Strings and Arrays


Java program: string manipulation
– Counting the number of words in a string

int i = 0, wordCount = 0;

while (i < [Link]()) {

while (i < [Link]() && [Link](i) == ' ')


i++;
if (i < [Link]()) {
while (i < [Link]() && [Link](i) != ' ')
i++;
wordCount++;
}
}
NMCGJ
2020-2021
Strings and Arrays


Characters and strings
– Formatting output (since Java SE5)

[Link](), [Link](), [Link]( )

int x = 5; double y = 5.332542;

// the old way


[Link]("Row [" + x + " " + y + "]");
// the new way
[Link]("Row [%d %f]\n", x, y);
// or
[Link]("Row [%d %f]\n", x, y);
// output
// Row [5 5.332542]
NMCGJ
2020-2021
Strings and Arrays


Characters and strings
– Format specifiers

%<flags><width><.precision><conversion>

optional

conversion
Code Meaning Code Meaning
d integer (decimal) c character (Unicode)
x integer (hexadecimal) s string
f floating point (decimal) b boolean
e floating point (scientific) % literal “%”
NMCGJ
2020-2021
Strings and Arrays


Characters and strings
– Format specifiers

%<flags><width><.precision><conversion>

optional

width: minimum size of a field (padding with space chars)

flags: controls alignment
– default: right alignment
– using ‘−’: left alignment

Precision: meaning depends on type
– strings: maximum number of characters
NMCGJ
– floating points: number of decimal places after comma (default = 6) 2020-2021
Strings and Arrays


Java program: string formatting
– Task

Printing a shopping receipt to the console

– Output

Item Qty Price


---- --- -----
Jack's Magic Beans 4 4.25
Princess Peas 3 5.10
Three Bears Porridge 1 14.29
-----
Total 23.64

NMCGJ
2020-2021
Strings and Arrays


Java program: string formatting
– Printing a shopping receipt to the console

public class Receipt {


private double total = 0.0;
...
public static void main(String[] args) {
Receipt receipt = new Receipt();
[Link]();
[Link]("Jack's Magic Beans", 4, 4.25);
[Link]("Princess Peas", 3, 5.1);
[Link]("Three Bears Porridge", 1, 14.29);
[Link]();
}
}
NMCGJ
2020-2021
Strings and Arrays


Java program: string formatting
– Printing a shopping receipt to the console

public class Receipt {


...
public void printTitle() {
formatItem("Item", "Qty", "Price");
formatItem("----", "---", "-----");
}

private void formatItem(String i, String q, String p) {


[Link]("%-20s %5s %10s\n", i, q, p);
}
...
}
NMCGJ
2020-2021
Strings and Arrays


Java program: string formatting
– Printing a shopping receipt to the console

public class Receipt {


...
public void printItem(String i, int q, double p) {
formatItem(i, q, p);
total += p;
}

private void formatItem(String i, int q, double p) {


[Link]("%-20s %5d %10.2f\n", i, q, p);
}
...
}
NMCGJ
2020-2021
Strings and Arrays


Java program: string formatting
– Printing a shopping receipt to the console

public class Receipt {


...
public void printTotal() {
formatItem("", "", "-----");
formatTotal("Total", total);
}

private void formatTotal(String s, double t) {


[Link]("%-20s %15.2f\n", s, t);
}
...
}
NMCGJ
2020-2021
Strings and Arrays


Arrays
– An array is a sequence of elements of same type (primitives / objects)
– Declaration

<type>[] <array name> ; an array is an object:


reference semantics
– Creation
<array name> = new <type>[<integer>] ;

– Number of elements
<integer> = <array name> . length ;
NMCGJ
2020-2021
Strings and Arrays


Arrays
– Initialization

int nbMonths = 12; index of first position


String[] months = new String[nbMonths]; in an array is zero
months[0] = "January";
months[1] = "February";
...
months[11] = "December";

String[] months = {"January", "February", "March",


"April", "May", "June", "July",
"August", "September", "October",
"November", "December"};
NMCGJ
2020-2021
Strings and Arrays


Arrays
– Initialization

Default value for primitives: zero

Default value for objects: empty object

– Creating an empty object with the null keyword



Object variable is not pointing to an object

Identical for any object type Date

Date date = new Date();


date = null; date

NMCGJ
2020-2021
Strings and Arrays


Arrays
– Repetition statement: foreach loop (since Java SE5)

for (<element> : <array name>)


<for block> if <block> consists of multiple
statements, then use { }

– Comparison between standard for and foreach


for (int i = 0; i < [Link]; i++)
[Link](months[i]);

for (String m : months)


[Link](m);
NMCGJ
2020-2021
Strings and Arrays


Java program: arrays
– Task

Searching maximum element in an unsorted array

– Algorithm

Running over elements

Comparing current element > maximum value so far

– Input
int[] list = {24, 14, 10, 30, 45, 2,
1, 23, 5, 34, 23, 8};

NMCGJ
2020-2021
Strings and Arrays


Java program: arrays
– Searching maximum element in an unsorted array

int valMax = list[0];


int posMax = 0;

for (int i = 1; i < [Link]; i++)


if (list[i] > valMax) {
valMax = list[i]; // update max value
posMax = i; // update position
}

String str = [Link]("The %dth number has "


+ "the maximum value %d", posMax + 1, valMax);
[Link](str);
NMCGJ
2020-2021
Strings and Arrays


Java program: arrays
– Searching maximum element in an unsorted array (bis)

int valMax = list[0];

for (int val : list)


if (val > valMax)
valMax = val; // update max value

String str = [Link]("The maximum value is "


+ valMax);
[Link](str);

NMCGJ
2020-2021
Strings and Arrays


Two-dimensional arrays
– A two-dimensional array is an array of arrays

Arrays are objects

Objects can be elements in an array

– Creating a matrix
<type>[][] <matrix name> = new <type>[<integer>][<integer>];

NMCGJ
2020-2021
Strings and Arrays


Two-dimensional arrays price
– Example

int[][] price = new int[3][2];


...
int value = price[1][0];

price
– Number of rows and columns
price[1]
int r = [Link]; = 3 price[1][0]
int c = price[0].length; = 2

NMCGJ
2020-2021
Strings and Arrays


Two-dimensional arrays
– A two-dimensional array is not always a matrix!
price
int[][] price = new int[3][];
price[0] = new int[3];
price[1] = new int[2];
price[2] = new int[1];

– Multi-dimensional arrays

straightforward extension

NMCGJ
2020-2021
Strings and Arrays


Two-dimensional arrays
– Example: printing a given matrix to the console

int[][] matrix = {{1,2,3},


{4,5,6}};

for (int i = 0; i < [Link]; i++)


for (int j = 0; j < matrix[i].length; j++)
[Link](
"matrix[%d][%d] = %d\n",
i, j, matrix[i][j]
);

NMCGJ
2020-2021
Strings and Arrays


Two-dimensional arrays
– Example: printing a given matrix to the console (bis)

int[][] matrix = {{1,2,3},


{4,5,6}};

[Link]("matrix = ");
for (int[] row : matrix) {
[Link](" [");
for (int entry : row)
[Link]("[%d]", entry);
[Link]("]");
}

NMCGJ
2020-2021
Strings and Arrays


Container classes
– Arrays

Most efficient way to hold a group of objects (compiler supported)

Primitives or objects of same type

Fixed size
– Container classes

Part of the library [Link]

Sophisticated ways to hold your objects
– Exploiting characteristics of your group (List, Set, Map, ...)

Objects of same type (based on the concept of generics)

Automatically resizing
NMCGJ
2020-2021
Strings and Arrays


Container classes
– Overview of basic interfaces

Collection: a sequence of elements according to some rules
– List: holds the elements in the way they were inserted
– Set: cannot have duplicate elements
– Queue: holds the elements in the order of a queuing discipline

Map: a group of key-value object pairs
– Look up an object using another object (principle of dictionary)

These interfaces allow you to hold your objects
without caring about the exact implementation

NMCGJ
2020-2021
Strings and Arrays


Container classes
– Overview of basic interfaces

Collection: a sequence of elements according to some rules
– List: holds the elements in the way they were inserted
– Set: cannot have duplicate elements
– Queue: holds the elements in the order of a queuing discipline

Map: a group of key-value object pairs
– Look up an object using another object (principle of dictionary)

These interfaces allow you to hold your objects
without caring about the exact implementation

NMCGJ
2020-2021
Strings and Arrays


Container classes
– Implementations of the interface List

ArrayList: extends the classical array generics: specify type of
– Fast random access to elements objects to be held in List
– Expensive insertion / deletion of elements in the middle between angle brackets

LinkedList (since Java SE5)
– Optimal sequential access, but slow random access
– Inexpensive insertion / deletion of elements in the middle
– Syntax of List creation
List<Apple> apples = new ArrayList<Apple>();
List<Orange> oranges = new LinkedList<Orange>();
NMCGJ
2020-2021
Strings and Arrays


Container classes
– Some useful List methods

<integer> = <list> . size () ;


<object> = <list> . get (<integer>) ;
<integer> = <list> . indexOf (<object>) ;
<boolean> = <list> . add (<object>) ;
<list> . add (<integer>, <object>) ;
<object> = <list> . set (<integer>, <object>) ;
<object> = <list> . remove (<integer>) ;
<boolean> = <list> . remove (<object>) ;
<list> . clear () ;
<list> = <list> . subList (<integer>, <integer>) ;
NMCGJ
2020-2021
Strings and Arrays


Container classes
– Example: iterating over a List (using for loop)

class Apple {}
get() is fast for ArrayList
class Gala extends Apple {}
class Fuji extends Apple {} but slow for LinkedList

ArrayList<Apple> apples = new ArrayList<Apple>();


[Link](new Gala());
[Link](new Fuji());
for (int i = 0; i < [Link](); i++) {
Apple apple = [Link](i);
[Link]([Link]());
}

NMCGJ
2020-2021
Strings and Arrays


Container classes
– The interface Iterator is designed for

moving efficiently through a sequence (Collection), and

selecting each object in the sequence without knowing its structure
– Implementation depends on the specific container
– Some useful Iterator methods

<iterator> = <collection> . iterator () ;


<listiterator> = <list> . listIterator () ;

<object> = <iterator> . next () ;


<boolean> = <iterator> . hasNext () ;
NMCGJ
2020-2021
Strings and Arrays


Container classes
– Example: iterating over a List (using an Iterator)

Iterator<Apple> iter = [Link]();


while ([Link]()) {
Apple apple = [Link]();
a foreach loop works
[Link]([Link]());
} with any Iterable object
(generates an Iterator)

– Example: iterating over a List (using foreach loop)

for (Apple apple : apples)


[Link]([Link]());

NMCGJ
2020-2021
Strings and Arrays


Container classes: overview
Collection Map

List Queue Set TreeMap HashMap

ArrayList LinkedList TreeSet HashSet LinkedHashMap

PriorityQueue LinkedHashSet
NMCGJ
2020-2021

You might also like