Title: The Java 2SE Platform
1The Java 2SE Platform
- Lars Degerstedt
- Linköping university, IDA
- larde_at_ida.liu.se
2This Lecture
- 1st hour Java, the language
- Prelimiaries Java 2 overview
- Language constructs
- Java programs
- 2nd hour Java, APIs
- Literature
- The Java Tutorial http//java.sun.com/docs/books/t
utorial
3Preliminaries UML and objects
Interface
Class/Superclass
Eater
Animal
size int
getFood() Food
BodyParts List
getFood() Food
Consists of
Leg
inherits
Dog
Subclass
4The Java 2 Platform and J2SE
- Several parts Language, JVM, APIs, Component
models, and still growingall packages in
subplatforms. - Our main focus J2SE Java 2 Standard Edition
5The Java Language (SDK 1.4)
- Almost pure object-oriented
- Static methods/fields, e.g. the main method
- Single inheritance
- Interfaces and classes
- Runs interpreted on Java Virtual Machine (JVM)
everywhere, not always true - graphical components have problems
- Different machines JVM/KVM
- Garbage collection explicit call
java.lang.System.gc()
6Example Java Class brief
- import java.io.
- import java.net.URL
- package java.being.primates
- public class Dog extends Animal implements
- Eater
- private int size -1
- private Food food null
- public Dog(int size, Food food)
- this.size size
- this.food food
-
- public Food getFood()
- return food
-
-
-
7Variables
- Static typing (almost, see inner classes)
- int zero 0
- public String enStrang nisse
- Casting
- String s (String) anObject
8Data Types
- Primitive
- byte,short, int, long
- float double
- char
- Boolean
- Reference
- Objects
- arrays
9Operators
- Arithmetic - / , --
- Relational gt , gt, lt, lt, , !
- Conditional , , !, , ,
- Assignment - /
- Others .(Type)new instanceof this super
- Blocks
- Scope is block dependent
10Control Flow Statements
- looping while, dowhile , for
- Branching ifelse, switchcase
- Exceptions trycatchfinally,throw, throws
- aborts break, continue, label, return
11Java programs
- Executable programs are collections of
classes/interfaces that - Compiles, i.e. No dangling references
- Contains a main method
- static void main(String args)
- Jar-archives optional encapsulation of compiled
classes, e.g. - mylib.jar
12Compiling/ Running Programs
- javac MyClass.java
- -gt MyClass.class
- java MyClass
- Starts and runs program
- Start point
- public class MyClass
-
- public static void main(String argv)
-
13CLASSPATH
- To link in external classes
- Win
- java classpath c\myJavac\jars\myjar.jar
MyClass.java - Solaris
- java classpath /home/my/myJava/home/my/myjar.jar
MyClass.java
14Classes
- Blueprint of objects (state and behavior)
- One top level class one file
- Default inheritance from java.lang.Object
- Modifiers
- public, protected, private
- abstract, final
15Interfaces
- Abstract Class definition
- A set of methods for a class type
- Class type description
- Multiple views on Class
- Class contract
- Can also declare constants
- Two uses
- Callback making methods parameters
- Polymorphism alternative to subclasses
16Methods
- Methods that provide behavior for Classes
- In Parameters
- Fixed number use anonymous arrays for dynamic
case - Return Value (return statement/type)
- Single object/primitive/array
- Modifiers
- public, protected, private
- static, final, native, synchronized
17Constructors
- Method that initialize objects
- Default constructor
- Constructors are not inherited
- Modifiers
- public, protected, private
18Fields
- Primitives and Classes
- Must have a type
- All Fields are objects in reality
- Even primitives
- Modifiers
- public, protected, private
- static, final, transient, volatile
19Packages Import
- Packages are namespaces for groups of Classes
- ex java.lang
- protected modifier
- used to be usable in package and for subclasses
- Packages can be imported
- to use Classes by short Name
- e.g String vs. java.lang.String
20Example Class again
- import java.io.
- import java.net.URL
- package java.being.primates
- public class Dog extends Animal implements
- Eater
- private int size -1
- private Food food null
- public Dog(int size, Food food)
- this.size size
- this.food food
-
- public Food getFood()
- return food
-
-
-
21Naming Conventions
- Classes
- MyClassName
- Methods
- myMethodName()
- Variables
- MyClass myClass new MyClass()
- Packages
- java.lang, opennlp.jbrickslib.util
22System
- java.lang.System
- System.out, System.in
- java.lang.RunTime
- java.lang.Process, java.lang.SecurityManager
- java.lang.Object
- java.lang.Class, java.langClassLoader
- Integer, Byte, Boolean, Char, String,
StringBuffer, Double
23Comments
- // on liners
- / Multi linersexpanding several lines/
- /Javadoc comment/
24Javadoc
- Document generation based on _at_-tags and automated
code extraction - /
- Class description goes here.
-
- _at_version 1.82 18 Mar 1999
- _at_author Firstname Lastname
- /
- public class Blah extends SomeClass
25Unicode
- Java character encoding
- The Unicode Standard, Version 2.0, ISBN
0-201-48345-9 - A unique number for every character
- no matter platform, program, language
26This Lecture
- 1st hour Java, the language
- 2nd hour Java, APIs
- Overview of J2SE APIs
- Collections
- Graphics AWT/Swing
- Reflection
- XML
- JDBC
27J2SE (v1.4) APIs - Overview
User Interface toolkits
Swing
AWT
Input methods
Sound
Java2D
Access
Integration APIs
RMI
JDBC
JNDI
CORBA
Core APIs
XML
Logging
Beans
Locale
Pref
Collections
JNI
Security
Lang
Util
New I/O
Network
28Collection/Map API
- Representing and manipulating collections/maps
- Collections have three parts
- Interfaces ADT APIs
- Implementations data structures
- Algorithms polymorphism
- Program with interfaces
- List l new ArrayList()
- Interoperatibility beyond vectors
- Fosters software reuse
- element and bulk operations add/addAll
29Collection/Map Interface Taxonomy
AbstractCollection
AbstractMap
HashMap
AbstractSet
TreeMap
AbstractList
HashSet
ArrayList
TreeSet
30Collection/Map Collections
- Group of elements (e.g. List or Set)
- Add/Remove/Iterate/Contains
- Bulk operations are polymorphic, i.e. works on
any Collection - Parameter for Map interface
- toArray method for export
31Collection/Map Lists
- Positional access
- Arrays.toList() method for static list view of
array - ListIterator allows for manipulation during
iteration - Sublist extraction
32Collection/Map Maps
- Collection views of keys and values
- Iterators over keys, values, and tuples
- Bulk op. putAll imports maps
- Equals must imply hashCode for elements
- Bulk op. retainAll restricts a map to a given
Collection
33Graphics are Components
- AWT and Swing is based on Components and
Containers - Components are placed in containers
- update(), paint(), repaint()
- Layout Managers
- Swing is now the pushed Window Toolkit from SUN
34Graphics AWT Hierarchy
35Graphics AWT Event Model
- Messaging across Java classes
- java.awt.event (extended in javax.swing.event)
- Event listener
- the Observer Design pattern
- Interested classes report them selves to event
casting classes
36Graphics AWT-Example Event
- import java.awt.
- import java.awt.event.
- class MyApp implements ActionListener Button
okButton new Button() - MyApp()
- // build graphics components
- okButton new Button(OK)
- okButton.addActionListener(this)
- // deploy gui widget
- public void actionPerformed(ActionEvent e)
System.out.println(Hey, you pressed
OK button!") -
37Graphics Swing
- Two types of entities
- atomic components and containers
- More advanced Window Toolkit
- but uses the AWT event model
- Control-View-Model design pattern
- gui-state and application-data models. Ex
Button, table resp. - Text parsing (HTML)
- No native code lightweight
- AWT and Swing components dont mix!
38Swing Containment hierarchy
The Containment hierarchy
OBS!
Containment is a dynamic Property not the
taxonomy
39Swing Code Example
public static void main(String args) try
UIManager.setLookAndFeel(UIManager.getCrossPlatf
ormLookAndFeelClassName()) catch (Exception
e) JButton button new JButton("I'm a Swing
button!") button.setMnemonic(KeyEvent.VK_I)
button.addActionListener(...create an action
listener...) labelPrefix "Number of button
clicks " numClicks 0 label new
JLabel(labelPrefix "0 ") JPanel pane new
JPanel() pane.setBorder(BorderFactory.createEmpt
yBorder(30, 30, 10, 30)) pane.setLayout(new
GridLayout(0, 1)) pane.add(button)
pane.add(label) JFrame frame new
JFrame("SwingApplication") frame.getContentPane(
).add(pane, BorderLayout.CENTER)
frame.addWindowListener(...) frame.pack()
frame.setVisible(true)
Obs
40Swing Containers
- Containers arrange collections of visual Swing
components - Top level containers JFrame, JDialog, JApplet
- Intermediate containers/Content panes JPanel,
JLayeredPanel, JInternalFrame, JScrollPane, etc.
41Swing Component/Container Taxonomy
Container
AWT
JComponent
Window
Frame
AbstractButton
JPanel
Swing
JButton
JFrame
42AWT/Swing Layout Managers
- Objectified functionality of Container
- Both AWT and Swing have managers
43AWT/Swing Implementation
- AWT is heavyweight have platform-specific peer
classes. - Swing is lightweight uses AWT, thus only
indirectly related to underlying platform. - Swing has pluggable Look and Feel
- Event dispatching thread AWT/Swing is
single-threaded. - Use SwingUtilities for threads invokeAndWait,
invokeLater
44Graphics Additional Features
- Drag and Drop
- Internationalization
- Adapting to various languages and regions without
engineering changes - Accessibility
- Support for People with Disabilities
- Java Foundation Classes (JFC) bean support
(ready for drag and drop)
45XML
- Java to XML
- Save Java classes in XML (JAXB)
- XML-Remote Procedure Call (like SOAP)
- XML messaging...
- Working with XML documents
- XML parser
- DOM navigation (eg JAXP)
- XML Binding (saving Java to XML)
JAXP API
46Reflection Java meta-programming
- Inspection of objects (both arrays and classes)
- Superclasses
- The Class object
- Method and Field objects
- Meta-creation of new objects
- Meta-evaluation of methods/fields
- Security and exception handling somewhat elaborate
47JDBC
- Java Data Base Connectivity
- High-level API to SQL-databases
- java.sql.
- Includes network connection
- Vendor specific Drivers take care of networking
and DB-connections
48JDBC Accessing the Database
Java Client
java.sql.Connection
Creates
Database
Java.sql.Statement
SQL Call API
- Load Driver
- Create a connection
- Create Statement and execute SQL-commands
- Extract Results
- Close connection
Creates
Java.sql.Resultset
SQL Result API
49JDBC Code Example
- Class.forName(com.mysql.jdbc.Driver).newInstance
() - String url jdbcmysql//maj4.ida.liu.sebird_da
tabase - Connection c DriverManager.getConnection(url,
"my_login", "my_password") - Statement stmt con.createStatement()
- Resultset rs stmt.executeQuery(SELECT FROM
species WHERE name \skata\") - rs.next()
- String text rs.getString(migration_field)
- System.out.println(Skata has migrationtext)
-
50Java News
- Java 2SE, version 1.5
- Language extensions, e.g. Parameterized types
- New APIs, e.g. java.util.concurrent
- Suns Java Desktop System
- Java-based graphical desktop on top of
Linux/GNOME - Java Community Process
- Future enhancements of the Java Platform