You are on page 1of 72

Arrays

A way to organize data

1
What are Arrays?
 An array is a series of compartments to
store data.

 Each compartment is appropriately sized for


the particular data type the array is declared
to store.

 An array can hold only one type of data!


E.g. int[] can hold only integers
char[] can hold only characters
2
Array Visualization

Specifies an array of
variables of type int
We are creating
a new array object

int[] primes = new int[10]; // An array of 10 integers

The name of The array object is of


the array type int
and has ten elements index values

primes[0] primes[1] primes[2] primes[3] primes[4] primes[9]

3
Declaring an Array Variable

 Array declarations use square brackets.


datatype[] label;

 For example:
int[] prices;
String[] names;

4
Creating a New "Empty" Array
Use this syntax: new int[20]
 The new keyword creates an array of type
int that has 20 compartments
 The new array can then be assigned to an
array variable:
int[] prices = new int[20];
 When first created as above, the items in the
array are initialized to the zero value of the
datatype
int: 0 double: 0.0 String: null 5
Array Indexes

 Every compartment in an array is assigned an


integer reference.

 This number is called the index of the


compartment

 Important: In Java (and most other languages),


the index starts from 0 and ends at n-1, where
n is the size of the array
6
Accessing Array Elements

 To access an item in an array, type


the name of the array followed by
the item’s index in square brackets.

 For example, the expression:


names[0]
will return the first element in the
names array
7
Filling an Array

 Assign values to compartments:

prices[0] = 6;
prices[1] = 80;
prices[2] = 10;

8
Constructing Arrays

 To construct an array, you can declare a


new empty array and then assign values
to each of the compartments:

String[] names = new String[5];


names[0] = "Dawit";
names[1] = "Elsa";
names[2] = "Abebe";
names[3] = "Jamal";
names[4] = "Ashenafi";
9
Another Way to Construct Arrays
 You can also specify all of the items in an
array at its creation.
 Use curly brackets to surround the array’s
data and separate the values with commas:
String[] names = { "Dawit", "Abebe",
"Elsa", "Jamal", "Ashenafi"};
 Note that all the items must be of the same
type. Here they are of type String.
 Another example:
int[] powers = {0, 1, 10, 100}; 10
Length of array
String[] names = {
"Dawit", "Abebe", “Elsa",
"Jamal", "Ashenafi" };
int numberOfNames = names.length;
System.out.println(numberOfNames);

Output: 5

 Important: Arrays are always of the


same size: their lengths cannot be
changed once they are created! 11
Example
String[] names = {
"Mulatu", "Tamirat", "Bekele", "Mesfin",
"Meron"};
for(int i = 0; i < names.length; i++){
System.out.println("Hello " + names[i] + ".");
}

Output:
Hello Mulatu.
Hello Tamirat.
Hello Bekele.
Hello Mesfin.
Hello Meron.
12
Modifying Array Elements
 Example:
names[0] = "Bekele";
 Now the first name in names[0] has been
changed from "Mulatu" to "Bekele".
 So the expression names[0] now evaluates to
"Bekele".
 Note: The values of compartments can change,
but no new compartments may be added. 13
Example

int[] fibs = new int[10];


fibs[0] = 1;
fibs[1] = 1;
for(int i = 2; i < fibs.length; i++) {
fibs[i] = fibs[i-2] + fibs[i-1];
}
Note: array indexes can be expressions

 After running this code, the array fibs[]


contains the first ten Fibonacci numbers:
1 1 2 3 5 8 13 21 34 55
14
Exercise 1
 Which of the following sequences of
statements does not create a new array?

a. int[] arr = new int[4];

b. int[] arr;
arr = new int[4];

c. int[] arr = { 1, 2, 3, 4};

d. int[] arr; just declares an array variable


15
Exercise 2
 Given this code fragment,
int[] data = new int[10];
System.out.println(data[j]);

 Which of the following is a legal value of j?


a. -1 // out of range
b. 0 // legal value
c. 3.5 // out of range
d. 10 // out of range
16
Exercise 3
 Which set of data would not be
suitable for storing in an array?

a. your name, date of birth, and score


on your physics test // these are different types
b. temperature readings taken every
hour throughout a day
c. Student’s grade to calculate the avg
to give grade.
17
Exercise 4
 What is the value of c after the following
code segment?

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


int [] b = {11, 12, 13};
int [] c = new int[4];
for (int j = 0; j < 3; j++) {
c[j] = a[j] + b[j];
}
c = [12, 14, 16, 0] 18
2-Dimensional Arrays

 The arrays we've used so far can be 0 1


thought of as a single row of values.
0 8 4
 A 2-dimensional array can be thought
1 9 7
of as a grid (or matrix) of values
2 3 6
 Each element of the 2-D array is
accessed by providing two indexes: value at row index 2,
column index 0 is 3
a row index and a column index

 (A 2-D array is actually just an array of arrays)


19
2-D Array Example
 Example:
A landscape grid of a 20 x 55 square km piece of land:
We want to store the height of the land at each
row and each column of the grid.

 We declare a 2D array two sets of square brackets:


double[][] heights = new double[20][55];

 This 2D array has 20 rows and 55 columns

 To access the grid at row index 11 and column index 23


user: heights[11][23] 20
Exceptions

Handling Errors with Exceptions

21
Attack of the Exception
public static int average(int[] a) {
int total = 0;
for(int i = 0; i < a.length; i++) {
total += a[i];
}
return total / a.length;
}
 What happens when this method is used to
take the average of an array of length zero?
 Program throws an Exception and fails
22
java.lang.ArithmeticException: / by zero
What is an Exception?

 An error event that disrupts the program


flow and may cause a program to fail.

 Some examples:
 Performing illegal arithmetic
 Illegal arguments to methods
 Accessing an out-of-bounds array element
 Hardware failures
23
Another Exception Example
 What is the output of this program?
public class ExceptionExample {
public static void main(String args[]) {
String[] greek = {"Alpha", "Beta"};
System.out.println(greek[2]);
}
}
Output:
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 2
at ExceptionExample.main(ExceptionExample.java:4)
24
Exception Message Details
Exception message format:
[exception class]: [additional description of exception]
at [class].[method]([file]:[line number])

Example:
java.lang.ArrayIndexOutOfBoundsException: 2
at ExceptionExample.main(ExceptionExample.java:4)

 What exception class? ArrayIndexOutOfBoundsException


 Which array index is out of bounds? 2
 What method throws the exception? main
 What file contains the method? ExceptionExample.java
25
 What line of the file throws the exception? 4
Exception Handling
 Use a try-catch block to handle
exceptions that are thrown

try {
// code that might throw exception
}
catch ([Type of Exception] e) {
// what to do if exception is thrown
}
26
Exception Handling Example
public static int average(int[] a) {
int total = 0;
for(int i = 0; i < a.length; i++) {
total += a[i];
}
return total / a.length;
}

public static void printAverage(int[] a) {


try {
int avg = average(a);
System.out.println("the average is: " + avg);
}
catch (ArithmeticException e) {
System.out.println("error calculating average");
27
} }
Unhandled exception

class DivByZero{
public static void main(String args[]){
System.out.println(3/0);
System.out.println(“please print me”);
}
}

Output
C:\java>javac DivByZero.java
C:\java>java DivByZero
Exception in thread “main”
java.lang.ArithmeticException:/by zero at
DivByZero.main(DivByZero.java:3) 28
Handling this exception during execution

class Exc{
public static void main(String[] args){
int d,a;
try {//monitor a block of code
d=0;
a=42/d;
System.out.println(“This will not be printed.”);
}
catch(ArithmeticException e){//catch divided by 0 error
System.out.println(“division by zero”);
}
output: division by zero
29
Catching Multiple Exceptions
 Handle multiple possible exceptions by
multiple successive catch blocks
try {
// code that might throw multiple exception
}
catch (IOException e) {
// handle IOException and all subclasses
}
catch (ClassNotFoundException e2) {
// handle ClassNotFoundException
30
}
Illustrating multiple catch block
class MultiCatch
{
public static void main(String[] args)
{
try {
int y=Integer.parseInt(args[0]);
int a=args.length;
System.out.println(“a=“+a);
int b=42/a;
int c[]={1};
C[42]=99;
}
31
Illustrating multiple catch block…

catch(ArithmeticException e)
{
System.out.println(“divide by 0:”);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Array index oob:”);
}
}
}
32
Exceptions Terminology

 When an exception happens we


say it was thrown or raised

 When an exception is dealt with,


we say the exception is handled or
caught
33
Unchecked Exceptions
 All the exceptions we've seen so far
have been Unchecked Exceptions, or
Runtime Exceptions
 Usually occur because of programming
errors,
 when code is not robust enough to prevent
them
 They are numerous and can be ignored
by the programmer 34
Common Unchecked
Exceptions
 NullPointerException
reference is null and should not be
 IllegalArgumentException
method argument is improper in some way
 ArrayIndexOutOfBoundsException
 ArithmeticException
 UnknownHostException
 IOException 35
Checked Exceptions
 There are also Checked Exceptions

 Usually occur because of errors


programmer cannot control:
examples: hardware failures, unreadable files

 They are less frequent and they cannot


be ignored by the programmer . . .
36
Dealing With Checked
Exceptions
 Every method must catch (handle) checked
exceptions or specify that it may throw them
 Specify with the throws keyword
void readFile(String filename) {
try {
FileReader reader = new FileReader("myfile.txt");
// read from file . . .
} catch (FileNotFoundException e) {
System.out.println("file was not found");
}
} or
void readFile(String filename) throws FileNotFoundException {
FileReader reader = new FileReader("myfile.txt");
// read from file . . .
}
Exception Class Hierarchy
 All exceptions are instances of classes
that are subclasses of Exception
Exception

RuntimeException IOException SQLException

ArrayIndexOutofBounds FileNotFoundException

NullPointerException MalformedURLException

IllegalArgumentException SocketException

etc. etc.

38
Unchecked Exceptions Checked Exceptions
Checked and Unchecked Exceptions

Checked Exception Unchecked Exception


not subclass of subclass of
RuntimeException RuntimeException
if not caught, method must if not caught, method may
specify it to be thrown specify it to be thrown
for errors that the for errors that the
programmer cannot directly programmer can directly
prevent from occurring prevent from occurring,
IOException, NullPointerException,
FileNotFoundException, IllegalArgumentException,
SocketException IllegalStateException 39
Socket programming using
java networking

40
Outline

 Socket programming using TCP

 Secret key Exchange using DIFFIE–


HELLMAN algorithm (Security using
public key cryptography)

41
Processes communication
Process: program running
within a host.
 within same host, two Client process: process
processes communicate that initiates
using inter-process communication
communication (defined Server process: process
by OS). that waits to be
 processes in different contacted
hosts communicate by
exchanging messages

42
Sockets
host or host or
 process sends/receives client server
messages to/from its
socket controlled by
app developer
process process
 socket analogous to door
 sending process gives socket socket

message out door TCP with TCP with


buffers, Internet buffers,
 sending process relies on variables variables
transport infrastructure on
other side of door which
controlled
brings message to socket by OS
at receiving process

43
Socket Addresses
 a transport-layer protocol needs
 process-to-process a pair of socket addresses:
delivery needs two
 the client socket address and
addresses:
 the server socket address
 IP address and
 port number at
each end
 the IP header contains the IP
address; the UDP or TCP header
contains the port number
 the combination of an
IP address and a port
number is called a
socket address

44
some of the well-known ports used by TCP
Port Protocol Description
7 Echo Echoes a received datagram back to the sender
9 Discard Discards any datagram that is received
11 Users Active users
13 Daytime Returns the date and the time
17 Quote Returns a quote of the day
19 Chargen Returns a string of characters
20 FTP, Data File Transfer Protocol (data connection)
21 FTP, Control File Transfer Protocol (control connection)
23 TELNET Terminal Network
25 SMTP Simple Mail Transfer Protocol
53 DNS Domain Name Server
67 BOOTP Bootstrap Protocol
79 Finger Lookup information about a user
80 HTTP Hypertext Transfer Protocol
111 45 RPC Remote Procedure Call
Addressing processes
 identifier includes both IP
 to receive messages,
address and port
process must have
numbers associated with
identifier
process on host.
 host device has unique
 Example port numbers:
32-bit IP address
 HTTP server: 80
 Q: does IP address of  Mail server: 25
host on which process
runs suffice for
 to send HTTP message
identifying the process? to a web server with IP
 A: No, many
address:217.110.45.12,
we use:
processes can be
running on same host
 217.110.45.12:80
46
Socket programming
Goal: learn how to build client/server application that communicate
using sockets

Socket API socket


 introduced in BSD4.1 UNIX,
a host-local,
1981
application-created,
 explicitly created, used, OS-controlled interface
released by apps (a “door”) into which
 client/server paradigm application process can
 two types of transport service both send and
via socket API: receive messages to/from
 reliable, byte stream- another application
oriented TCP process
 unreliable datagram UDP
47
Socket-programming with TCP
Socket: a door between application process and end-end-
transport protocol (TCP or UDP)
TCP service: reliable transfer of bytes from one process
to another

controlled by
controlled by process application
application process
developer
developer socket socket
controlled by TCP with TCP with controlled by
buffers, operating
operating buffers, internet system
system variables variables

host or host or
server server
48
Socket programming with TCP
Client must contact server
 server process must first be running
 server must create socket (door) that welcomes client’s contact
Client contacts server by:
 creating client-local TCP socket
 specifying IP address, port number of server process
 When client creates socket: client TCP establishes connection to
server TCP
 When contacted by client, server TCP creates new socket for
server process to communicate with client
 allows server to talk with multiple clients
 source port numbers used to distinguish clients

49
Client/server socket interaction: TCP
Server Client
(running on hostid)
create socket,
port=x, for
incoming request:
ServerSocket servSock =new
ServerSocket(x)

TCP create socket,


wait for incoming
connection request connection setup connect to hostid, port=x
Socket link = Socket clientSocket = new
servSock.accept() Socket(h,x)

send request using


read request from clientSocket
servSock

write reply to
servSock read reply from
clientSocket
close
servSock
close
50
clientSocket
Stream terminology
keyboard monitor

 A stream is a sequence of

inFromUser
input
characters that flow into or stream

out of a process. Client


Process
 An input stream is attached process
to some input source for
the process, e.g., keyboard
or socket.
 An output stream is

inFromServer
outToServer
output input
stream stream
attached to an output
source, e.g., monitor or
socket. client TCP
clientSocket
socket TCP
socket

to network from network

51
Socket programming with TCP: Example

Client side behavior Server side behavior

 The client program presents  The server program


a simple command prompts
presents a simple user
for text input.
interface.
 When you enter the
message, the text will be
sent to the server program.  When message sent from
the client received, it
 The client program expects displays on its output screen
an echo from the server and that message is received.
prints the echo it receives on
 it send the message back to
its standard output.
the client.
52
Compile and Run
 To run the example programs, start the server
program first.
 If you do not, the client program cannot establish
the socket connection.
 Here are the compiler and interpreter commands to
compile and run the example.
- javac Server.java
- java Server in one command prompt
- javac Client.java in another command pro
- java Client
53
Server-Socket programming
 The java.net package provides
ServerSocket and DatagramSocket
objects for servers at the TCP/IP socket
level.

Establishing a stream server involves five steps:


1- Create a new Socket with port number.
2- Set a Socket connect for a client using the accept()
method.
3- Create inputstream and outputstream objects.
4- Process stream data.
5- Close the streams. 54
Server-Socket programming
cont’d…
 The server program establishes a socket
connection on Port 1234 in its listenSocket
method.
 It reads data sent to it and sends that same
data back to the client in its listenSocket
method.

ListenSocket Method
 The listenSocket method creates a
ServerSocket object with port number on
which the server program is going to listen
for client communications.
55
Server-Socket Programming cont’d…
 The port number must be an available port, which
means the number cannot be reserved or already in use.
 For example, Unix systems reserve ports 1 through 1023
for administrative functions leaving port numbers greater
than 1024 available for use.
public static void listenSocket(){
try {
ServerSocket servSock = new ServerSocket(1234);
}
catch(IOException e){
System.out.println("Unable to create port!");
System.exit(-1);
}

56
Server-Socket Programming
cont’d…
 Next, the listenSocket method creates a Socket
connection for the requesting client.

 This code executes when a client starts up and requests


the connection on the host and port where this server
program is running.

 When the connection successfully established, the


servSock.accept() method returns a new Socket
object.

57
Server-Socket Programming
cont’d…

Socket link=null;
try
{
link = servSock.accept();
}
catch(IOException e)
{
System.out.println("Accept failed: 1234");
}

58
Server-Socket Programming cont’d…

 Then, the listenSocket method creates a BufferedReader


object to read the data sent over the socket connection
from the client program.
 It also creates a PrintWriter object to send the data
received back to the client.

BufferedReader in = new BufferedReader(new


InputStreamReader(link.getInputStream()));

PrintWriter out = new


PrintWriter(link.getOutputStream(), true);

59
Server-Socket Programming cont’d…

 Lastly, the listenSocket method loops on the input stream


to read data as it comes in from the client and writes to the
output stream to send the data back.

int numMessages = 0;
String message = in.readLine();
while (!message.equals("close")) {
System.out.println("Message received.");
numMessages++;
out.println("Message " + numMessages + ": " +
message);
message = in.readLine();
}

60
Lab: Server -Socket source code

import java.io.*;
import java.net.*;
public class Server {
private static ServerSocket servSock;
private static final int PORT=1234;
public static void main(String[] args)
throws IOException {
System.out.println("Openning port.....");
while(true)
{
listenSocket();
}
}
61
Lab: Server-Socket source code cont’d…
public static void listenSocket() {

Create try {
server socket servSock=new ServerSocket(PORT);
at port 1234
} catch(IOException e) {
System.out.println("Unable to create
socket with port no:1234!");
System.exit(-1); }
Socket link=null;
try {
Create socket
connection link=servSock.accept();
with the client } catch(IOException e){
System.out.println("Accept failed:
Port 1234");
}
62
Lab: Server-Socket source code cont’d…

try {
BufferedReader in=new
Create input BufferedReader(new
stream, attached InputStreamReader(link.getInputStrea
to socket m()));

Create output PrintWriter out=new


stream, attached PrintWriter(link.getOutputStream(),t
to socket rue);
int numMessages=0;
Read in line
from socket String message=in.readLine();
while(!message.equals("close")) {
System.out.println("Message
recieved.");
numMessages ++;
63
Lab: Server-Socket source code cont’d…

Write out line out.println("Message" +


to socket numMessages+ ":" + message);
message=in.readLine();
}
}

catch(IOException e)
{
System.out.println("Message is
not recieved");
End of while loop,
loop back and wait for }
another client connection }
}
64
Client-Socket Programming

 Establishing a stream client involves four


steps:

1- Create a new Socket with a server IP address and


port number.
2- Create input stream and output stream objects.
3- Process stream data and
4- Close the streams.

65
Client-Socket Programming
cont’d…
 The client program establishes a connection to the
server program on a particular host and port
number in its listenSocket method, and

 It then sends data entered by the end user to the


server program.

 The listenSocket method also receives the data


back from the server and prints it to the command
line.

66
Client-Socket Programming cont’d…
listenSocket Method
 The listenSocket method first creates a Socket object
with the IP address (“local host”) and port number (1234)
where the server program is listening for client
connection requests.
Socket link= new Socket(host,PORT);
• It then provide a place where the data shall be stored by
creating BufferedReader object to read the streams sent
by the server back to the client.
BufferedReader in=new BufferedReader(
new
InputStreamReader(link.getInputStream()));

67
Client-Socket Programming cont’d…

 Next, it creates a PrintWriter object to send data over


the socket connection to the server program.
PrintWriter out=
New
PrintWriter(link.getOutputStream(),true);

 It also creates a BufferedReader object Set up stream


for keyboard entry...

BufferedReader userentry=new BufferedReader(


new InputStreamReader(System.in));
68
Client-Socket Programming cont’d…
 This listenSocket method code gets the input streams
and passes it to the PrintWriter object, which then sends
it over the socket connection to the server program.
 Lastly, it receives the input text sent back to it by the
server and prints the streams out.
String message, response;
do {
System.out.print("Enter message:");
message=userentry.readLine();
out.println(message);
response=in.readLine();
System.out.println("\nSERVER>" + response);
} while(!message.equals("close"));

69
Lab: Client-Socket Programming
import java.io.*;
import java.net.*;
public class Client {
private static InetAddress host;
private static final int PORT=1234;
public static void main(String[] args) throws
IOException {
Server is
try {
local host=InetAddress.getLocalHost();
}
catch(UnknownHostException e)
{
System.out.println("Host id not found!");
System.exit(-1);
}
listenSocket();
}

70
Lab: Client-Socket Programming
public static void listenSocket() {
Socket link=null;
Create try {
client socket, link=new Socket(host,PORT);}
connect to server catch(IOException e){
System.out.println("Unable to connect");
System.exit(-1);}
Create try {
input stream BufferedReader in=new BufferedReader(new
attached to socket InputStreamReader(link.getInputStream())
);
Create PrintWriter out=new
PrintWriter(link.getOutputStream(),true)
output stream
;
attached to socket

Create BufferedReader userentry=new


BufferedReader(new
input stream
InputStreamReader(System.in));
for user entry
String message, response; 71
Client-Socket Programming cont’d…
do {
System.out.print("Enter message:");
message=userentry.readLine();
out.println(message);
response=in.readLine();
System.out.println("\nSERVER>" +
response);
} while(!message.equals("close"));
}
catch(IOException e)
{
System.out.println("Message is not
sent.");
}
}
}
72

You might also like