Java API, Exceptions and IO

32
Java Class Libraries, Exceptions and IO Jussi Pohjolainen Tampere University of Applied Sciences

Transcript of Java API, Exceptions and IO

Page 1: Java API, Exceptions and IO

Java Class Libraries, Exceptions and IO

Jussi PohjolainenTampere University of Applied

Sciences

Page 2: Java API, Exceptions and IO

CLASS LIBRARIES

Page 3: Java API, Exceptions and IO

Class Libraries

• Programming would be very time consuming if everything would be implemented from the beginning.

• Class Libraries: premade classes that the programmer can use.

• Example: You don't implement GUI-elements by yourself, you use the given classes!

• You don't have to understand how the classes have been implemented. You have to understand how to use them!

Page 4: Java API, Exceptions and IO

Java Application Programming Interface

• Documentation available on the Internet– http://java.sun.com/javase/6/docs/api/

• The Java API is divided into– Packages• Contains classes or other packages

– Classes• Contains methods

– Methods

Page 5: Java API, Exceptions and IO

Structure of the Java API

java.io

Math static int round(float a)java.lang

java.applet String

Integer

static double sqrt(double a)

static double sin(double a)

PackagePackage ClassClass MethodsMethods

.

.

.

.

.

.

.

.

.

Page 6: Java API, Exceptions and IO

Importing

• If you want to import all classes from one package:– import java.io.*;

• If you want to import only one class from the package:– import java.io.SomeClass;

• Every Java – app imports automatically the package java.lang.*;

Page 7: Java API, Exceptions and IO

Example: Dateimport java.util.Date;

class App {

public static void main(String [] args) {

Date mydate = new Date();

String now = mydate.toString();

System.out.println(now);

}

}

Page 8: Java API, Exceptions and IO

Example Date - class

• Documentation:– http://java.sun.com/javase/6/docs/api/java/util/D

ate.html

Page 9: Java API, Exceptions and IO

Example: Math.random()// You really don't have to do this, since

// the Math class is in java.lang!

import java.lang.Math;

class App {

public static void main(String [] args) {

double randomValue = Math.random();

System.out.println(randomValue);

}

}

Page 10: Java API, Exceptions and IO

static?

• If method declaration contains static, call the method via Class name:– Class.method();– Math.random();

• If method declaration does NOT contain static, create object and then call object's method– Class object = new Class();– object.method();– Date mydate = new Date();– mydate.toString();

Page 11: Java API, Exceptions and IO
Page 12: Java API, Exceptions and IO
Page 13: Java API, Exceptions and IO

Couple Packages

• Graphical user interface and events:– java.awt– java.awt.event– javax.swing

• Input and output – java.io

• Data Structures, Internationalization, Utility Classes– java.util

Page 14: Java API, Exceptions and IO

Examples

• java.lang.String• java.util.Vector

Page 15: Java API, Exceptions and IO

EXCEPTIONS

Page 16: Java API, Exceptions and IO

Exception Handling

• Exception is a situation where application fail during runtime.

• You can handle these exceptions so you can for example give error messages to user.

Page 17: Java API, Exceptions and IO

Checked vs. Unchecked

• Checked exceptions– You have to implement exception handling– Subclass of Exception

• Unchecked exceptions– You may implement exception handling– Subclass of RuntimeException

• For example: when doing IO you MUST handle exceptions. When handling arrays you MAY handle exceptions

Page 18: Java API, Exceptions and IO

Unchecked Exceptionclass App {

public static void main(String [] args) {

double result = 1/0;

System.out.println(result);

}

}

java AppException in thread "main" java.lang.ArithmeticException: / by zero

at App.main(App.java:3)

Page 19: Java API, Exceptions and IO

Using Exceptionsclass App {

public static void main(String [] args) {

try {

double result = 1/0;

System.out.println(result);

} catch (ArithmeticException e) {

System.out.println("You cannot divide with zero!");

}

}

}

java AppYou cannot divide with zero!

Page 20: Java API, Exceptions and IO

Using Exceptionstry {

// something that can trigger an exception

} catch(ExceptionClass1 e) {

// If it was ExceptionClass1, go here

} catch(ExceptionClass2 e) {

// If it was ExceptionClass2, go here

} finally {

// Do this no matter what

}

Page 21: Java API, Exceptions and IO

Example of Exception Usageclass App {

public static void main(String [] args) {

try {

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

int a2 = Integer.parseInt(args[1]);

double result = a1 / a2;

System.out.println(result);

} catch (ArithmeticException e) {

System.out.println("You cannot divide with zero!");

} catch (NumberFormatException e) {

System.out.println("Please give integer numbers!");

} catch (ArrayIndexOutOfBoundsException e) {

System.out.println("Please give two integer numbers!");

}

}

}

Page 22: Java API, Exceptions and IO

Integer.parseInt?

• Package: java.lang• Class: Integer• Method: parseInt

It may throw an exception!

Page 23: Java API, Exceptions and IO

NumberFormatException

Inherites RuntimeException=>Unchecked Exception=>You MAY implement exception handling

Page 24: Java API, Exceptions and IO

Exception is the Base Class!class App {

public static void main(String [] args) {

try {

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

int a2 = Integer.parseInt(args[1]);

double result = a1 / a2;

System.out.println(result);

} catch (Exception e) {

System.out.println("Whatever exception is, always come here");

}

}

}

Page 25: Java API, Exceptions and IO

class App { public static void main(String [] args) { try { int a1 = Integer.parseInt(args[0]); int a2 = Integer.parseInt(args[1]); double result = a1 / a2; System.out.println(result); } catch (Exception e) { // Exception is class, e is an object. String errormsg = e.toString(); System.out.println(errormsg); } } }

> java App 4 0java.lang.ArithmeticException: / by zero> java App 4 kjava.lang.NumberFormatException: For input string: "k"> java App 4 java.lang.ArrayIndexOutOfBoundsException: 1

Page 26: Java API, Exceptions and IO

JAVA IO

Page 27: Java API, Exceptions and IO

Input and Output Streams

Input OutputBinary FileInputStream FileOutputStream

Text FileReader FileWriter

Page 28: Java API, Exceptions and IO

Reading Textimport java.io.*;

class App {

public static void main(String [] args) {

try {

// We use int even though characters are read!

int character;

FileReader input = new FileReader("App.java");

// Let's read and print the rest

// input.read() returns -1 when the file is done!

while((character = input.read()) != -1) {

System.out.print( (char) character);

}

// close the stream

input.close();

} catch(IOException e) {

System.out.println("Some problem reading the file");

}

}

}

Page 29: Java API, Exceptions and IO

Writing Textimport java.io.*;

class App {

public static void main(String [] args) {

try {

// We use int even though characters are read!

int character;

FileWriter output = new FileWriter("Test.txt");

do {

// Read from the user one char at a time

character = System.in.read();

// Write the chars to the text file.

// Write until user gives 'q'

output.write(character);

} while( ( (char) character ) != 'q' );

// close the stream

output.close();

} catch(IOException e) {

System.out.println("Some problem reading the file");

}

}

}

Page 30: Java API, Exceptions and IO

Reading and Writing Binaryimport java.io.*;

public class App{ public static void main(String args[]) { int oneByte; try { // For reading FileInputStream input = new FileInputStream("calculator.exe"); // For writing FileOutputStream output = new FileOutputStream("duplicatecalculator.exe"); // Read and write one byte at a time while( (oneByte = input.read()) != -1) { output.write(oneByte); } // close the streams input.close(); output.close(); } catch(IOException e) { System.out.println("Some problem with reading and writing"); } }}

Page 31: Java API, Exceptions and IO

Buffered Stream: BufferedReaderimport java.io.*;

class App { public static void main(String [] args) { try { String line = "something"; FileReader input = new FileReader("App.java"); BufferedReader bf = new BufferedReader(input); while((line = bf.readLine()) != null) { System.out.println(line); } // close the streams bf.close(); input.close(); } catch(IOException e) { System.out.println("Some problem reading the file"); } } }

Page 32: Java API, Exceptions and IO

Buffered Stream: BufferedWriterimport java.io.*;

class App { public static void main(String [] args) { try { FileWriter output = new FileWriter("Test.txt"); BufferedWriter bf = new BufferedWriter(output); bf.write("Hello");

bf.close(); output.close(); } catch(IOException e) { System.out.println("Some problem reading the file"); } } }