Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Java Programming

614 views

Published on

A trip down memory lane with the first Java presentation I ever gave, all the way back in 1997.

Published in: Software
  • Be the first to comment

  • Be the first to like this

Java Programming

  1. 1. 1
  2. 2. 2 Java Programming Simon Ritter simon.ritter@uk.sun.com
  3. 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?
  4. 4. 4 Java Language Syntax
  5. 5. 5 Comments u C Style /* Place a comment here */ u C++ Style // Place another comment here
  6. 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. 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. 8 Java Data Types u Reference Types – class – array – interface (cannot be instantiated)
  9. 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. 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. 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. 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. 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. 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. 15 Operators u ! ~ ++ -- u * / % u + - u << >> >>> u < <= > >= u == != u & u ^ u | u && u || u = += -= *= /= %= &= |= ^= <<= >>= >>>=
  16. 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. 17 Determinate Loops u Syntax for ( [start]; [end]; [update] ) { [statement_block]; } u Example for (i = 0; i < 10; i++) x[i] = i;
  18. 18. 18 Indeterminate Loops u Syntax 1: while ( [condition] ) { [statement_block] } u Syntax 2: do { [statement_block] } while ( [condition] );
  19. 19. 19 Multiple Selections: Switch u Syntax: switch ( [variable] ) { case [value]: [statement_block]; break <label>; default: [statement_block]; }
  20. 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. 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. 22 Error Handling In Java u Catching Exceptions u Syntax: try { [statement_block]; } catch ( [exception_type] ) { [statement_block]; } finally { [statement_block]; }
  23. 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
  24. 24. 24 Objects The Java Way
  25. 25. 25 Basic Java Objects u Syntax: class [name] extends [super] { [variables] name() {} /* Constructor */ [methods] }
  26. 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. 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. 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. 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. 30 Accessor/Mutator Methods u Mutator Methods – setProperty() u Accessor Methods – getProperty()
  31. 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. 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. 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. 34 Inheritance/Subclasses u Allows Common Functionality To Be Reused u Subclasses Extend The Functionality Of The Super Class
  35. 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. 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. 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. 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. 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. 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. 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. 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. 43. 43 Basics Of AWT
  44. 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. 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. 46 Layout Managers u FlowLayout u BorderLayout u CardLayout u GridLayout u GridBagLayout
  47. 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. 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. 49 CardLayout u Allows For Flipping Between Components u Look & Feel Is Not Ideal
  50. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 62. 62 Demonstration Java Workshop
  63. 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
  64. 64. 64 Questions & Answers

×