Weeks 1-2 Java Basics by ygq15756

VIEWS: 13 PAGES: 65

									CG0093: Application Design in Java


       Weeks 1-2: Java Basics
      Sajjad Shami
      Michael Brockway
      School of Computing, Engineering and Information Systems
      Northumbria University




                                   Java                          1
                          Java

1995 Sun Microsystems
 www.java.sun.com (several good tutorials)
J2SE: This module
J2EE      next term: CG0165
J2ME      Advanced Applications Development in Java




                        Java                          2
                     Java Facts
Object oriented
Simple
– Small language
– Easy OO use, error handling
Platform independent
–   PC
–   Unix
–   Handheld
–   Smartcard

                         Java     3
                      Java Facts…

Network centric
– Designed for network environment
Large number of libraries (Packages)
– Graphics
– Phone
– Database




                          Java         4
                 Topics (Weeks 1-2)
From Deitel & Deitel: Java HTP 6e
  Chapter 2 – Introduction to Java Applications
  Chapter 20 – Introduction to Java Applets
  Chapter 4 – Control Statements: Part 1
  Chapter 5 – Control Statements: Part 2
  Chapter 6 – Methods
  Chapter 29 – Strings and Characters
  Though not quite in that order
  Emphasising main points
                         Java                     5
           Applications and Applets
Applications
– Run under host OS
– Full access to system resources
Applets
– Run from within web page
– Limited access to system resources
– Typically small
System Resources vary
– Console input/output
– User Interface
                           Java        6
          Applications: Procedure

Write file say Example1.java that contains code
for class Example1
Compile as >javac Example1.java
– Statements terminate with a semi-colon
– // means line is a comment ( also /* ….*/ )
This will create bytecodes Example1.class
Execute by >java Example1
                       Java                     7
                      Example1.java
//Adding integers using DialogBox

import javax.swing.JOptionPane;

public class Example1 {
  public static void main (String args[])
  {
    String firstNumber = null,
           secondNumber = null;
    int n1 = 0,
        n2 = 0,
        sum = 0;

   firstNumber = JOptionPane.showInputDialog("Enter first
                                            integer");
   n1 = Integer.parseInt( firstNumber );

                             Java                           8
                     Example1.java …contd

   n2 = Integer.parseInt(JOptionPane.showInputDialog(
               "Enter second integer") );

    sum = n1 + n2;

    JOptionPane.showMessageDialog( null,
                    "The sum is: "+ n1 + "+" + n2 + " = " + sum,
                    "Equation",
      JOptionPane.PLAIN_MESSAGE );
  }
} // end Example1




                             Java                            9
                   Example1.java (again)
//Adding Integers using DialogBox
import javax.swing.JOptionPane;
public class Example1 {
  public static void main (String args[])
  {
    String firstNumber = null, secondNumber = null;
    int n1 = 0, n2 = 0, sum = 0;
    firstNumber = JOptionPane.showInputDialog("Enter first
                   integer");
    n1 = Integer.parseInt( firstNumber );
    n2 =Integer.parseInt(JOptionPane.showInputDialog("Enter
                    second integer"));
    sum = n1 + n2;
    JOptionPane.showMessageDialog(null,"The sum is: " +n1+
       "+" +n2+ "=" +sum,"Equation",JOptionPane.PLAIN_MESSAGE);
  }
}                             Java                          10
                                Style
Indent blocks {…}                     Be consistent
Line up { and }                       Easy to read (aids)
Split long lines                       – Maintenance
– One parameter per line                   • you may be some time before
                                             revisiting
– At “punctuation”                         • others may maintain
Remember ;                             – Use by others
Names                                      • extending
–   CapitaliseClasses                      • using from library
–   notFirstWordForVariables          Clarity
–   simple_data_types                 Good choice of names
–   CONSTANT_VALUES                    – describe meaning
                                       – don‟t abbreviate
                               Java                                   11
                             Starters
   Make library class available
              import javax.swing.JOptionPane;

• Declare class, note same name as file
              public class Example1 {

• Declare main function (entry point)
             public static void main ( String args[] )

• Declare and initialise variables
               String  firstNumber = null,
                      secondNumber = null;
               int n1 = 0,
                   n2 = 0,
                  sum = 0;
                                  Java                   12
                  Get data
  Get a string using library dialog box

 firstNumber =
     JOptionPane.showInputDialog(
               "Enter first integer"
     );



• Convert to Integer (another library class)

 n1 = Integer.parseInt( firstNumber );




                    Java                       13
                    Get data …
• get second number,


   • note how one method (function) can be
     parameter of second

       n2 =   Integer.parseInt(
               JOptionPane.
                showInputDialog(
                            "Enter second integer"
                                )
       );




                       Java                          14
                    Process and Output
 Process data
           sum = n1 + n2;


• Output results
        JOptionPane.showMessageDialog(
              null,
              "The sum is: "+
                    n1 + "+" + n2 +
                    " = " + sum,
              "Equation",
              JOptionPane.PLAIN_MESSAGE
        );

      Breaking between parameters and operators can aid clarity if
       done well…
                                 Java                                 15
                Built in Data types
  8 types
  Have wrapper class supplying utility functions
Type         Contents                  Size
boolean      true or false             1 bit
char         Unicode character         2 byte
byte         signed integer            1 byte
short        signed integer            2 byte
int          signed integer            4 byte
long         signed integer            8 byte
float        IEEE 754 floating point   4 byte
double       IEEE 754 floating point   8 byte
                              Java                 16
                      Operators (some)
operator                action                        associativity
++       --             increment decrement           rightleft

*    /        %         multiply division remainder   leftright


+    -                  addition subtraction          leftright

==        !=            equal not-equal               leftright

&    ^            |     AND XOR        OR             leftright
                        (bitwise)

&&                      AND (conditional)             leftright
||                      OR (conditional)
?:                      conditional ternary           rightleft
=                       assignment                    rightleft
*= /= %= += -=          assignment with operation

                                      Java                            17
                    Increments et.al.
 pre and post
        int   a,b,y,z;
                                a   =   4
        a =   b = 3;
                                b   =   4
        y =   z = 2;
                                y   =   3
        y =   a++;
                                z   =   4
        z =   ++b;


• assignment and operation
       int a,b,y,z;
       a = b = 3;
       y = z = 5;
                                y = 8
       y += a;
                                z = 2
       z %= b;

                         Java               18
                            Conditionals
                            And && Or ||
 Short-circuit evaluation         int a = 5, b = 6

  – evaluates left to right as far as needed to get result
• AND &&
                 a>=6 && b==6

      second test is not evaluated as false and anything is false
• OR ||
                a<=6 || b==6

      second test is not evaluated as true or anything is true

• be aware of side effects
                                         r = b==6 || ++a >= 42
      side effect of increment
                                  Java                               19
            Exercises Chapter 2

All examples in text
2.14
2.17
2.26
2.32




                       Java       20
                   Applets (Ch 20)
Java programs that can be embedded in HTML documents
(web pages)
When a browser loads a web page containing an applet, the
applet downloads into the browser and begins execution
J2SDK comes with appletviewer for testing applets before
embedding
                           > appletviewer example1.html


Three methods: init( ), paint( ) and start( )
.java and the .html files are usually stored in the same
directory
                           Java                            21
          Applets: Procedure
Write file SampleApplet.java
Also write file SampleApplet.html
In the same directory
> javac SampleApplet.java
– produces SampleApplet.class
> appletviewer SampleApplet.html


                  Java              22
         SampleApplet.java
//Class SampleApplet.java: displays two strings
import java.awt.Graphics;
import javax.swing.JApplet;

public class SampleApplet extends JApplet{
  public void paint ( Graphics g)
  {
    super.paint(g);
    g.drawString( “Welcome to”, 25, 25 );
    g.drawString( “Java Programing!”, 25, 40 );
  }
}




                   Java                           23
                   SampleApplet.html
//SampleApplet.html loads class SampleApplet into the appletviewer
<html>
<applet code = “SampleApplet.class” width = “300” height = “60” >
</applet>
</html>



        > appletviewer   SampleApplet.html




                                Java                         24
           Exercises Chapter 20

All examples in text
20.4
20.5
20.9




                       Java       25
        Control Structures (Ch 4 & 5)

Decision
Selection
Repetition
– counter
– logic test
   • top
   • bottom
Exits
                   Java                 26
                     if…then…else

                       if ( a==7 )
Simple decision          do_a();

else is optional       else
                         do_b();

                      if ( a==7 )
                        do_a();



• Ternary conditional operator
       s = a%2==0 ? "even" : "odd"

     evaluates to a value that can be assigned to a variable
                             Java                               27
               switch … selection
Must test integral type                    switch(a)
                                           {
byte, short, int, long                       case 1:
                                               do_this();
once matched falls through until             case 2:
break.                                       case 3:
                                               do_that();
default is optional                            break;
(but good practice)   a:
                                             case 4:
                                               do_then();
                      1.      this, that       break;
                      2.      that           default:
                                               do_other();
                      3.      that         }
                      4.      then
                      •       other
                       Java                                  28
                  while          and         do…while
 tests at TOP of loop                   while ( a<100 )
                                          a*=2;
       – loop may never
         execute
                                        do
tests at BOTTOM of loop                   a*=2;
       loop will execute once          while ( a<100 );




• Ensure loops terminate!

                                 Java                      29
                                 for
•      equivalent to…             for(int a=0 ; a<=10 ; ++a)
                                    b+=a;
      i. initialisation
      ii. test
                                  int a=0;
      iii. <body>                 while(a<=10)
      iv. increment               {
                                    b+=a;
                                    a++;
                                  }


    • be aware
        test occurs after increment and before

         next iteration!
                          Java                             30
                          for loops…
• counter controlled loops
      need not be simple increments
      can use complex tests
  for(
                                        A common idiom for
     Enumeration e=a.getElements();
                                        traversing sets of data
     e.hasMoreElements();
     e.nextElement()
                                        (Vector class)
  );

  for( int a=0,b=2; a<100; a*=2,b++ )   multiple counters and
                                        increments
  for( int a=1,b=1; b<=10; a*=++b )     geometric progression




                              Java                        31
                     Loop Exits
                  break and continue
                   line:
break              while(a>=1)
                   {
  exits loop         if (b==2) break;
continue             for(int c=10 ; c>0 ; c-=b)
                     {
  skips to next
                       if(b==c) continue;
     iteration         if(b==a) break line;
                       if(c%2==0) break;
                       b=a%4;
                     }
                     --a;
                   }


                         Java                     32
                Blocks and Scoping
“visibility”                      public class Scope {
                                    int a;
 of variables
– from declaration                    {
                                          int x;
– until end of enclosing block            /*
                     scope of a           */
                                      }
                     scope of x
                                      int b;
                                      for(int c=10;c>0;--c)
                     scope of b       {
                                        a ^= c/b;
                     scope of c       }

                                  }



                           Java                          33
                               Strings

 Are Objects not built-in types
  – are useful so a special case is made
  – anonymous strings
• Creation     String s = new String("some text");

• Joining (Concatenation)
                                  "some text"+" more text";


• Conversion from built-in types
      automatic      "value is..." + variableName + "km";

         done by calling the toString() method of the class

                               Java                            34
                        Packages
                          (libraries)
n2 = java.lang.Integer.parseInt(
            javax.swing.JOptionPane.showInputDialog(
                      "Enter second integer");


No import
 – Use full package path and class name
 – long winded
 – clear in context what class is


                           Java                        35
             Package: single class import
       import javax.swing.JOptionPane;

       n2 = Integer.parseInt(
       JOptionPane.showInputDialog(
       "Enter second integer"
       ));


Single class import
– import whole class
– use class name alone in code
– explicit what classes are used
    • at top of file
    • clear
    • easy maintained
                            Java            36
                  Package: Package import
                              import javax.swing.*;
Package import                public class Sample2 extends JApplet
                              {
–   makes all classes available
–   use class name                 JOptionPane. showInputDialog(   ...

–   easier to manage as class use increases
–   get “free”
     • java.lang.*
note: there is no overhead on the program code, the compiler
includes just those classes actually used.
good to import java.lang.* in any case.

                                Java                               37
         Exercises Chapter 4 & 5

All examples in text
4.17, 4.20, 4.22, 4.30
5.11, 5.17, 5.24




                     Java          38
                 Methods (functions)

Methods are the functions that form a Java program
– function is usually a term in non object-oriented programming
– method is the term in object-oriented programming
Already seen some of the predefined methods in
various Java library classes
– see Fig 6.2, page 235 Math class methods
How to define your own methods


                            Java                              39
                 Invocation of methods
  Anonymous
   – called from within same class as declaration

                            a = solve(f,g,"loose");


• Object
      called as a property of an existing object
                        d.drawString("Welcome...", 25, 25);
• Class
      called as a property of a class
       f = Math.sin( angle/3 );


                                Java                          40
                    The Anatomy of a Method
                                       public double cube( double x )
                                       {
                                         return x*x*x;
    Definition                         }

      – public double cube( double x )

visibility
     return type
                   method name
                                                 parameter list, type and name
 • body
            parameters are local variable
            non-void methods must have a return and a value
            can return from any point in a method
            good practice to use return in a void method
                                    Java                                    41
         An Aside – Type Casting
conversion between variable types
promotion
– automatic for built-in types as parameter or in expressions
   • float  double
   • long  float, double
   • int  long, float, double
   • char  int, long, float, double
   • short  int, long, float, double
   • byte  short, int, long, float, double
explicit cast
 – required where no promotion exists
    • (long)Math.exp(f);

                          Java                              42
                        Recursion
  Factorial
  – n! = n×(n-1)×(n-2)×…×2×1
• loop
         long factorial(long n){
           long f=1;
           for(long p=n;p>=1;p--)
             f*=p;
           return f;
         }

• recursive   long factorial(long n){
                if(n<=1)
                  return 1;
                else
                  return n * factorial( n-1 )
              }
                           Java                 43
                         Recursion…
Fibonacci series
– f(0) = 0                        • What would this be as a
  f(1) = 1                          for loop?
  f(n) = f(n-1)+f(n-2)
long fibonacci(long n)
{
  switch(n)
  {
    case 0:
    case 1:
      return n;
    default:
      return fibonacci(n-1) + fibonacci(n-2);
  }
}

                           Java                         44
               Method Overloading
A method may be given one or more definitions
 – example java.lang.String.indexOf
    • int   indexOf(int ch)
    • int   indexOf(int ch, int fromIndex)
    • int   indexOf(String str)
    • int   indexOf(String str, int fromIndex)
The compiler uses the supplied parameter list to select
which version to use.
– typically the simpler definitions call the others with default
  parameters
– e.g…           int indexOf(int ch)
                {
                    return this.indexOf(ch,0);
                }
                             Java                                  45
                     Extensions
                      public class Sample2
                        extends JApplet
                        implements Runnable, ActionListener
                      {

Extending a Class
– gain default methods for class
– may redefine override methods
   • overridden methods must be given the same declaration as in
     the parent class.
– additional methods may be added
   • e.g. Applet has
       – init(), start(), stop(), destroy()
   • override these to define the applet behaviour
                          Java                            46
                   Implementations
                      public class Sample2
                        extends JApplet
                        implements Runnable, ActionListener
                      {


Implementing an Interface
– Must provide an implementation of the defined methods
   • e.g. Runnable interface
        – run() provides the code that is the behaviour of the thread
    • e.g. ActionListener interface
        – actionPerformed (ActionEvent e) provides the code
          that responds to GUI events



                              Java                                 47
     Example: Casino game „Craps‟

Game of chance
Played by rolling two dice
Rules on p.250
Application code in Fig 6.9 simulates the game
of craps
Uses several methods to define the game‟s logic

                     Java                     48
                Craps.java (Applet version)
                                          import java.awt.*;
                                          import java.awt.event.*;
                                          import javax.swing.*;

   imports classes needed for Applet
       – awt – Container and FlowLayout
       – event – ActionListener and ActionEvent
       – swing – JApplet, JLabel, JButton, JTextField
 public class Craps extends JApplet implements ActionListener


• declares Applet
       extends JApplet – gains basic Applet behaviour
       implements ActionListener – responds to GUI events

                                Java                           49
                    Craps.java: JApplet
          final int WON = 0, LOST = 1, CONTINUE = 2;


  Initialise constants
   – the final qualifier indicates that these are constants, their
     value cannot be changed by the program.

           public void init()

• called when the Applet is loaded
      used to create the GUI and perform any other tasks needed
       in setting up the Applet to run.


                                Java                             50
                         Craps.java : GUI
          Container c = getContentPane();

    A Container is an AWT class into which GUI items
    are placed
    The getContentPane() method of the JApplet returns
    a reference to the Container that forms the Applet
    – note how the method becomes available by extending the
      JApplet class
          c.setLayout( new FlowLayout() );

• the setLayout() method of a Container is used.
•   a “new” FlowLayout is created and passed to the Container


                                  Java                          51
                          Craps.java: GUI bits
  create a new label and add it to the Container
 –       add() is a method defined in JApplet
  create a new text box               die1Label = new JLabel( "Die 1" );
 –       make it un-editable          c.add( die1Label );
 –       add it to the Applet         firstDie = new JTextField( 10 );
                                      firstDie.setEditable( false );
                                      c.add( firstDie );

• create a push button with a text label
• register a class to receive events from the button
        this refers to the Applet
        the class receiving events must implement an ActionListener.
• add it to the applet                roll = new JButton("Roll Dice" );
                                      roll.addActionListener( this );
                                      c.add( roll );
                                      Java                              52
                Craps.java: Events
    public void actionPerformed(ActionEvent e )

called by a GUI component when an event occurs, generated by
that component

the ActionEvent object passed to the method provides information
about the event and the object that generated it




                          Java                             53
           Exercises Chapter 6

All examples in text
6.8 – calculation
6.14 – loops
6.22 – multiple event sources
6.38 – calculation




                    Java         54
      Strings and Characters (Ch 29)
Constructors                 s1     =   new   String(   "Hello World" );
– String                     s2     =   new   String(   charArray);
                             s3     =   new   String(   byteArray);
– Byte and Char arrays       s4     =   new   String(   charArray, 2, 3);
     • with indexes          s5     =   new   String(   byteArray, 2, 3);

Once created the size (length) of a string is fixed
methods for                     int l = s1.length();
                                              char c = s2.charAt(5);
–   determining the length
–   extracting characters
–   comparisons
–   extracting sub-strings
–   changing the characters in the string
                             Java                                      55
                         Comparisons
 Methods compare strings using the value
 (ACSII/Unicode) of the characters
  – lexicographical comparison – case sensitive!
                              s1 = new String( "Hello" );
                              s1.equals("hello"); //false
                              s1.equalsIgnoreCase("hello");   //true


• compareTo() method returns
    0 if equal

    <0 if string is less than argument

    >0 if string is greater than argument

 Note: A<a
                                Java                           56
                       Comparing regions
                         s1 = new String( "Hello Worlds" );
                         s2 = new String( "world" );
                         s1.regionMatches(6, s2, 0, 5);//false
    Parameters
    1.   is position to start match at
    2.   is string to match
    3.   is position in parameter string to start at
    4.   number of characters to match
                         s1.regionMatches(true, 6, s2, 0, 5);//true

•    Optional first parameter
       true – match with case insensitivity
       false – match using case sensitive test
                                    Java                         57
                    A note on ==
The == test when applied to strings (or any Object)
does not test the value of the objects
It tests to see if the variables contain references to the
same object
Suppose          String s1 = new String("hello");

then
    s1 == "hello"

                 is FALSE, s1 is not the same object as “hello”




                           Java                              58
                                      ==

           Now if    String s1 = "hello";


              then   s1 == "hello"

                     is TRUE,
                     The compiler has reused the anonymous
                     string “hello” which s1 is a reference to
This test is very useful in handling events in an actionListener. A
test can be made to see who caused the event.

                                       if(e.getSource()==button)



                               Java                                59
                            Other methods
  These all create a new string object
  –    concatenating – joining strings
  –    to UPPER case
  –    to lower case
  –    trim – removes white space at beginning and end of strings
                            String s1 = new String(" Hello");
                            s1.concat(" World ");//" Hello World           "
                            s1.toUpperCase();     //" HELLO WORLD          "
                            s1.toLowerCase();     //" hello world          "
                            s1.trim();            //"hello world"
• Other tests
      startsWith('a') tests if string begins with char of string
      endsWith("sub") tests if string ends with char of string
      lastIndexOf('s') finds position working back down the string
       from the end
                                     Java                             60
                    StringBuffer
A StringBuffer can have its contents and size changed
– length() is the length of the current string
– capacity() is the length that can be stored without needing
  more memory
– append(String) joins the string to the end of the buffer,
  getting more memory if needed
– setLength(int) sets the length of the string, truncating if
  necessary
– insert(int, String) inserts the string at the index
– delete(int from, int to) deletes the sub-string from
  the first index, up to but not including the second
                         Java                          61
                             StringTokenizer
    A StringTokenizer splits a string into tokens
    – just as a sentence is split into words
  • creates a tokeniser for the sentence
  import java.lang.utils.StringTokenizer;

StringTokenizer st = new StringTokenizer("Some sentence or other“);



                                                  int count =
 • count() returns the number of tokens           st.countTokens();
 • The while loop shows how to work               while(st.hasMoreTokens())
                                                    st.nextToken();
   through the string extracting tokens in turn


                                       Java                             62
         StringTokenizer…
StringTokenizer st = new StringTokenizer(
   "Some sentence or other",
   ",.()-“
);



    The tokenizer uses whitespace. A
    second string can be used to define
    the splitting characters




                Java                        63
                                  Character tests
method                               test (true if)
isDigit()                            is a digit [0-9]
isDefined()                          is defined in the Unicode character set
isLetter()                           is a letter upper and lower case [a-z A-Z] and others
                                     (international character set)
isUpper()                            is an upper case letter
isLower()                            is a lower case letter
isJavaIdentifierStart()              is valid to start a Java identifier, class, method or
                                     variable name
isJavaIdentifierPart()               is valid to be in a Java identifier
         •and many others…
             the letter tests work with the Unicode set so they also test for
             Ù ù Â â æ etc…                   Java                                       64
                Exercises Chapter 29
All examples in text
29.3 compareTo
29.4 regionMatches
29.7 StringTokenizer
29.9 StringTokenizer
 – hint: try s = (String)st.nextToken().concat( s)
if time try
 – 29.8
 – 29.12
                               Java                  65

								
To top