Download Introduction to Java

Document related concepts
no text concepts found
Transcript
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
1
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
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
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
4
Compiling and Executing a Java Program
5
Classloader & Classpath
• ClassLoader
o 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.
• Classpath
o 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
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
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
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
9
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
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
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.
public abstract class MyAbstractClass {
abstract double returnDouble();
}
12
Abstract class vs Interface
13
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.
public interface MyDefinition {
// constant definition
String URL="http://www.google.com";
// define several method stubs
void test();
void write(String s);
}
14
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”
15
Primitive Data Types
• Represent numbers, characters, boolean values
• Integers: byte, short, int, and long
• Real numbers: float and double
• Characters: char
16
Operators
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
subscript [ ], call ( ), member access .
pre/post-increment ++ --, boolean complement !, bitwise complement ~,
unary + -, type cast (type), object creation new
*/%
binary + - (+ also concatenates strings)
signed shift << >>, unsigned shift >>>
comparison < <= > >=, class test instanceof
equality comparison == !=
bitwise and &
bitwise or |
logical (sequential) and &&
logical (sequential) or ||
conditional cond ? true-expr : false-expr
assignment =, compound assignment += -= *= /= <<= >>= >>>= &= |=
17
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)
18
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″;
19
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
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
21
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
Escape Sequences
• An escape sequence is a sequence of two characters
beginning with the character \
• A way to represents special characters/symbols
23
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
24
The StringBuffer Class
• Stores character sequences
• Unlike a String object, you can change the contents of a
StringBuffer object
25
StringTokenizer Class
• We often need to process individual pieces, or tokens, of a
String
26
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.
27
Modifiers
• Access modifiers
o 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
28
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
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
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:
31
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
32
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) { ... }
33
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();
34
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)
35
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();
36
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.
37
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.
38
Coding Exceptions
• Example
• try {
… normal program code
}
catch(Exception e) {
… exception handling code
}
39
Throw vs Throws
40
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
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
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
Creating Threads Example 1
class 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);
}
}
}
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
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
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);
}
}
}
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
Advantage of Using Runnable
• remember - can only extend one class (no multiple
extends)
• implementing runnable allows class to extend something
else
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)
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
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
States of Java Threads
start()
runnable
stop(),
end of run method
new
dead
wait(),
I/O request,
suspend()
blocked
notify(),
I/O completion,
resume()
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.
Defining Your Own Classes
• Unified Modeling Language (UML) is a standard diagram
notation for describing a class
Field
signatures:
type and name
Method signatures:
name, argument
types, result type
Class
name
Field
values
Class
name
55
Processing and Running HelloWorld
• javac HelloWorld.java
• Produces HelloWorld.class (byte code)
• java HelloWorld
• Starts the JVM and runs the main method
56