1 some salient characteristics of java java is platform independent: the same program can run on any...

56
1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented: Structured in terms of classes, which group data with operations on that data Can construct new classes by extending existing ones Java designed as •A core language plus A rich collection of commonly available packages Java can be embedded in Web pages

Upload: jonathan-malone

Post on 01-Jan-2016

213 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

1

Some Salient Characteristics of Java

• Java is platform independent: the same program can run on any correctly implemented Java system

• Java is object-oriented:• Structured in terms of classes, which group data with operations on

that data• Can construct new classes by extending existing ones

• Java designed as• A core language plus• A rich collection of commonly available packages

• Java can be embedded in Web pages

Page 2: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

JRE & JDK

• A Java distribution comes typically in two flavors, the Java Runtime Environment (JRE) and the Java Development Kit (JDK).

o The Java runtime environment (JRE) consists of the JVM and the Java class libraries and contains the necessary functionality to start Java programs.

o The JDK contains in addition the development tools necessary to create Java programs. The JDK consists therefore of a Java compiler, the Java virtual machine, and the Java class libraries.

2

Page 3: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

JVM

• JVM (Java virtual machine)

o Is a software implementation of a computer that executes programs like a real machine. Is written specifically for a specific operating system. Java programs are compiled by the Java compiler into bytecode. The Java virtual machine interprets this bytecode and executes the Java program.

o This gives Java the “write once run anywhere” nature.

Appendix A: Introduction to Java 3

Page 4: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

4

Java Processing and Execution

• Begin with Java source code in text files: Model.java

• A Java source code compiler produces Java byte code• Outputs one file per class: Model.class

• A Java Virtual Machine loads and executes class files

Page 5: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

5

Compiling and Executing a Java Program

Page 6: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

Classloader & Classpath

• ClassLoadero The Java ClassLoader is a crucial, but often overlooked, component of

the Java run-time system. It is the class responsible for finding and loading class files at run time. Creating your own ClassLoader lets you customize the JVM in useful and interesting ways, allowing you to completely redefine how class files are brought into the system.

• Classpatho The classpath defines where the Java compiler and Java runtime look

for .class files to load. This instructions can be used in the Java program. For example if you want to use an external Java library you have to add this library to your classpath to use it in your program.

6

Page 7: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

Garbage Collector

• Garbage collector

o The JVM automatically re-collects the memory which is not referred to by other objects. The java garbage collector checks all object references and find the objects which can be automatically released.

o While the garbage collector releases the programmer from the need to explicitly manage memory the programmer still need to ensure that he does not keep unneeded object references otherwise the garbage collector cannot release the associated memory. Keeping unneeded object references are typically called memory leaks.

7

Page 8: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

Package• Java groups classes into functional packages.

• Packages are typically used to group classes into logical units. For example all graphical views of an application might be placed in the same package called com.appname.application.views

• Other main reason for the usage of packages is to avoid name collisions of classes. A name collision occurs if two programmers give the same fully qualified name to a class. The fully qualified name of a class in Java consists out of the package name followed by a dot (.) and the class name. (package1.class1 ; package2.class1)

• The import statement tells the compiler to make available classes and methods of another package

• (See coding practices for naming)

8

Page 9: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

9

Classes and Objects• The class is the unit of programming. The class can be seen as the blueprint of an

object. It describes how an object is created.

• A Java program is a collection of classes• Each class definition (usually) in its own .java file• The file name must match the class name

• A class describes objects (instances)• Describes their common characteristics: is a blueprint• Thus all the instances have these same characteristics

• These characteristics are:• Data fields for each object• Methods (operations) that do work on the objects

Page 10: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

Inheritance

• A class can be derived from another class. In this case this class is called a subclass. Another common phrase is that a class extends another class.

• Inheritance is a mechanism in which one object acquires all the properties and behavior of another object of another class.

• It represents the “IS A” relations

• Multiple inheritance is not supported in Java.

10

Page 11: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

Abstraction & Encapsulation

• Abstraction is the process of hiding implementation details and showing only functionality.

• Abstraction hides the implementation details, whereas encapsulation hides the data.

• Abstraction lets you focus on what the object does rather than how it does it.

11

Page 12: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

Abstract Class

• A class that is declared as abstract is known as abstract class.

• It needs to be extended and its method implemented.

• It cannot be instantiated.

12

public abstract class MyAbstractClass { abstract double returnDouble(); }

Page 13: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

Abstract class vs Interface

13

Page 14: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

Interface

• Interface is a blueprint of a class that have static constants and abstract methods.

• It can be used to achieve fully abstraction and multiple inheritance.

14

public interface MyDefinition { // constant definition String URL="http://www.google.com"; // define several method stubs void test(); void write(String s); }

Page 15: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

15

References and Primitive Data Types

• Java distinguishes two kinds of entities• Primitive types• Objects

• Primitive-type data is stored in primitive-type variables• Reference variables store the address of an object

• No notion of “object (physically) in the stack”• No notion of “object (physically) within an object”

Page 16: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

16

Primitive Data Types

• Represent numbers, characters, boolean values

• Integers: byte, short, int, and long

• Real numbers: float and double

• Characters: char

Page 17: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

17

Operators

1. subscript [ ], call ( ), member access .2. pre/post-increment ++ --, boolean complement !, bitwise complement ~,

unary + -, type cast (type), object creation new3. * / %4. binary + - (+ also concatenates strings)5. signed shift << >>, unsigned shift >>>6. comparison < <= > >=, class test instanceof7. equality comparison == !=8. bitwise and &9. bitwise or |10. logical (sequential) and &&11. logical (sequential) or ||12. conditional cond ? true-expr : false-expr13. assignment =, compound assignment += -= *= /= <<= >>= >>>= &= |=

Page 18: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

18

Declaring and Setting Variables

• int square;square = n * n;

• double cube = n * (double)square;• Can generally declare local variables where they are initialized• All variables get a safe initial value anyway (zero/null)

Page 19: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

19

Referencing and Creating Objects

• You can declare reference variables• They reference objects of specified types

• Two reference variables can reference the same object• The new operator creates an instance of a class• A constructor executes when a new object is created• Example: String greeting = ″hello″;

Page 20: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

Constructor

• Constructor is just like a method that is use to initialize the state of an object.

• It is invoked at the time of creation.

• The return value is the current instance

20

Page 21: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

21

Methods

• A Java method defines a group of statements as performing a particular operation

• static indicates a static or class method• A method that is not static is an instance method• All method arguments are call-by-value

• Primitive type: value is passed to the method• Method may modify local copy but will not affect caller’s

value• Object reference: address of object is passed• Change to reference variable does not affect caller• But operations can affect the object, visible to caller

Page 22: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

Method Overloading vs Method Overwriting

• If a class has multiple methods by the same name but different parameters its called method Overloading. It increases the readibility of the program.

• If a subclass provides a specific implementation of a method that is already provided by its parent class it is known as method overriding. It is used for runtime polymorphism.

22

Page 23: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

23

Escape Sequences

• An escape sequence is a sequence of two characters beginning with the character \

• A way to represents special characters/symbols

Page 24: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

24

The String Class

• The String class defines a data type that is used to store a sequence of characters

• String is an immutable object• You cannot modify a String object

• If you attempt to do so, Java will create a new object that contains the modified character sequence

Page 25: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

25

The StringBuffer Class

• Stores character sequences• Unlike a String object, you can change the contents of a

StringBuffer object

Page 26: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

26

StringTokenizer Class

• We often need to process individual pieces, or tokens, of a String

Page 27: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

27

Wrapper Classes for Primitive Types

• Sometimes we need to process primitive-type data as objects• Java provides a set of classes called wrapper classes whose

objects contain primitive-type values: Float, Double, Integer, Boolean, Character, etc.

Page 28: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

28

Modifiers

• Access modifierso There are three access modifiers keywords available in

Java. public, protected and private.o There are four access levels: public, protected, default and private.

They define how the corresponding element is visible to other components.

Modifier Class Package Subclass World

public Y Y Y Y

protected Y Y Y N

no modifier Y Y N N

private Y N N N

Table 1. Access Level

Page 29: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

Static

• Variables• Static variable is used to refer the common property of all objects

(that is not unique for each object)• Static variables get memory only once in class area at the time of

loading

• Methods• Static methods belong to the class rather than the object of a class. • A static method can be invocked withouth a need to create na

instance of the class.• Static methods can access static data and change their value

29

Page 30: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

Final

• Variable• You cannot change the value of final variables.

• Method• Final methods cannot be overwritten (see previous slide)

• Class • Final classes cannot be inherited.

30

Page 31: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

31

Converting Numeric Strings to Numbers

• A dialog window always returns a reference to a String• Therefore, a conversion is required, using static

methods of class String:

Page 32: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

32

Input/Output using Streams

• An InputStream is a sequence of characters representing program input data

• An OutputStream is a sequence of characters representing program output

• The console keyboard stream is System.in• The console window is associated with System.out

Page 33: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

33

Opening and Using Files: Reading Input

import java.io.*;

public static void main (String[] args) {

// open an input stream (**exceptions!)

BufferedReader rdr =

new BufferedReader(

new FileReader(args[0]));

// read a line of input

String line = rdr.readLine();

// see if at end of file

if (line == null) { ... }

Page 34: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

34

Opening and Using Files: Reading Input (2)

// using input with StringTokenizer

StringTokenizer sTok =

new StringTokenizer (line);

while (sTok.hasMoreElements()) {

String token = sTok.nextToken();

...;

}

// when done, always close a stream/reader

rdr.close();

Page 35: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

35

Alternate Ways to Split a String

• Use the split method of String:

String[] = s.split(“\\s”);

// see class Pattern in java.util.regex• Use a StreamTokenizer (in java.io)

Page 36: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

36

Opening and Using Files: Writing Output

// open a print stream (**exceptions!)

PrintStream ps = new PrintStream(args[0]);

// ways to write output

ps.print(“Hello”); // a string

ps.print(i+3); // an integer

ps.println(“ and goodbye.”); // with NL

ps.printf(“%2d %12d%n”, i, 1<<i); // like C

ps.format(“%2d %12d%n”, i, 1<<i); // same

// closing output streams is very important!

ps.close();

Page 37: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

37

Exceptions• What are they?

• An exception is a representation of an error condition or a situation that is not the expected result of a method.

• Exceptions fall into two categories:• Checked Exceptions• Unchecked Exceptions

• Checked exceptions are inherited from the core Java class Exception. They represent exceptions that are frequently considered “non fatal” to program execution

• Checked exceptions must be handled in your code, or passed to parent classes for handling.

Page 38: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

38

Exceptions (2)

• Unchecked exceptions represent error conditions that are considered “fatal” to program execution.

• You do not have to do anything with an unchecked exception. Your program will terminate with an appropriate error message.

• To handle the exception, you write a “try-catch” block. To pass the exception “up the chain”, you declare a throws clause in your method or class declaration.

Page 39: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

39

Coding Exceptions

• Example• try {… normal program code}catch(Exception e) {… exception handling code}

Page 40: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

Throw vs Throws

40

Page 41: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

What is a Thread?

• Individual and separate unit of execution that is part of a process• multiple threads can work together to accomplish a

common goal• Video Game example

• one thread for graphics• one thread for user interaction• one thread for networking

Page 42: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

Advantages

• easier to program• 1 thread per task

• can provide better performance• thread only runs when needed• no polling to decide what to do

• multiple threads can share resources• utilize multiple processors if available

Page 43: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

Creating Threads (method 1)

• extending the Thread class• must implement the run() method• thread ends when run() method finishes• call .start() to get the thread ready to run

Page 44: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

Creating Threads Example 1class Output extends Thread {

private String toSay;

public Output(String st) {

toSay = st;

}

public void run() {

try {

for(;;) {

System.out.println(toSay);

sleep(1000);

}

} catch(InterruptedException e) {

System.out.println(e);

}

}

}

Page 45: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

Example 1 (continued)

class Program {

public static void main(String [] args) {

Output thr1 = new Output(“Hello”);

Output thr2 = new Output(“There”);

thr1.start();

thr2.start();

}

}

• main thread is just another thread (happens to start first)

• main thread can end before the others do• any thread can spawn more threads

Page 46: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

Creating Threads (method 2)

• implementing Runnable interface• virtually identical to extending Thread class• must still define the run()method• setting up the threads is slightly different

Page 47: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

Creating Threads Example 2

class Output implements Runnable {

private String toSay;

public Output(String st) {

toSay = st;

}

public void run() {

try {

for(;;) {

System.out.println(toSay);

Thread.sleep(1000);

}

} catch(InterruptedException e) {

System.out.println(e);

}

}

}

Page 48: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

Example 2 (continued)

class Program {

public static void main(String [] args) {

Output out1 = new Output(“Hello”);

Output out2 = new Output(“There”);

Thread thr1 = new Thread(out1);

Thread thr2 = new Thread(out2);

thr1.start();

thr2.start();

}

}

• main is a bit more complex• everything else identical for the most part

Page 49: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

Advantage of Using Runnable

• remember - can only extend one class (no multiple extends)

• implementing runnable allows class to extend something else

Page 50: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

Controlling Java Threads

• _.start(): begins a thread running• wait() and notify(): for synchronization

• more on this later• _.stop(): kills a specific thread (deprecated)• _.suspend() and resume(): deprecated• _.join(): wait for specific thread to finish• _.setPriority(): 0 to 10 (MIN_PRIORITY to

MAX_PRIORITY); 5 is default (NORM_PRIORITY)

Page 51: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

Java Thread Scheduling

• highest priority thread runs• if more than one, arbitrary

• yield(): current thread gives up processor so another of equal priority can run• if none of equal priority, it runs again

• sleep(msec): stop executing for set time• lower priority thread can run

Page 52: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

States of Java Threads

• 4 separate states• new: just created but not started• runnable: created, started, and able to run• blocked: created and started but unable to run

because it is waiting for some event to occur• dead: thread has finished or been stopped

Page 53: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

States of Java Threads

new

runnable

blocked

dead

start()stop(), end of run method

wait(),I/O request,suspend()

notify(),I/O completion,resume()

Page 54: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

synchronized Statement

• Every object has a lock associated with it.

• Calling a synchronized method attempts to possess the lock• If no one owns the lock, then this thread has/owns the lock.

• If a calling thread does not own the lock (another thread already owns it), the calling thread is placed in the entry set for the object’s lock.

• The lock is released when a thread exits the synchronized method.

Page 55: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

55

Defining Your Own Classes

• Unified Modeling Language (UML) is a standard diagram notation for describing a class

Class name

Field valuesClass

name

Field signatures:

type and name

Method signatures: name, argument types, result type

Page 56: 1 Some Salient Characteristics of Java Java is platform independent: the same program can run on any correctly implemented Java system Java is object-oriented:

56

Processing and Running HelloWorld

• javac HelloWorld.java• Produces HelloWorld.class (byte code)

• java HelloWorld• Starts the JVM and runs the main method