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

More Related Content

What's hot (20)

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

Similar to Java Programming (20)

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

More from Simon Ritter (20)

PPTX
Java Pattern Puzzles Java Pattern Puzzles
Simon Ritter
 
PPTX
Keeping Your Java Hot by Solving the JVM Warmup Problem
Simon Ritter
 
PPTX
Cloud Native Compiler
Simon Ritter
 
PPTX
Java On CRaC
Simon Ritter
 
PPTX
The Art of Java Type Patterns
Simon Ritter
 
PPTX
Java performance monitoring
Simon Ritter
 
PPTX
Modern Java Workshop
Simon Ritter
 
PPTX
Getting the Most From Modern Java
Simon Ritter
 
PPTX
Building a Better JVM
Simon Ritter
 
PPTX
Java after 8
Simon Ritter
 
PPTX
How to Choose a JDK
Simon Ritter
 
PPTX
The Latest in Enterprise JavaBeans Technology
Simon Ritter
 
PPTX
Developing Enterprise Applications Using Java Technology
Simon Ritter
 
PPTX
Is Java Still Free?
Simon Ritter
 
PPTX
Java Is Still Free
Simon Ritter
 
PPTX
JDK 9, 10, 11 and Beyond
Simon Ritter
 
PPTX
JDK 9 and JDK 10 Deep Dive
Simon Ritter
 
PPTX
JDK 9 Deep Dive
Simon Ritter
 
PPTX
Java Support: What's changing
Simon Ritter
 
PPTX
JDK 9: The Start of a New Future for Java
Simon Ritter
 
Java Pattern Puzzles Java Pattern Puzzles
Simon Ritter
 
Keeping Your Java Hot by Solving the JVM Warmup Problem
Simon Ritter
 
Cloud Native Compiler
Simon Ritter
 
Java On CRaC
Simon Ritter
 
The Art of Java Type Patterns
Simon Ritter
 
Java performance monitoring
Simon Ritter
 
Modern Java Workshop
Simon Ritter
 
Getting the Most From Modern Java
Simon Ritter
 
Building a Better JVM
Simon Ritter
 
Java after 8
Simon Ritter
 
How to Choose a JDK
Simon Ritter
 
The Latest in Enterprise JavaBeans Technology
Simon Ritter
 
Developing Enterprise Applications Using Java Technology
Simon Ritter
 
Is Java Still Free?
Simon Ritter
 
Java Is Still Free
Simon Ritter
 
JDK 9, 10, 11 and Beyond
Simon Ritter
 
JDK 9 and JDK 10 Deep Dive
Simon Ritter
 
JDK 9 Deep Dive
Simon Ritter
 
Java Support: What's changing
Simon Ritter
 
JDK 9: The Start of a New Future for Java
Simon Ritter
 
Ad

Recently uploaded (20)

PPTX
How Apagen Empowered an EPC Company with Engineering ERP Software
SatishKumar2651
 
PDF
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
PPTX
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
 
PPTX
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
PPTX
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
PPTX
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
PPTX
MiniTool Power Data Recovery Full Crack Latest 2025
muhammadgurbazkhan
 
PDF
GetOnCRM Speeds Up Agentforce 3 Deployment for Enterprise AI Wins.pdf
GetOnCRM Solutions
 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
PPTX
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
PPT
MergeSortfbsjbjsfk sdfik k
RafishaikIT02044
 
PDF
Powering GIS with FME and VertiGIS - Peak of Data & AI 2025
Safe Software
 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
PDF
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PDF
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
DOCX
Import Data Form Excel to Tally Services
Tally xperts
 
PPTX
A Complete Guide to Salesforce SMS Integrations Build Scalable Messaging With...
360 SMS APP
 
PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
How Apagen Empowered an EPC Company with Engineering ERP Software
SatishKumar2651
 
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
 
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
MiniTool Power Data Recovery Full Crack Latest 2025
muhammadgurbazkhan
 
GetOnCRM Speeds Up Agentforce 3 Deployment for Enterprise AI Wins.pdf
GetOnCRM Solutions
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
MergeSortfbsjbjsfk sdfik k
RafishaikIT02044
 
Powering GIS with FME and VertiGIS - Peak of Data & AI 2025
Safe Software
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
Import Data Form Excel to Tally Services
Tally xperts
 
A Complete Guide to Salesforce SMS Integrations Build Scalable Messaging With...
360 SMS APP
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 

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