Chapter 2 The Java Overview. What is Java? The name Java is applied to a variety of technologies...

34
Chapter 2 The Java Overview

Transcript of Chapter 2 The Java Overview. What is Java? The name Java is applied to a variety of technologies...

Page 1: Chapter 2 The Java Overview. What is Java? The name Java is applied to a variety of technologies created by Sun Microsystems There are three main components.

Chapter 2

The Java Overview

Page 2: Chapter 2 The Java Overview. What is Java? The name Java is applied to a variety of technologies created by Sun Microsystems There are three main components.

What is Java?

The name Java is applied to a variety of technologies created by Sun Microsystems

There are three main components of Java: The Java Programming Language – a programming

language used to write software for the Java platform The Java platform – a range of runtime environments

that supports execution of software written in Java The Java API – a rich, fully featured class library that

provides graphical user interface, data storage, data processing, I/O and networking support

Page 3: Chapter 2 The Java Overview. What is Java? The name Java is applied to a variety of technologies created by Sun Microsystems There are three main components.

The Java Programming Language

History (http://java.sun.com/features/1998/05/birthday.html)

Properties of the Java language Object orientation Simplicity Automatic garbage collection Portability Multi-threaded programming Security Internet awareness

Page 4: Chapter 2 The Java Overview. What is Java? The name Java is applied to a variety of technologies created by Sun Microsystems There are three main components.

The Java Platform

Third-generation language The source code instructions written in Java

must be compiled to a form that the computer is capable to understand

Most languages would be compiled to machine native code, hence running on a specific CPU architecture.

Problem with distribution of the program

Page 5: Chapter 2 The Java Overview. What is Java? The name Java is applied to a variety of technologies created by Sun Microsystems There are three main components.

Cont.

The Java platform takes a different approach. Instead of creating machine code for

particular pieces of hardware, Java source code is compiled to run on a single CPU

Java machine code or bytecode is executed by a special software that mimics a CPU chip capable of understanding bytecode

The software is called Java Virtual Machine (JVM)

Page 6: Chapter 2 The Java Overview. What is Java? The name Java is applied to a variety of technologies created by Sun Microsystems There are three main components.

The Java Virtual Machine

An emulation of hardware device Write Once, Run Anywhere (WORA) JVM allows Java to be portable across

different type of OS Flexibility vs performance issues However, advancement of CPU performance

“covers” Java weakness

Page 7: Chapter 2 The Java Overview. What is Java? The name Java is applied to a variety of technologies created by Sun Microsystems There are three main components.

Java Runtime Environment

JVM is not a software application that can itself be run

Usually, the JVM is hosted within a Java runtime environment (JRE)

JRE will also include the core classes from the Java API and other supporting files.

J2SE, J2EE, J2ME

Page 8: Chapter 2 The Java Overview. What is Java? The name Java is applied to a variety of technologies created by Sun Microsystems There are three main components.

The Java API The API provides a rich suite of classes and components that allows

Java to do real work, such as: Reading from and writing to files on the local hard drive Creating graphical user interfaces with menus, buttons, text

fields and drop-down lists Drawing pictures from graphical primitives such as lines,

circles, squares and ellipses Assessing network resources such as Web sites or network

servers Storing data in data structures such as linked lists and arrays Manipulating and processing data such as text and numbers Retrieving information from databases or modifying records

Page 9: Chapter 2 The Java Overview. What is Java? The name Java is applied to a variety of technologies created by Sun Microsystems There are three main components.

Example of Java networking packages Package java.net – comprises the majority of

classes that deal with Internet Programming. It provides the basic building blocks needed to write network applications and services such as UDP packets, TCP sockets, IP addresses, URLs and HTTP connections

Package java.rmi – to supports Remote Method Invocation (RMI)

Package org.omg – package that supports the Common Object Request Broker Architecture (CORBA)

JavaMail – provides access to e-mail services.

Page 10: Chapter 2 The Java Overview. What is Java? The name Java is applied to a variety of technologies created by Sun Microsystems There are three main components.

Java Networking Considerations

“Ideal” language for network programming However, Java does not provide low-level

access to Internet Protocols Java imposes severe security restrictions on

Java applets No applet may bind to a local port, to prevent it

from masquerading as a legitimate service. An applet may connect only to the machine from

which its codebase was loaded.

Page 11: Chapter 2 The Java Overview. What is Java? The name Java is applied to a variety of technologies created by Sun Microsystems There are three main components.

Application of Java Network Programming

Network Programming adds a new dimension to software applications

Network programming gives software the ability to communicate with machines scattered around the globe

The limitation is the BANDWITDH of a network connection

Page 12: Chapter 2 The Java Overview. What is Java? The name Java is applied to a variety of technologies created by Sun Microsystems There are three main components.

Network clients

A common use for Java is to create network clients such as:

Mail readers Remote file transfer application Browser

In the design of a new network protocols for which no client yet exists

Page 13: Chapter 2 The Java Overview. What is Java? The name Java is applied to a variety of technologies created by Sun Microsystems There are three main components.

Games

One major application of network communication is the multiplayer games that run over a LAN or online games which run over the Internet

Page 14: Chapter 2 The Java Overview. What is Java? The name Java is applied to a variety of technologies created by Sun Microsystems There are three main components.

Software agents

A software that acts on the behalf of one or more users, to perform specific commands and tasks or to fulfill a set of goals

Examples: An agent to sort through email message An agent that searches for information on the

Web An agent that monitors a source of information for

changes relating to the interest of a user

Page 15: Chapter 2 The Java Overview. What is Java? The name Java is applied to a variety of technologies created by Sun Microsystems There are three main components.

Web Applications

One of the most important areas for Java network programming

Applets Server-side Java : JSP

Within a web server, Java can perform a variety of tasks Accessing databases. Interacting with other systems.

Page 16: Chapter 2 The Java Overview. What is Java? The name Java is applied to a variety of technologies created by Sun Microsystems There are three main components.

Distributed Systems

Used to solve very complex and large problems

Resources may be distributed across an organization

Distributed system technologies are used to integrate them (I.e. databases and inventory systems from different departments)

RMI and CORBA make this possible

Page 17: Chapter 2 The Java Overview. What is Java? The name Java is applied to a variety of technologies created by Sun Microsystems There are three main components.

Java Language Issues

In network programming using Java, there are some issues that we need to be aware of

1. Exception Handling in Java

2. What are Exceptions

3. Types of Exceptions

4. Handling exceptions

5. Causes of exceptions

Page 18: Chapter 2 The Java Overview. What is Java? The name Java is applied to a variety of technologies created by Sun Microsystems There are three main components.

Exception Handling in Java

A mechanism for dealing with errors that occur in software at runtime. For example, while attempting to read from a file, an application may be unable to proceed because the file is missing (occur at runtime).

Page 19: Chapter 2 The Java Overview. What is Java? The name Java is applied to a variety of technologies created by Sun Microsystems There are three main components.

What are Exceptions Unusual conditions that occur at runtime and are represented as

objects Track information about errors condition, making it possible to

diagnose the cause of the problem or at least to provide clues as to why it occurred.

The method in which an exception occurs will “throw” the exception and pass it to the calling method.

The calling method may choose to handle the error condition and “catch” the exception or it may throw the exception to its calling method.

Method that are likely to generate an exception will indicate the type of exception that will be thrown.

At some point in the code, the exceptions need to be caught and dealt with accordingly

Page 20: Chapter 2 The Java Overview. What is Java? The name Java is applied to a variety of technologies created by Sun Microsystems There are three main components.

Checked and Unchecked Exceptions

Checked The compiler checks that you don't ignore them Due to external circumstances that the programmer

cannot prevent Majority occur when dealing with input and output For example, IOException

Unchecked: Extend the class RuntimeException or Error They are the programmer's fault Examples of runtime exceptions:

NumberFormatException IllegalArgumentException NullPointerException

Example of error: OutOfMemoryError

Page 21: Chapter 2 The Java Overview. What is Java? The name Java is applied to a variety of technologies created by Sun Microsystems There are three main components.
Page 22: Chapter 2 The Java Overview. What is Java? The name Java is applied to a variety of technologies created by Sun Microsystems There are three main components.

Checked exceptions – must be caught or declared to be thrown

Catch the exception – try, catch, finally clause Declare the exception - tell compiler that you want

method to be terminated when the exception occurs Use throws specifier

public void read(String filename) throws FileNotFoundException { FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader); . . . }

For multiple exceptions: public void read(String filename) throws IOException, ClassNotFoundException

Keep in mind inheritance hierarchy: If method can throw an IOException and FileNotFoundException, only use IOException

Page 23: Chapter 2 The Java Overview. What is Java? The name Java is applied to a variety of technologies created by Sun Microsystems There are three main components.

Handling Checked Exceptions

Java provides three statements for handling checked exceptions:

1. try

2. catch

3. finally

Page 24: Chapter 2 The Java Overview. What is Java? The name Java is applied to a variety of technologies created by Sun Microsystems There are three main components.

try statement

The try statement indicates a block of code that can generate exception

//code outside of try block should not throw an exception

try {

// do something that could generate an exception…

}

//handle exception…

Page 25: Chapter 2 The Java Overview. What is Java? The name Java is applied to a variety of technologies created by Sun Microsystems There are three main components.

catch statement

The catch statement is used to catch exceptions thrown within a try block of code.

//try block can generate exceptionstry {

//generate an exception}catch (SocketException se){

System.err.println(“Socket error reading from host: “ + se);System.exit(2);

}catch (Exception e){

System.err.println(“Error:” + e);System.exit(1);

}

Page 26: Chapter 2 The Java Overview. What is Java? The name Java is applied to a variety of technologies created by Sun Microsystems There are three main components.

finally statementThe finally statement is a generic catchall for cleaning up after

a try block.

//try block can generate exceptionstry {

//generate an exception}catch (SomeException some){

//handle some exception}finally{

//clean up after try block, regardless of any//exceptions that are thrown

}

Page 27: Chapter 2 The Java Overview. What is Java? The name Java is applied to a variety of technologies created by Sun Microsystems There are three main components.

An exampletry {

String filename = . . .; FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader); String input = in.next(); int value = Integer.parseInt(input); . . .

} catch (IOException exception) {

exception.printStackTrace(); } catch (NumberFormatException exception) {

System.out.println("Input was not a number"); }finally {

reader.close(); // if an exception occurs, finally clause is also // executed before exception is passed to its handler

}

Page 28: Chapter 2 The Java Overview. What is Java? The name Java is applied to a variety of technologies created by Sun Microsystems There are three main components.

Unchecked Exceptions

Exceptions that extend from the Error class: Typical errors that typical Java software should not

encounter and over which the developer has no control. AWTError – serious error occurs in the Abstract Windowing

Toolkit NoClassDefFoundError – thrown when the JVM is unable

to locate the class definition file (.class) for a class OutOfMemoryError – occurs when JVM can no longer

allocate memory to objects

Page 29: Chapter 2 The Java Overview. What is Java? The name Java is applied to a variety of technologies created by Sun Microsystems There are three main components.

Unchecked Exceptions

Runtime error examples: NoSuchElementException – thrown when an attempt is

made to access the next element of an enumeration but all elements have been exhausted

NullPointerException – thrown when an attempt to reference an object has been made but the reference was null

SecurityException – thrown by the current security manager when an attempt to access a resource, object or method has been made but not permitted

Page 30: Chapter 2 The Java Overview. What is Java? The name Java is applied to a variety of technologies created by Sun Microsystems There are three main components.

Causes of exceptions in network programming

In networking, the most common cause of exceptions is related to the state of the network connection: Loss of connection due to congestion Server/host behind firewall that blocks external

requests Other may be due to security measures

imposed by the browser or by Java security policy or security manager.

Page 31: Chapter 2 The Java Overview. What is Java? The name Java is applied to a variety of technologies created by Sun Microsystems There are three main components.

import java.net.*;

public class LocalHostDemo {

public static void main(String args[]){

System.out.println ("Looking up local host");

try{

// Get the local hostInetAddress localAddress = InetAddress.getLocalHost();

System.out.println ("IP address : " + localAddress.getHostAddress() );

}catch (UnknownHostException uhe){

System.out.println ("Error - unable to resolve

localhost");}

}}

Using InetAddress to determine localhost address

Page 32: Chapter 2 The Java Overview. What is Java? The name Java is applied to a variety of technologies created by Sun Microsystems There are three main components.

import java.net.*;public class NetworkResolverDemo {

public static void main(String args[]){

if (args.length != 1){

System.err.println ("Syntax - NetworkResolverDemo host");System.exit(0);

}System.out.println ("Resolving " + args[0]);try{

// Resolve host and get InetAddressInetAddress addr = InetAddress.getByName ( args[0] );System.out.println ("IP address : " +

addr.getHostAddress() ); System.out.println ("Hostname : " + addr.getHostName() );

}catch (UnknownHostException uhe){

System.out.println ("Error - unable to resolve hostname");}

}}

Using InetAddress to find out about other Addresses

Page 33: Chapter 2 The Java Overview. What is Java? The name Java is applied to a variety of technologies created by Sun Microsystems There are three main components.

Development Tools

Java SDK version 6 IDE

NetBeans Eclipse JCreator

Page 34: Chapter 2 The Java Overview. What is Java? The name Java is applied to a variety of technologies created by Sun Microsystems There are three main components.

Chapter Highlights

You have learned The history of Java, design goals and properties

of the Java language About compiled bytecode, the Java Virtual

Machine and Java Runtime Environment The core Java API and some Java extensions Some issue and consideration related to Java Example of applications Exception handling Development tools