SlideShare a Scribd company logo
1
2
Java Programming
Simon Ritter
simon.ritter@uk.sun.com
3
Agenda
u Java Language Syntax
u Objects The Java Way
u Basics Of AWT
u Java Hints & Tips
u Demonstration
u Where Next?
4
Java Language Syntax
5
Comments
u C Style
/* Place a comment here */
u C++ Style
// Place another comment here
6
Auto-Documenting Comments
u javadoc utility part of JDK
/** Documentation comment */
– @see [class]
– @see [class]#[method]
– @version [text]
– @author [name]
– @param [variable_name] [description]
– @return [description]
– @throws [class_name] [description]
7
Java Data Types
u Primitive Types
– byte 8 bit signed
– short 16 bit signed
– int 32 bit signed
– long 64 bit signed
– float 32 bit IEEE 754
– double 64 bit IEEE 754
– char 16 bit Unicode
– boolean true or false
u No Unsigned Numeric Types
8
Java Data Types
u Reference Types
– class
– array
– interface (cannot be instantiated)
9
Type Promotion/Coercion
u Types Automatically Promoted
– int + float Automatically Returns float
u No Automatic Coercion
float pi = 3.142;
int whole_pi = pi; /* Compile Time Error */
int whole_pi = (int)pi; /* Success! */
10
Variables
u Cannot Use Reserved Words For Variable Names
u Variable Names Must:
– Start With A Letter (‘A’-’Z’, ‘a’-’z’,’_’,’$’)
(Can Use Unicode)
– Be A Sequence Of Letters & Digits
u Can Have Multiple Declarations
– int I, j, k;
u Constants Not Well Supported (Class Only)
11
Variable Assignment
u Assignments Can Be Made With Declaration
int I = 10;
u char uses single quote, strings use double
– Unicode can be specified with 4 byte hex number
and u escape
char CapitalA = `u0041`;
12
Variable Modifiers
u static
– Only One Occurrence For The Class
– Can Be accessed Without Instantiating Class
(Only If Class Variable)
u transient
– Do Not Need To Be Serialised
u volatile
– Do Not Need To Be Locked
13
Arrays
u Arrays Are References To Objects
u Subtely Different To ‘C’
int x[10];
x[1] = 42; /* Causes runtime nullPointer exception */
u Space Allocated With new
– int[] scores; /* Brackets either place */
– results = new int[10];
– short errors[] = new short[8];
14
Arrays (Cont’d)
u Can Create Multi-Dimensional Arrays
u Can Create ‘Ragged’ Arrays
u Space Freed When Last Reference Goes
Out Of Scope
15
Operators
u ! ~ ++ --
u * / %
u + -
u << >> >>>
u < <= > >=
u == !=
u &
u ^
u |
u &&
u ||
u = += -= *= /= %= &= |=
^= <<= >>= >>>=
16
Conditional Statements
u Syntax
if ( [test] ) { [action] } else { [action] }
u Example:
if (i == 10)
{
x = 4;
y = 6;
} else
j = 1;
17
Determinate Loops
u Syntax
for ( [start]; [end]; [update] )
{
[statement_block];
}
u Example
for (i = 0; i < 10; i++)
x[i] = i;
18
Indeterminate Loops
u Syntax 1:
while ( [condition] )
{
[statement_block]
}
u Syntax 2:
do {
[statement_block]
}
while ( [condition] );
19
Multiple Selections: Switch
u Syntax:
switch ( [variable] )
{
case [value]:
[statement_block];
break <label>;
default:
[statement_block];
}
20
Labeled Statement
u Label Must Preceed Statement To Jump To
u Label Must Be Followed By Colon (:)
u Use break And continue With Label
int i;
i:
for (i = start; i < max; i++)
{
int n = str.count, j = i, k = str.offset;
while (n-- != 0)
if (v[j++] != v2[k++])
continue i;
21
Java Memory Handling
u Allocation
– Use new with declaration
u Deallocation
– Handled Automatically By Garbage Collector
» Background Thread
– finalize Method
» File Handles
» Graphics Contexts
22
Error Handling In Java
u Catching Exceptions
u Syntax:
try
{
[statement_block];
} catch ( [exception_type] )
{
[statement_block];
} finally
{
[statement_block];
}
23
Returning Values
u Use return Expression
u If No Return Value Is Used Method Must Be
Declared void
u Don’t Get Confused By try/finally
Blocks
– finally Block Code Will Always Be executed Before
The Return Of Control To The Invoking Method
24
Objects The Java Way
25
Basic Java Objects
u Syntax:
class [name] extends [super]
{
[variables]
name() {} /* Constructor */
[methods]
}
26
Object Variables
u Implicit Pointer To Object
u Must Be Initialised (Unless Declared static)
– Wombat fred;
c = fred.colour(); WRONG
– Wombat fred = new Wombat();
c = fred.colour(); RIGHT
27
Overloading
(Ad-Hoc Polymorphism)
u Methods Have The Same Name But Different
Arguments (different ‘signature’)
– setTime(short hour, short min, short sec)
– setTime(short hour, short min)
– setTime(short hour)
u Java Uses Static Dispatch For Methods In The
Same Class
28
Constructor Methods
u Forces Initialisation Of The Object
u Can Be Overloaded
u Use super keyword for Superclass
public Wombat(String name, int age)
{
super(name); /* Must be first line */
wombat_age = age;
}
29
Destructor Methods
u Use finalize() method
u Used To Tidy Up Resources Not Tracked
By Garbage Collector
u Not Guaranteed To Be Called Until
Garbage Collector Runs
30
Accessor/Mutator Methods
u Mutator Methods
– setProperty()
u Accessor Methods
– getProperty()
31
Scope Modifiers
u public
– Available To All, Outside Object
u private
– Only Available Inside Object
u protected
– Only Available To Sub-Classes
u static
– Does Not Depend On Instatiation Of Object
32
The this Object
u Refers To The Current Instatiation Of This
Object
u Can Be Used In Constructor With
Overloading
Wombat(String name, int age)
{
Wombat_age = age;
this(name);
}
33
Packages
u Provides Libraries Of Classes
u Use package Keyword At Start Of Source
u Use import Keyword To Use Classes
import java.util.*;
Date Today = new Date();
u Can Use Full Name (must be in CLASSPATH)
Date Today = new java.util.Date();
u Source Files Can Only Have One Public Class
34
Inheritance/Subclasses
u Allows Common Functionality To Be
Reused
u Subclasses Extend The Functionality Of
The Super Class
35
The super Method
u Refers To The Super-Class Of This Object
u On It’s Own Will Call The Constructor For The
Super Class
– Call Must Be First Line Of Sub-Class Constructor
u Can Be Used To Directly Call Methods Of The
Super Class
– super.setName(name);
36
The Cosmic Superclass
u Object Class Is Ultimate Superclass
u If No Super-Class Specified, Object Is
Default
u Has Useful Methods
– getClass()
– equals()
– clone()
– toString()
37
Polymorphism
u Method Signature:
– Name
– Parameters
u Used To Access Methods Defined In Super-Classes
u Signatures Must Match To Be executed
u A Method With The Same Signature Will Hide Those
in Super Classes
u Failure To Match Will Cause Compile Time Error
38
Final Classes
u Use final Keyword
u Used With class Prevents Inheritance
u Used With Method Prevents Overriding
u Two Reasons For Using final
– Efficiency
– Safety
39
Abstract Classes
u Creates Placeholders For Methods
u Classes With Abstract Methods Must Be
Declared Abstract
u Abstract Methods Must Be Defined in
Sub-Classes
40
Interfaces
u Java Only Allows One Superclass
u Provides A Cleaner Mechanism For
Multiple-Inheritance
– Less Complex Compiler
– More Efficient Compiler
u Interfaces Are Not Instantiated
u Allows Callback Functions To Be
Implemented
41
Object Wrappers
u Used To Make Basic Types Look Like
Objects
u Allows Basic Types To Be Used In Generic
Object Based Methods
42
The Class Class
u Used To Access Run Time Identification Information
u Use getClass() To Create Object Reference
u Useful Methods
– getName()
– getSuperclass()
– getInterfaces()
– isInterface()
– toString()
– forName()
43
Basics Of AWT
44
Components
u Most Basic AWT class
u Contains Most AWT Methods
– event handling
– Physical Dimensions
– Properties (font, colour, etc)
u Useful Methods
– paint()/repaint()
– getGraphics()
– setFont()/getFont()
45
Container
u Holds Other Components/Containers
u Subclassed From Component
u Subclasses:
– Panel
– Window
– Frame
– Dialog
u Uses a LayoutManager To Control Placement
46
Layout Managers
u FlowLayout
u BorderLayout
u CardLayout
u GridLayout
u GridBagLayout
47
FlowLayout
u Simplest Layout Manager (Default)
u Components Lined Up Horizontally
– End Of Line Starts New One
u Alignment Choices
– CENTER (Default)
– LEFT
– RIGHT
48
BorderLayout
u Allows Five Components To Be Placed In
Fixed Relative Positions
u Components May Themselves Be Containers
North
CenterWest East
South
49
CardLayout
u Allows For Flipping Between Components
u Look & Feel Is Not Ideal
50
GridLayout
u Lays Out A Grid Of Locations
u Grid Width & Height Set At Creation Time
u All Components Are The Same Size
u Useful For Organising Parts Of A Window
51
GridBagLayout
u Grid Style Layout For Different Sized Components
u Constraint Properties Used To Define Layout
– gridx, gridy Start Point Of Component
– gridwidth, gridheight Size Of Component
– weightx, weighty Distribution Of Resize
u Rows & Columns Calculated Automagically
52
Events
u Used To Detect When Things Happen
– Key press, Mouse Button/Move
– Component Get/Lose Focus
– Scrolling Up/Down
– Window Iconify/Move etc
u Processed By
– HandleEvent() and action() (JDK 1.0)
– Event Delegation (JDK1.1)
53
Delegation Event Model
u New For JDK 1.1
u HandleEvent() & action() Can Get Messy
– Too Many Subclasses
– Too Much in Specific Methods
u New Model Uses
– Event Source
– Event Listener
– Event Adapters
54
Delegation Event Model
Advantages
u Application Logic Separated From GUI
– Allows GUI To Be Replaced Easily
u No Subclassing Of AWT Components
– Reduced Code Complexity
u Only Action Events Delivered To Program
– Improved Performance
55
Menus
u Used With Separate Frame Object
u Supports Cascading Menus
u Supports Tear-Off Menus
u Supports Checkboxes (CheckboxMenuItem)
u Menu Objects Attached To Menu Bar
u MenuItem Objects Attached To Menus
u Menu Events Carry The MenuItem Label
56
Scrolling Lists
u Simple Scrolling List Of String Objects
– Vertical & Horizontal Scroll Bars
u Supports Multiple Selections
u Uses Specific Event Types
– LIST_SELECT
– LIST_DESELECT
u Use getSelectedItems() To Get Strings
57
Dialog Box
u Provides User Interaction in Separate
Window
u Can Be Non-Resizable
u Modal - User Must Respond To Dialog
Before Continuing
u Modeless - User May Continue Without
Interacting With Dialog Box
u Use Dialog Object
58
Images
u Applets use Applet.getImage()
u Applications Use Toolkit.getImage()
u Most Image Methods Use ImageObserver()
– Not Normally Used Directly
– Use MediaTracker
u Simple Methods
– getGraphics() Returns Graphics Object For
Drawing
– getHeight()/getWidth() Return Parameters
59
The Media Tracker
u Allows Applet Thread To Wait For Images To
Load
u MediaTracker Object Can Optionally Timeout
u Can Detect Stages Of Image Loading
– Image Size Determined
– Pieces Of Image Downloaded
– Image Loading Complete
60
Animation
u Very Simple In Java
u Download Sequence Of Images Into Array
img[j] = getImage(“images/T1.gif”);
u Loop Through Array Calling Paint() With
Appropiate Image
public void paint(Graphics g)
{
g.drawImage(img[j], x, y, this);
}
61
Programming Hints & Tips
u CLASSPATH Variable
u One Public Class Per Source File
u Screen Flicker - Override update() Method
u Use Vector Class for Linked Lists
u Mouse Buttons
– ALT_MASK Middle Button
– META_MASK Right Hand Button
62
Demonstration
Java Workshop
63
Where Next?
u Web Sites
– java.sun.com
– java.sun.com/products/jdk/1.1 (Free Download!)
– kona.lotus.com
u Tools
– www.sun.com/workshop/index.html
u Books
– Core Java 2nd Ed, Gary Cornell & Cay S. Horstmann
u Training Courses
– www.sun.com/sunservice/suned
64
Questions
&
Answers
Ad

More Related Content

What's hot (20)

Java Garbage Collection, Monitoring, and Tuning
Java Garbage Collection, Monitoring, and TuningJava Garbage Collection, Monitoring, and Tuning
Java Garbage Collection, Monitoring, and Tuning
Carol McDonald
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
Knoldus Inc.
 
An Introduction to RxJava
An Introduction to RxJavaAn Introduction to RxJava
An Introduction to RxJava
Sanjay Acharya
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for Android
Tomáš Kypta
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for Android
Tomáš Kypta
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
Carol McDonald
 
RxJava for Android - GDG DevFest Ukraine 2015
RxJava for Android - GDG DevFest Ukraine 2015RxJava for Android - GDG DevFest Ukraine 2015
RxJava for Android - GDG DevFest Ukraine 2015
Constantine Mars
 
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Carol McDonald
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
Ram132
 
Moving Towards JDK 12
Moving Towards JDK 12Moving Towards JDK 12
Moving Towards JDK 12
Simon Ritter
 
Java Lab Manual
Java Lab ManualJava Lab Manual
Java Lab Manual
Naveen Sagayaselvaraj
 
LogicObjects
LogicObjectsLogicObjects
LogicObjects
Sergio Castro
 
Reactive Android: RxJava and beyond
Reactive Android: RxJava and beyondReactive Android: RxJava and beyond
Reactive Android: RxJava and beyond
Fabio Tiriticco
 
Re-engineering Eclipse MDT/OCL for Xtext
Re-engineering Eclipse MDT/OCL for XtextRe-engineering Eclipse MDT/OCL for Xtext
Re-engineering Eclipse MDT/OCL for Xtext
Edward Willink
 
Pattern Matching in Java 14
Pattern Matching in Java 14Pattern Matching in Java 14
Pattern Matching in Java 14
GlobalLogic Ukraine
 
Introduction to rx java for android
Introduction to rx java for androidIntroduction to rx java for android
Introduction to rx java for android
Esa Firman
 
Generics Past, Present and Future
Generics Past, Present and FutureGenerics Past, Present and Future
Generics Past, Present and Future
RichardWarburton
 
(chapter 5) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 5) A Concise and Practical Introduction to Programming Algorithms in...(chapter 5) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 5) A Concise and Practical Introduction to Programming Algorithms in...
Frank Nielsen
 
RxJava 2.0 介紹
RxJava 2.0 介紹RxJava 2.0 介紹
RxJava 2.0 介紹
Kros Huang
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
Tomáš Kypta
 
Java Garbage Collection, Monitoring, and Tuning
Java Garbage Collection, Monitoring, and TuningJava Garbage Collection, Monitoring, and Tuning
Java Garbage Collection, Monitoring, and Tuning
Carol McDonald
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
Knoldus Inc.
 
An Introduction to RxJava
An Introduction to RxJavaAn Introduction to RxJava
An Introduction to RxJava
Sanjay Acharya
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for Android
Tomáš Kypta
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for Android
Tomáš Kypta
 
RxJava for Android - GDG DevFest Ukraine 2015
RxJava for Android - GDG DevFest Ukraine 2015RxJava for Android - GDG DevFest Ukraine 2015
RxJava for Android - GDG DevFest Ukraine 2015
Constantine Mars
 
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Carol McDonald
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
Ram132
 
Moving Towards JDK 12
Moving Towards JDK 12Moving Towards JDK 12
Moving Towards JDK 12
Simon Ritter
 
Reactive Android: RxJava and beyond
Reactive Android: RxJava and beyondReactive Android: RxJava and beyond
Reactive Android: RxJava and beyond
Fabio Tiriticco
 
Re-engineering Eclipse MDT/OCL for Xtext
Re-engineering Eclipse MDT/OCL for XtextRe-engineering Eclipse MDT/OCL for Xtext
Re-engineering Eclipse MDT/OCL for Xtext
Edward Willink
 
Introduction to rx java for android
Introduction to rx java for androidIntroduction to rx java for android
Introduction to rx java for android
Esa Firman
 
Generics Past, Present and Future
Generics Past, Present and FutureGenerics Past, Present and Future
Generics Past, Present and Future
RichardWarburton
 
(chapter 5) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 5) A Concise and Practical Introduction to Programming Algorithms in...(chapter 5) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 5) A Concise and Practical Introduction to Programming Algorithms in...
Frank Nielsen
 
RxJava 2.0 介紹
RxJava 2.0 介紹RxJava 2.0 介紹
RxJava 2.0 介紹
Kros Huang
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
Tomáš Kypta
 

Similar to Java Programming (20)

L04 Software Design Examples
L04 Software Design ExamplesL04 Software Design Examples
L04 Software Design Examples
Ólafur Andri Ragnarsson
 
Modern_Java_Workshop manjunath np hj slave
Modern_Java_Workshop manjunath np hj slaveModern_Java_Workshop manjunath np hj slave
Modern_Java_Workshop manjunath np hj slave
gangadharnp111
 
02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt
Yonas D. Ebren
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
BG Java EE Course
 
L04 Software Design 2
L04 Software Design 2L04 Software Design 2
L04 Software Design 2
Ólafur Andri Ragnarsson
 
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_types
Abed Bukhari
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
Gousalya Ramachandran
 
2java Oop
2java Oop2java Oop
2java Oop
Adil Jafri
 
Ifi7184 lesson3
Ifi7184 lesson3Ifi7184 lesson3
Ifi7184 lesson3
Sónia
 
Building Single-Page Web Appplications in dart - Devoxx France 2013
Building Single-Page Web Appplications in dart - Devoxx France 2013Building Single-Page Web Appplications in dart - Devoxx France 2013
Building Single-Page Web Appplications in dart - Devoxx France 2013
yohanbeschi
 
9781439035665 ppt ch08
9781439035665 ppt ch089781439035665 ppt ch08
9781439035665 ppt ch08
Terry Yoast
 
Core java
Core javaCore java
Core java
kasaragaddaslide
 
Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basics
LovelitJose
 
Classes1
Classes1Classes1
Classes1
phanleson
 
Java Basics
Java BasicsJava Basics
Java Basics
Rajkattamuri
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features Summary
Amal Khailtash
 
CORE JAVA PPT FOR ENGINEERS BBBBBBBBBBBBBBBBBBB
CORE JAVA PPT FOR ENGINEERS  BBBBBBBBBBBBBBBBBBBCORE JAVA PPT FOR ENGINEERS  BBBBBBBBBBBBBBBBBBB
CORE JAVA PPT FOR ENGINEERS BBBBBBBBBBBBBBBBBBB
NagarathnaRajur2
 
Unit 1: Primitive Types - Variables and Datatypes
Unit 1: Primitive Types - Variables and DatatypesUnit 1: Primitive Types - Variables and Datatypes
Unit 1: Primitive Types - Variables and Datatypes
agautham211
 
Jacarashed-1746968053-300050282-Java.ppt
Jacarashed-1746968053-300050282-Java.pptJacarashed-1746968053-300050282-Java.ppt
Jacarashed-1746968053-300050282-Java.ppt
DilipDas70
 
14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining Classes
Intro C# Book
 
Modern_Java_Workshop manjunath np hj slave
Modern_Java_Workshop manjunath np hj slaveModern_Java_Workshop manjunath np hj slave
Modern_Java_Workshop manjunath np hj slave
gangadharnp111
 
02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt
Yonas D. Ebren
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
BG Java EE Course
 
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_types
Abed Bukhari
 
Ifi7184 lesson3
Ifi7184 lesson3Ifi7184 lesson3
Ifi7184 lesson3
Sónia
 
Building Single-Page Web Appplications in dart - Devoxx France 2013
Building Single-Page Web Appplications in dart - Devoxx France 2013Building Single-Page Web Appplications in dart - Devoxx France 2013
Building Single-Page Web Appplications in dart - Devoxx France 2013
yohanbeschi
 
9781439035665 ppt ch08
9781439035665 ppt ch089781439035665 ppt ch08
9781439035665 ppt ch08
Terry Yoast
 
Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basics
LovelitJose
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features Summary
Amal Khailtash
 
CORE JAVA PPT FOR ENGINEERS BBBBBBBBBBBBBBBBBBB
CORE JAVA PPT FOR ENGINEERS  BBBBBBBBBBBBBBBBBBBCORE JAVA PPT FOR ENGINEERS  BBBBBBBBBBBBBBBBBBB
CORE JAVA PPT FOR ENGINEERS BBBBBBBBBBBBBBBBBBB
NagarathnaRajur2
 
Unit 1: Primitive Types - Variables and Datatypes
Unit 1: Primitive Types - Variables and DatatypesUnit 1: Primitive Types - Variables and Datatypes
Unit 1: Primitive Types - Variables and Datatypes
agautham211
 
Jacarashed-1746968053-300050282-Java.ppt
Jacarashed-1746968053-300050282-Java.pptJacarashed-1746968053-300050282-Java.ppt
Jacarashed-1746968053-300050282-Java.ppt
DilipDas70
 
14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining Classes
Intro C# Book
 
Ad

More from Simon Ritter (20)

Java Pattern Puzzles Java Pattern Puzzles
Java Pattern Puzzles Java Pattern PuzzlesJava Pattern Puzzles Java Pattern Puzzles
Java Pattern Puzzles Java Pattern Puzzles
Simon Ritter
 
Keeping Your Java Hot by Solving the JVM Warmup Problem
Keeping Your Java Hot by Solving the JVM Warmup ProblemKeeping Your Java Hot by Solving the JVM Warmup Problem
Keeping Your Java Hot by Solving the JVM Warmup Problem
Simon Ritter
 
Cloud Native Compiler
Cloud Native CompilerCloud Native Compiler
Cloud Native Compiler
Simon Ritter
 
Java On CRaC
Java On CRaCJava On CRaC
Java On CRaC
Simon Ritter
 
The Art of Java Type Patterns
The Art of Java Type PatternsThe Art of Java Type Patterns
The Art of Java Type Patterns
Simon Ritter
 
Java performance monitoring
Java performance monitoringJava performance monitoring
Java performance monitoring
Simon Ritter
 
Modern Java Workshop
Modern Java WorkshopModern Java Workshop
Modern Java Workshop
Simon Ritter
 
Getting the Most From Modern Java
Getting the Most From Modern JavaGetting the Most From Modern Java
Getting the Most From Modern Java
Simon Ritter
 
Building a Better JVM
Building a Better JVMBuilding a Better JVM
Building a Better JVM
Simon Ritter
 
Java after 8
Java after 8Java after 8
Java after 8
Simon Ritter
 
How to Choose a JDK
How to Choose a JDKHow to Choose a JDK
How to Choose a JDK
Simon Ritter
 
The Latest in Enterprise JavaBeans Technology
The Latest in Enterprise JavaBeans TechnologyThe Latest in Enterprise JavaBeans Technology
The Latest in Enterprise JavaBeans Technology
Simon Ritter
 
Developing Enterprise Applications Using Java Technology
Developing Enterprise Applications Using Java TechnologyDeveloping Enterprise Applications Using Java Technology
Developing Enterprise Applications Using Java Technology
Simon Ritter
 
Is Java Still Free?
Is Java Still Free?Is Java Still Free?
Is Java Still Free?
Simon Ritter
 
Java Is Still Free
Java Is Still FreeJava Is Still Free
Java Is Still Free
Simon Ritter
 
JDK 9, 10, 11 and Beyond
JDK 9, 10, 11 and BeyondJDK 9, 10, 11 and Beyond
JDK 9, 10, 11 and Beyond
Simon Ritter
 
JDK 9 and JDK 10 Deep Dive
JDK 9 and JDK 10 Deep DiveJDK 9 and JDK 10 Deep Dive
JDK 9 and JDK 10 Deep Dive
Simon Ritter
 
JDK 9 Deep Dive
JDK 9 Deep DiveJDK 9 Deep Dive
JDK 9 Deep Dive
Simon Ritter
 
Java Support: What's changing
Java Support:  What's changingJava Support:  What's changing
Java Support: What's changing
Simon Ritter
 
JDK 9: The Start of a New Future for Java
JDK 9: The Start of a New Future for JavaJDK 9: The Start of a New Future for Java
JDK 9: The Start of a New Future for Java
Simon Ritter
 
Java Pattern Puzzles Java Pattern Puzzles
Java Pattern Puzzles Java Pattern PuzzlesJava Pattern Puzzles Java Pattern Puzzles
Java Pattern Puzzles Java Pattern Puzzles
Simon Ritter
 
Keeping Your Java Hot by Solving the JVM Warmup Problem
Keeping Your Java Hot by Solving the JVM Warmup ProblemKeeping Your Java Hot by Solving the JVM Warmup Problem
Keeping Your Java Hot by Solving the JVM Warmup Problem
Simon Ritter
 
Cloud Native Compiler
Cloud Native CompilerCloud Native Compiler
Cloud Native Compiler
Simon Ritter
 
The Art of Java Type Patterns
The Art of Java Type PatternsThe Art of Java Type Patterns
The Art of Java Type Patterns
Simon Ritter
 
Java performance monitoring
Java performance monitoringJava performance monitoring
Java performance monitoring
Simon Ritter
 
Modern Java Workshop
Modern Java WorkshopModern Java Workshop
Modern Java Workshop
Simon Ritter
 
Getting the Most From Modern Java
Getting the Most From Modern JavaGetting the Most From Modern Java
Getting the Most From Modern Java
Simon Ritter
 
Building a Better JVM
Building a Better JVMBuilding a Better JVM
Building a Better JVM
Simon Ritter
 
How to Choose a JDK
How to Choose a JDKHow to Choose a JDK
How to Choose a JDK
Simon Ritter
 
The Latest in Enterprise JavaBeans Technology
The Latest in Enterprise JavaBeans TechnologyThe Latest in Enterprise JavaBeans Technology
The Latest in Enterprise JavaBeans Technology
Simon Ritter
 
Developing Enterprise Applications Using Java Technology
Developing Enterprise Applications Using Java TechnologyDeveloping Enterprise Applications Using Java Technology
Developing Enterprise Applications Using Java Technology
Simon Ritter
 
Is Java Still Free?
Is Java Still Free?Is Java Still Free?
Is Java Still Free?
Simon Ritter
 
Java Is Still Free
Java Is Still FreeJava Is Still Free
Java Is Still Free
Simon Ritter
 
JDK 9, 10, 11 and Beyond
JDK 9, 10, 11 and BeyondJDK 9, 10, 11 and Beyond
JDK 9, 10, 11 and Beyond
Simon Ritter
 
JDK 9 and JDK 10 Deep Dive
JDK 9 and JDK 10 Deep DiveJDK 9 and JDK 10 Deep Dive
JDK 9 and JDK 10 Deep Dive
Simon Ritter
 
Java Support: What's changing
Java Support:  What's changingJava Support:  What's changing
Java Support: What's changing
Simon Ritter
 
JDK 9: The Start of a New Future for Java
JDK 9: The Start of a New Future for JavaJDK 9: The Start of a New Future for Java
JDK 9: The Start of a New Future for Java
Simon Ritter
 
Ad

Recently uploaded (20)

Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World ExamplesMastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
jamescantor38
 
Best HR and Payroll Software in Bangladesh - accordHRM
Best HR and Payroll Software in Bangladesh - accordHRMBest HR and Payroll Software in Bangladesh - accordHRM
Best HR and Payroll Software in Bangladesh - accordHRM
accordHRM
 
How to Troubleshoot 9 Types of OutOfMemoryError
How to Troubleshoot 9 Types of OutOfMemoryErrorHow to Troubleshoot 9 Types of OutOfMemoryError
How to Troubleshoot 9 Types of OutOfMemoryError
Tier1 app
 
Mobile Application Developer Dubai | Custom App Solutions by Ajath
Mobile Application Developer Dubai | Custom App Solutions by AjathMobile Application Developer Dubai | Custom App Solutions by Ajath
Mobile Application Developer Dubai | Custom App Solutions by Ajath
Ajath Infotech Technologies LLC
 
Orion Context Broker introduction 20250509
Orion Context Broker introduction 20250509Orion Context Broker introduction 20250509
Orion Context Broker introduction 20250509
Fermin Galan
 
Wilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For WindowsWilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For Windows
Google
 
Unit Two - Java Architecture and OOPS
Unit Two  -   Java Architecture and OOPSUnit Two  -   Java Architecture and OOPS
Unit Two - Java Architecture and OOPS
Nabin Dhakal
 
Solar-wind hybrid engery a system sustainable power
Solar-wind  hybrid engery a system sustainable powerSolar-wind  hybrid engery a system sustainable power
Solar-wind hybrid engery a system sustainable power
bhoomigowda12345
 
Adobe InDesign Crack FREE Download 2025 link
Adobe InDesign Crack FREE Download 2025 linkAdobe InDesign Crack FREE Download 2025 link
Adobe InDesign Crack FREE Download 2025 link
mahmadzubair09
 
NYC ACE 08-May-2025-Combined Presentation.pdf
NYC ACE 08-May-2025-Combined Presentation.pdfNYC ACE 08-May-2025-Combined Presentation.pdf
NYC ACE 08-May-2025-Combined Presentation.pdf
AUGNYC
 
The-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptx
The-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptxThe-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptx
The-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptx
james brownuae
 
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdfTop Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
evrigsolution
 
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
OnePlan Solutions
 
Exchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv SoftwareExchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv Software
Shoviv Software
 
Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025
GrapesTech Solutions
 
From Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
From Vibe Coding to Vibe Testing - Complete PowerPoint PresentationFrom Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
From Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
Shay Ginsbourg
 
Medical Device Cybersecurity Threat & Risk Scoring
Medical Device Cybersecurity Threat & Risk ScoringMedical Device Cybersecurity Threat & Risk Scoring
Medical Device Cybersecurity Threat & Risk Scoring
ICS
 
Time Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project TechniquesTime Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project Techniques
Livetecs LLC
 
sequencediagrams.pptx software Engineering
sequencediagrams.pptx software Engineeringsequencediagrams.pptx software Engineering
sequencediagrams.pptx software Engineering
aashrithakondapalli8
 
Passive House Canada Conference 2025 Presentation [Final]_v4.ppt
Passive House Canada Conference 2025 Presentation [Final]_v4.pptPassive House Canada Conference 2025 Presentation [Final]_v4.ppt
Passive House Canada Conference 2025 Presentation [Final]_v4.ppt
IES VE
 
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World ExamplesMastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
jamescantor38
 
Best HR and Payroll Software in Bangladesh - accordHRM
Best HR and Payroll Software in Bangladesh - accordHRMBest HR and Payroll Software in Bangladesh - accordHRM
Best HR and Payroll Software in Bangladesh - accordHRM
accordHRM
 
How to Troubleshoot 9 Types of OutOfMemoryError
How to Troubleshoot 9 Types of OutOfMemoryErrorHow to Troubleshoot 9 Types of OutOfMemoryError
How to Troubleshoot 9 Types of OutOfMemoryError
Tier1 app
 
Mobile Application Developer Dubai | Custom App Solutions by Ajath
Mobile Application Developer Dubai | Custom App Solutions by AjathMobile Application Developer Dubai | Custom App Solutions by Ajath
Mobile Application Developer Dubai | Custom App Solutions by Ajath
Ajath Infotech Technologies LLC
 
Orion Context Broker introduction 20250509
Orion Context Broker introduction 20250509Orion Context Broker introduction 20250509
Orion Context Broker introduction 20250509
Fermin Galan
 
Wilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For WindowsWilcom Embroidery Studio Crack 2025 For Windows
Wilcom Embroidery Studio Crack 2025 For Windows
Google
 
Unit Two - Java Architecture and OOPS
Unit Two  -   Java Architecture and OOPSUnit Two  -   Java Architecture and OOPS
Unit Two - Java Architecture and OOPS
Nabin Dhakal
 
Solar-wind hybrid engery a system sustainable power
Solar-wind  hybrid engery a system sustainable powerSolar-wind  hybrid engery a system sustainable power
Solar-wind hybrid engery a system sustainable power
bhoomigowda12345
 
Adobe InDesign Crack FREE Download 2025 link
Adobe InDesign Crack FREE Download 2025 linkAdobe InDesign Crack FREE Download 2025 link
Adobe InDesign Crack FREE Download 2025 link
mahmadzubair09
 
NYC ACE 08-May-2025-Combined Presentation.pdf
NYC ACE 08-May-2025-Combined Presentation.pdfNYC ACE 08-May-2025-Combined Presentation.pdf
NYC ACE 08-May-2025-Combined Presentation.pdf
AUGNYC
 
The-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptx
The-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptxThe-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptx
The-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptx
james brownuae
 
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdfTop Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
evrigsolution
 
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
OnePlan Solutions
 
Exchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv SoftwareExchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv Software
Shoviv Software
 
Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025Top 12 Most Useful AngularJS Development Tools to Use in 2025
Top 12 Most Useful AngularJS Development Tools to Use in 2025
GrapesTech Solutions
 
From Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
From Vibe Coding to Vibe Testing - Complete PowerPoint PresentationFrom Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
From Vibe Coding to Vibe Testing - Complete PowerPoint Presentation
Shay Ginsbourg
 
Medical Device Cybersecurity Threat & Risk Scoring
Medical Device Cybersecurity Threat & Risk ScoringMedical Device Cybersecurity Threat & Risk Scoring
Medical Device Cybersecurity Threat & Risk Scoring
ICS
 
Time Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project TechniquesTime Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project Techniques
Livetecs LLC
 
sequencediagrams.pptx software Engineering
sequencediagrams.pptx software Engineeringsequencediagrams.pptx software Engineering
sequencediagrams.pptx software Engineering
aashrithakondapalli8
 
Passive House Canada Conference 2025 Presentation [Final]_v4.ppt
Passive House Canada Conference 2025 Presentation [Final]_v4.pptPassive House Canada Conference 2025 Presentation [Final]_v4.ppt
Passive House Canada Conference 2025 Presentation [Final]_v4.ppt
IES VE
 

Java Programming

  • 1. 1
  • 3. 3 Agenda u Java Language Syntax u Objects The Java Way u Basics Of AWT u Java Hints & Tips u Demonstration u Where Next?
  • 5. 5 Comments u C Style /* Place a comment here */ u C++ Style // Place another comment here
  • 6. 6 Auto-Documenting Comments u javadoc utility part of JDK /** Documentation comment */ – @see [class] – @see [class]#[method] – @version [text] – @author [name] – @param [variable_name] [description] – @return [description] – @throws [class_name] [description]
  • 7. 7 Java Data Types u Primitive Types – byte 8 bit signed – short 16 bit signed – int 32 bit signed – long 64 bit signed – float 32 bit IEEE 754 – double 64 bit IEEE 754 – char 16 bit Unicode – boolean true or false u No Unsigned Numeric Types
  • 8. 8 Java Data Types u Reference Types – class – array – interface (cannot be instantiated)
  • 9. 9 Type Promotion/Coercion u Types Automatically Promoted – int + float Automatically Returns float u No Automatic Coercion float pi = 3.142; int whole_pi = pi; /* Compile Time Error */ int whole_pi = (int)pi; /* Success! */
  • 10. 10 Variables u Cannot Use Reserved Words For Variable Names u Variable Names Must: – Start With A Letter (‘A’-’Z’, ‘a’-’z’,’_’,’$’) (Can Use Unicode) – Be A Sequence Of Letters & Digits u Can Have Multiple Declarations – int I, j, k; u Constants Not Well Supported (Class Only)
  • 11. 11 Variable Assignment u Assignments Can Be Made With Declaration int I = 10; u char uses single quote, strings use double – Unicode can be specified with 4 byte hex number and u escape char CapitalA = `u0041`;
  • 12. 12 Variable Modifiers u static – Only One Occurrence For The Class – Can Be accessed Without Instantiating Class (Only If Class Variable) u transient – Do Not Need To Be Serialised u volatile – Do Not Need To Be Locked
  • 13. 13 Arrays u Arrays Are References To Objects u Subtely Different To ‘C’ int x[10]; x[1] = 42; /* Causes runtime nullPointer exception */ u Space Allocated With new – int[] scores; /* Brackets either place */ – results = new int[10]; – short errors[] = new short[8];
  • 14. 14 Arrays (Cont’d) u Can Create Multi-Dimensional Arrays u Can Create ‘Ragged’ Arrays u Space Freed When Last Reference Goes Out Of Scope
  • 15. 15 Operators u ! ~ ++ -- u * / % u + - u << >> >>> u < <= > >= u == != u & u ^ u | u && u || u = += -= *= /= %= &= |= ^= <<= >>= >>>=
  • 16. 16 Conditional Statements u Syntax if ( [test] ) { [action] } else { [action] } u Example: if (i == 10) { x = 4; y = 6; } else j = 1;
  • 17. 17 Determinate Loops u Syntax for ( [start]; [end]; [update] ) { [statement_block]; } u Example for (i = 0; i < 10; i++) x[i] = i;
  • 18. 18 Indeterminate Loops u Syntax 1: while ( [condition] ) { [statement_block] } u Syntax 2: do { [statement_block] } while ( [condition] );
  • 19. 19 Multiple Selections: Switch u Syntax: switch ( [variable] ) { case [value]: [statement_block]; break <label>; default: [statement_block]; }
  • 20. 20 Labeled Statement u Label Must Preceed Statement To Jump To u Label Must Be Followed By Colon (:) u Use break And continue With Label int i; i: for (i = start; i < max; i++) { int n = str.count, j = i, k = str.offset; while (n-- != 0) if (v[j++] != v2[k++]) continue i;
  • 21. 21 Java Memory Handling u Allocation – Use new with declaration u Deallocation – Handled Automatically By Garbage Collector » Background Thread – finalize Method » File Handles » Graphics Contexts
  • 22. 22 Error Handling In Java u Catching Exceptions u Syntax: try { [statement_block]; } catch ( [exception_type] ) { [statement_block]; } finally { [statement_block]; }
  • 23. 23 Returning Values u Use return Expression u If No Return Value Is Used Method Must Be Declared void u Don’t Get Confused By try/finally Blocks – finally Block Code Will Always Be executed Before The Return Of Control To The Invoking Method
  • 25. 25 Basic Java Objects u Syntax: class [name] extends [super] { [variables] name() {} /* Constructor */ [methods] }
  • 26. 26 Object Variables u Implicit Pointer To Object u Must Be Initialised (Unless Declared static) – Wombat fred; c = fred.colour(); WRONG – Wombat fred = new Wombat(); c = fred.colour(); RIGHT
  • 27. 27 Overloading (Ad-Hoc Polymorphism) u Methods Have The Same Name But Different Arguments (different ‘signature’) – setTime(short hour, short min, short sec) – setTime(short hour, short min) – setTime(short hour) u Java Uses Static Dispatch For Methods In The Same Class
  • 28. 28 Constructor Methods u Forces Initialisation Of The Object u Can Be Overloaded u Use super keyword for Superclass public Wombat(String name, int age) { super(name); /* Must be first line */ wombat_age = age; }
  • 29. 29 Destructor Methods u Use finalize() method u Used To Tidy Up Resources Not Tracked By Garbage Collector u Not Guaranteed To Be Called Until Garbage Collector Runs
  • 30. 30 Accessor/Mutator Methods u Mutator Methods – setProperty() u Accessor Methods – getProperty()
  • 31. 31 Scope Modifiers u public – Available To All, Outside Object u private – Only Available Inside Object u protected – Only Available To Sub-Classes u static – Does Not Depend On Instatiation Of Object
  • 32. 32 The this Object u Refers To The Current Instatiation Of This Object u Can Be Used In Constructor With Overloading Wombat(String name, int age) { Wombat_age = age; this(name); }
  • 33. 33 Packages u Provides Libraries Of Classes u Use package Keyword At Start Of Source u Use import Keyword To Use Classes import java.util.*; Date Today = new Date(); u Can Use Full Name (must be in CLASSPATH) Date Today = new java.util.Date(); u Source Files Can Only Have One Public Class
  • 34. 34 Inheritance/Subclasses u Allows Common Functionality To Be Reused u Subclasses Extend The Functionality Of The Super Class
  • 35. 35 The super Method u Refers To The Super-Class Of This Object u On It’s Own Will Call The Constructor For The Super Class – Call Must Be First Line Of Sub-Class Constructor u Can Be Used To Directly Call Methods Of The Super Class – super.setName(name);
  • 36. 36 The Cosmic Superclass u Object Class Is Ultimate Superclass u If No Super-Class Specified, Object Is Default u Has Useful Methods – getClass() – equals() – clone() – toString()
  • 37. 37 Polymorphism u Method Signature: – Name – Parameters u Used To Access Methods Defined In Super-Classes u Signatures Must Match To Be executed u A Method With The Same Signature Will Hide Those in Super Classes u Failure To Match Will Cause Compile Time Error
  • 38. 38 Final Classes u Use final Keyword u Used With class Prevents Inheritance u Used With Method Prevents Overriding u Two Reasons For Using final – Efficiency – Safety
  • 39. 39 Abstract Classes u Creates Placeholders For Methods u Classes With Abstract Methods Must Be Declared Abstract u Abstract Methods Must Be Defined in Sub-Classes
  • 40. 40 Interfaces u Java Only Allows One Superclass u Provides A Cleaner Mechanism For Multiple-Inheritance – Less Complex Compiler – More Efficient Compiler u Interfaces Are Not Instantiated u Allows Callback Functions To Be Implemented
  • 41. 41 Object Wrappers u Used To Make Basic Types Look Like Objects u Allows Basic Types To Be Used In Generic Object Based Methods
  • 42. 42 The Class Class u Used To Access Run Time Identification Information u Use getClass() To Create Object Reference u Useful Methods – getName() – getSuperclass() – getInterfaces() – isInterface() – toString() – forName()
  • 44. 44 Components u Most Basic AWT class u Contains Most AWT Methods – event handling – Physical Dimensions – Properties (font, colour, etc) u Useful Methods – paint()/repaint() – getGraphics() – setFont()/getFont()
  • 45. 45 Container u Holds Other Components/Containers u Subclassed From Component u Subclasses: – Panel – Window – Frame – Dialog u Uses a LayoutManager To Control Placement
  • 46. 46 Layout Managers u FlowLayout u BorderLayout u CardLayout u GridLayout u GridBagLayout
  • 47. 47 FlowLayout u Simplest Layout Manager (Default) u Components Lined Up Horizontally – End Of Line Starts New One u Alignment Choices – CENTER (Default) – LEFT – RIGHT
  • 48. 48 BorderLayout u Allows Five Components To Be Placed In Fixed Relative Positions u Components May Themselves Be Containers North CenterWest East South
  • 49. 49 CardLayout u Allows For Flipping Between Components u Look & Feel Is Not Ideal
  • 50. 50 GridLayout u Lays Out A Grid Of Locations u Grid Width & Height Set At Creation Time u All Components Are The Same Size u Useful For Organising Parts Of A Window
  • 51. 51 GridBagLayout u Grid Style Layout For Different Sized Components u Constraint Properties Used To Define Layout – gridx, gridy Start Point Of Component – gridwidth, gridheight Size Of Component – weightx, weighty Distribution Of Resize u Rows & Columns Calculated Automagically
  • 52. 52 Events u Used To Detect When Things Happen – Key press, Mouse Button/Move – Component Get/Lose Focus – Scrolling Up/Down – Window Iconify/Move etc u Processed By – HandleEvent() and action() (JDK 1.0) – Event Delegation (JDK1.1)
  • 53. 53 Delegation Event Model u New For JDK 1.1 u HandleEvent() & action() Can Get Messy – Too Many Subclasses – Too Much in Specific Methods u New Model Uses – Event Source – Event Listener – Event Adapters
  • 54. 54 Delegation Event Model Advantages u Application Logic Separated From GUI – Allows GUI To Be Replaced Easily u No Subclassing Of AWT Components – Reduced Code Complexity u Only Action Events Delivered To Program – Improved Performance
  • 55. 55 Menus u Used With Separate Frame Object u Supports Cascading Menus u Supports Tear-Off Menus u Supports Checkboxes (CheckboxMenuItem) u Menu Objects Attached To Menu Bar u MenuItem Objects Attached To Menus u Menu Events Carry The MenuItem Label
  • 56. 56 Scrolling Lists u Simple Scrolling List Of String Objects – Vertical & Horizontal Scroll Bars u Supports Multiple Selections u Uses Specific Event Types – LIST_SELECT – LIST_DESELECT u Use getSelectedItems() To Get Strings
  • 57. 57 Dialog Box u Provides User Interaction in Separate Window u Can Be Non-Resizable u Modal - User Must Respond To Dialog Before Continuing u Modeless - User May Continue Without Interacting With Dialog Box u Use Dialog Object
  • 58. 58 Images u Applets use Applet.getImage() u Applications Use Toolkit.getImage() u Most Image Methods Use ImageObserver() – Not Normally Used Directly – Use MediaTracker u Simple Methods – getGraphics() Returns Graphics Object For Drawing – getHeight()/getWidth() Return Parameters
  • 59. 59 The Media Tracker u Allows Applet Thread To Wait For Images To Load u MediaTracker Object Can Optionally Timeout u Can Detect Stages Of Image Loading – Image Size Determined – Pieces Of Image Downloaded – Image Loading Complete
  • 60. 60 Animation u Very Simple In Java u Download Sequence Of Images Into Array img[j] = getImage(“images/T1.gif”); u Loop Through Array Calling Paint() With Appropiate Image public void paint(Graphics g) { g.drawImage(img[j], x, y, this); }
  • 61. 61 Programming Hints & Tips u CLASSPATH Variable u One Public Class Per Source File u Screen Flicker - Override update() Method u Use Vector Class for Linked Lists u Mouse Buttons – ALT_MASK Middle Button – META_MASK Right Hand Button
  • 63. 63 Where Next? u Web Sites – java.sun.com – java.sun.com/products/jdk/1.1 (Free Download!) – kona.lotus.com u Tools – www.sun.com/workshop/index.html u Books – Core Java 2nd Ed, Gary Cornell & Cay S. Horstmann u Training Courses – www.sun.com/sunservice/suned
  翻译: