Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 80

1

FORMATION JAVA OCA


SABER BHAR

Programming Fundamentals using Java


Java - Saber BHAR 1
2

Core Java APIs

Java - Saber BHAR 2


3

Arrays
 Objects in Java (but not in C/C++).

 An array is a container object that holds a fixed


number of values of a single type.

 An array is an area of memory on the heap with


space for a designated number of elements.

 Specify length when creating.


Java - Saber BHAR 3
4

Arrays

Java - Saber BHAR 4


5

Arrays
Example:
int array of length 5.

Declaration:
int[] array1;

Initialization:
array1 = new int[5];

Java - Saber BHAR 5


6

Arrays
Length provided can be an int variable.

Example:

int x = 6;
array1 = new int[x];

Java - Saber BHAR 6


7

Arrays
Two ways to declare:

int[] array1; // convention

int array1[]; // discouraged!

Java - Saber BHAR 7


8

Arrays
Declare and initialize with some values:

int[] array1 = {5, 100, 200, 45};

Length = no. of elements between the braces.

 Property “length”.

 Very useful! Especially for traversing


Java - Saber BHAR 8
9

Arrays
 Example: Printing out all the values of an array

 for (int i = 0; i < array1.length; i++) {


System.out.println(array1[i]);
}

Java - Saber BHAR 9


10

Arrays
 Another way of traversing:

for-each loop:

 for (int i : array1) {


System.out.println(i);
}

For each element i in array1 do…

Java - Saber BHAR 10


11

Arrays
 What happens here?

System.out.println(array1[array1.length]);

Java - Saber BHAR 11


12

Arrays
 ArrayIndexOutOfBoundsException thrown

 Will later look at how to handle these exceptions.

 Be careful about boundaries!

Java - Saber BHAR 12


13

Passing Arrays to Methods


public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
}

int[] array1 = {5, 100, 200, 45};

printArray( array1 );

Java - Saber BHAR 13


14

Passing Arguments to Methods


 Two ways:
 Pass-by-Value:
Used for primitive types (int/char/float/etc.)
Changing value in the method does not change the
original variable

Pass-by-reference:
Used for objects (such as arrays). Changing in the
method changes the original!

Java - Saber BHAR 14


15

Pass-by-value
public void changeValue(float y) {
y = 3.4;
}

float y = 5.4;
changeValue(y);
System.out.println(y);

What is the output?

Java - Saber BHAR 15


16

Pass-by-reference
public void changeValue(float[] y) {
y[y.length - 1] = 3.4;
}

float[] y = {5.4, 10.4, 1.2};


changeValue(y);
System.out.println(y[1]);

What is the output?

Java - Saber BHAR 16


17

Pass-by-reference

y = {5.4, 10.4, 3.4};

After calling the method

Java - Saber BHAR 17


18

public void changeValue(float y) {


y = 3.4;
}

float[] y = {5.4, 10.4, 1.2};


changeValue(y[0]);
System.out.println(y[0]);

What is the output?

Java - Saber BHAR 18


19

Passing Arguments to Methods


 So be careful when passing objects/arrays to
methods.

Java - Saber BHAR 19


20

Copying arrays
 public static void arraycopy(Object src,
int srcPos,
Object dest,
int destPos,
int length)

 Provided in the System class

System.arrayCopy(…)

Java - Saber BHAR 20


21

Copying arrays
Example:

char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i',
'n', 'a', 't', 'e', 'd'};
char[] copyTo = new char[7];
System.arraycopy(copyFrom, 2, copyTo, 0, 7);

System.out.println(copyTo);

What is the output?

Java - Saber BHAR 21


22

Copying arrays
Output: caffein

char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i',
'n', 'a', 't', 'e', 'd'};

Java - Saber BHAR 22


23

Multi-dimensional Arrays
 Looked at 1-dimensional (1-D) arrays so far.

 Multi-dimensional arrays:
 Array of arrays!

 Used for multi-dimensional data

Java - Saber BHAR 23


24

Multi-dimensional Arrays
 Examples:
 Storing all student info in a 2-D array
 Matrices
 Storing 3D data such as points/vertices (x, y, z)

Java - Saber BHAR 24


25

Multi-dimensional Arrays
 Declaration (2-D arrays):

elementType[][] variableName;

 Example:

float[][] matrix;

Java - Saber BHAR 25


26

Multi-dimensional Arrays
 Initialization:
matrix = new float[2][3];

 2 rows, 3 columns

int[][] differentSize =
{{1, 4}, {3}, {9,8,7}};

Java - Saber BHAR 26


27

Multi-dimensional Arrays
 Declare and initialize with some values:

float[][] matrix = { {2.3, 50.1, 5.5},


{9.8, 4.0, 11.4} };

Creates 2 arrays with length 3;

Java - Saber BHAR 27


28

Multi-dimensional Arrays
 Each row can have a different length

float[][] matrix = { {2.3, 50.1, 5.5},


{9.8, 4.0} };

 First row = length 3


 Second row = length 2

Java - Saber BHAR 28


29

Multi-dimensional Arrays
float[][] matrix = new float[2][];

 Specifies size of the array - 2

 But not the size of the array in each row – do it


individually

matrix[0] = new float[3];


matrix[1] = new float[1];

Java - Saber BHAR 29


30

Multi-dimensional Arrays
 Traversal:

for(int row = 0; row < matrix.length; row++) {


for (int column = 0; column < matrix[row].length; column++) {
System.out.println(matrix[row][column]);
}
}

Java - Saber BHAR 30


31

Multi-dimensional Arrays
 Traversal – Enhanced Loop:

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


for (int[] inner : twoD) {
for (int num : inner)
System.out.print(num + " ");
System.out.println();
}

Java - Saber BHAR 31


32

Array with Reference Variables


 You can choose any Java type to be the type of the
array.
 int is a primitive; int[] is an object.
 We can call equals() because an array is an object.
 Since Java 5, Java has provided a method that prints
an array nicely:

java.util.Arrays.toString(bugs) would print


[cricket, beetle, ladybug]

System.out.println(bugs.toString());
//[Ljava.lang.String;@160bc7c0
Java - Saber BHAR 32
33

Array with Reference Variables


 You wanted to force a bigger type into a smaller
type
3: String[] strings = { "stringValue" }; //fine
4: Object[] objects = strings; //OK
5: String[] againStrings = (String[]) objects; //OK
6: againStrings[0] = new StringBuilder(); // DOES NOT
COMPILE
7: objects[0] = new StringBuilder(); // careful!

 At line 7, at runtime, the code throws an


Exception. Why?
Java - Saber BHAR 33
34

Array with Reference Variables


 From the point of view of the compiler, this is just
fine.
 A StringBuilder object can clearly go in an Object[].
 The problem is that we don’t actually have an
Object[].
 We have a String[] referred to from an Object[]
variable.
 At runtime, the code throws an ArrayStoreException.

Java - Saber BHAR 34


35

ArrayIndexOutOfBoundsException
numbers[10] = 3;
numbers[numbers.length] = 5;
for (int i = 0; i <= numbers.length; i++)
numbers[i] = i + 5;

 The length is always one more than the maximum


valid index.
 Finally, the for loop incorrectly uses <= instead of
<, which is also a way of referring to that 10th
element.
Java - Saber BHAR 35
36

Sorting
 You can pass almost any array to Arrays.sort().
 import java.util.* // import whole package
 import java.util.Arrays; // import just Arrays

String[] strings = { "10", "9", "100" };


Arrays.sort(strings);
for (String string : strings)
System.out.print(string + " ");

int[] numbers = { 6, 9, 1 };
Arrays.sort(numbers);
for (int i = 0; i < numbers.length; i++)
System.out.print (numbers[i] +
Java - Saber BHAR " "); 36
37

Searching
 Java also provides a convenient way to search—
but only if the array is already sorted.

Java - Saber BHAR 37


38

Searching
3: int[] numbers = {2,4,6,8};
4: System.out.println(Arrays.binarySearch(numbers, 2)); // 0
5: System.out.println(Arrays.binarySearch(numbers, 4)); // 1
6: System.out.println(Arrays.binarySearch(numbers, 1)); // -1
7: System.out.println(Arrays.binarySearch(numbers, 3)); // -2
8: System.out.println(Arrays.binarySearch(numbers, 9)); // -5

 3 isn't in the list, it would need to be inserted at element 1


to preserve the sorted order. We negate and subtract 1 for
consistency, getting –1 –1, also known as – 2.
 line 8 wants to tell us that 9 should be inserted at index 4.
We again negate and subtract 1, getting –4 –1, also known
as –5
Java - Saber BHAR 38
39

Working with Strings

Java - Saber BHAR 39


40

The String class


 Array of characters in many languages (C/C++ for
ex.)

 But: Strings are objects in Java

 Strings are widely used – so should know how to


use them.

Java - Saber BHAR 40


41

The String class


 Creating Strings:

String string1 = new String(“this is a string”);

String string2 = “this is a string”;


// slight difference in the 2nd one

 String from a character array:

char[] charArray = {‘s’, ‘t’, ‘r’, ‘i’, ‘n’, ‘g’};


String string3 = new String(charArray);
Java - Saber BHAR 41
42

The String class


 Strings are immutable – Not changeable!

 Once a String object is created, it is not allowed to


change. It cannot be made larger or smaller, one
of the characters inside it. and you cannot change

 Mutable is another word for changeable.


Immutable is the opposite - an object that can't be
changed once it's created.

Java - Saber BHAR 42


43

The String class


 Strings are immutable – Not changeable!

 So what happens here?:

String s = “Java”;
s = “Another String”;

Java - Saber BHAR 43


44

The String class


 Initially:

s Java

 Now:
s Java

Another String

Java - Saber BHAR 44


45

The String class


 A new object “Another String” is created

 Reference s now points to it

 No reference to “Java”, so garbage collection


cleans it up

Java - Saber BHAR 45


46

String comparisons
 Interned instances of the same string

 Example:
String s1 = “Java”;
String s2 = new String(“Java”);

String s3 = “Java”;

Java - Saber BHAR 46


47

String comparisons

In Memory:

s1
Java

s2
Java

Java - Saber BHAR 47


48

String comparisons

In Memory:

s1
Java
s3

s2
Java

Java - Saber BHAR 48


49

String comparisons
 s1 == s2 is ? (different reference)

Java - Saber BHAR 49


50

String comparisons
 s1 == s2 is false (different reference)

Java - Saber BHAR 50


51

String comparisons
 s1 == s2 is false (different reference)

 s1 == s3 is ? (same reference)

Java - Saber BHAR 51


52

String comparisons
 s1 == s2 is false (different reference)

 s1 == s3 is true (same reference)

Java - Saber BHAR 52


53

String comparisons
 Don’t use “==“ for comparing objects!
 Compares references

Java - Saber BHAR 53


54

String comparisons
 Don’t use “==“ for comparing objects!
 Compares references


string1.equals(string2) for content comparison
 s1.equals(s2) is true

Java - Saber BHAR 54


55

String comparisons
 Don’t use “==“ for comparing objects!
 Compares references


string1.equals(string2) for content comparison
 s1.equals(s2) is true

 Define equals() method individually for every class –


will look at it later
 equalsIgnoreCase() will convert the characters' case
if needed before comparing.
Java - Saber BHAR 55
56

The String class


 Some useful String methods:
 .length() – returns the length

 .charAt(int index) – returns char at that index

 .split(String regex) – Splits string according to a regular


expression

 indexOf() - looks at the characters in the string and finds the first
index that matches the desired value.

 trim() The trim() method removes whitespace from the beginning


and end of a String.
Java - Saber BHAR 56
57

The String class


 Some useful String methods:
 substring() - looks for characters in a string. It returns
parts of the string. The first parameter is the index to start
with for the returned string. As usual, this is a zero-based
index.
 toLowerCase() and toUpperCase() After that mental

exercise, it is nice to have methods that do exactly what


they sound like!
 contains() - looks for matches in the String.

 replace() - simple search and replace.

 startsWith() and endsWith() - look at whether the

provided value matches part of the String.


Java - Saber BHAR 57
58

Input
public static void main(String[] args) {
...
}

Java - Saber BHAR 58


59

Input
public static void main(String[] args) {
...
}

String[] args = array of arguments to the


program

Java - Saber BHAR 59


60

Input
public static void main(String[] args) {
...
}

String[] args = array of arguments to the


program

Executing a program:
java programName arg1 arg2 arg3 ...

Java - Saber BHAR 60


61

Convert from String


 Input are Strings

 Need to convert to int, double, etc...

 Use Wrapper classes to convert

 Primitives have wrapper classes:


 Integer for int, Double for double, etc.

Java - Saber BHAR 61


62

Convert from String


 java programName 2 6.5 “testing java”

int firstArgument = Integer.parseInt(args[0]);

double secArgument = Double.parseDouble(args[1]);

String thirdArgument = args[2]; // “testing java”

Java - Saber BHAR 62


63

Varargs
 Here are three examples with a main() method

public static void main(String[] args)


public static void main(String args[])
public static void main(String... args) //
varargs

 The third example uses a syntax called varargs


(variable arguments)

Java - Saber BHAR 63


64

String Concatenation
 Note the + operator can be used in two ways within the same line
of code. 3 rules :
 If both operands are numeric, + means numeric addition.
 If either operand is a String, + means concatenation.
 The expression is evaluated left to right.
System.out.println(1 + 2) //3
System.out.println(“a” + ”b”) //ab
System.out.println(“a” + ”b” + 3) //ab3
System.out.println(1 + 2 + ”c”) //3c
 Remember what + = does. s + = "2" means the same thing as s = s +
“2".
Java - Saber BHAR 64
65

The String Pool


 Since strings are everywhere in Java, they use up a
lot of memory. In some production applications,
they can use up 25– 40 % of the memory in the
entire program.
 Java realizes that many strings repeat in the
program and solves this issue by reusing common
ones.
 The string pool, also known as the intern pool, is a
location in the Java virtual machine (JVM) that
collects all these strings.
Java - Saber BHAR 65
66

The String Pool

String s1 = “Java”;
String s2 = new String(“Java”);

 The former says to use the string pool normally.


 The second says “No, JVM. I really don't want you
to use the string pool. Please create a new object
for me even though it is less efficient.”

Java - Saber BHAR 66


67

Using the StringBuilder Class


 This sequence of events continues, and after 26
iterations through the loop, a total of 27 objects
are instantiated, most of which are immediately
eligible for garbage collection.

String alpha = "";


for(char current = 'a'; current <= 'z'; current++)
alpha += current;
system.out.println(alpha);

Java - Saber BHAR 67


68

Using the StringBuilder Class


 This is very inefficient. The StringBuilder class
creates a String without storing all those interim
String values. Unlike the String class, StringBuilder
is not immutable.

StringBuilder alpha = new StringBuilder();


for(char current = 'a'; current <= 'z'; current++)
alpha.append(current);
System.out.println(alpha);

Java - Saber BHAR 68


69

Mutability and Chaining


 When we chained String method calls, the result
was a new String with the answer. Chaining
StringBuilder objects doesn't work this way.
Instead, the StringBuilder changes its own state
and returns a reference to itself!

StringBuilder sb = new StringBuilder("start");


sb.append("+middle"); // sb = "start+middle"
StringBuilder same = sb.append("+end");
// "start+middle+end"

Java - Saber BHAR 69


70

Mutability and Chaining


StringBuilder a = new StringBuilder("abc");
StringBuilder b = a.append("de");
b = b.append("f").append("g");
System.out.println("a=" + a);
System.out.println("b=" + b);

 Did you say both print "abcdefg"?


 Good. There's only one StringBuilder object here.

Java - Saber BHAR 70


71

Creating a StringBuilder
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder("animal");
StringBuilder sb3 = new StringBuilder(10);

 Size vs. Capacity


 Size is the number of characters currently in the
sequence, and capacity is the number of characters
the sequence can currently hold.
 Since a String is immutable, the size and capacity
are the same. The number of characters appearing
in the String is both the size and capacity.
Java - Saber BHAR 71
72

Important StringBuilder Methods


 charAt(), indexOf(), length(), and substring()
work exactly the same as in the String class.
 append() - adds the parameter to the StringBuilder and
returns a reference to the current StringBuilder.
 StringBuilder append( String str)

 There are more than 10 method signatures.

 insert() - adds characters to the StringBuilder at the


requested index and returns a reference to the current
StringBuilder.

Java - Saber BHAR 72


73

Important StringBuilder Methods


 delete() removes characters from the sequence
and returns a reference to the current
StringBuilder.
 deleteCharAt() method is convenient when you
want to delete only one character.

 reverse() reverses the characters in the


sequences and returns a reference to the current.
 toString() converts a StringBuilder into a String.
Java - Saber BHAR 73
74

StringBuilder vs. StringBuffer


 StringBuilder was added to Java in Java 5.
 If you come across older code, you will see
StringBuffer used for this purpose.
 StringBuffer does the same thing but more slowly
because it is thread safe.
 In theory, you don't need to know about
StringBuffer because it is less efficient.

Java - Saber BHAR 74


75

Understanding Equality
StringBuilder one = new StringBuilder();
StringBuilder two = new StringBuilder();
StringBuilder three = one.append("a");
System.out.println(one == two); // false
System.out.println(one == three); // true

String x = "Hello World";


String y = "Hello World";
System.out.println(x == y); // true

String x = "Hello World";


String z = " Hello World".trim();
System.out.println(x == z); // false

String y = new String("Hello World");


Java - Saber BHAR
System.out.println(x == y); // false 75
76

Understanding Equality
 Remember to never use == to compare Strings.
 equals to check the values inside the String rather
than the String itself.

String x = "Hello World";


String z = " Hello World".trim();
System.out.println(x.equals(z)); // true

 StringBuilder did not implement equals(). If you


call equals() on two StringBuilder instances, it will
check reference equality.
Java - Saber BHAR 76
77

Review Questions

Java - Saber BHAR 77


78

Question

Java - Saber BHAR 78


79

Question

Java - Saber BHAR 79


80

Question

Java - Saber BHAR 80

You might also like