Weeks 1 2 java basics l.jpg
This presentation is the property of its rightful owner.
Sponsored Links
1 / 65

Weeks 1-2: Java Basics PowerPoint PPT Presentation


  • 159 Views
  • Uploaded on
  • Presentation posted in: General

CG0093: Application Design in Java. Weeks 1-2: Java Basics. Sajjad Shami Michael Brockway School of Computing, Engineering and Information Systems Northumbria University. Java . 1995 Sun Microsystems www.java.sun.com (several good tutorials) J2SE: This module

Download Presentation

Weeks 1-2: Java Basics

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


Weeks 1 2 java basics l.jpg

CG0093: Application Design in Java

Weeks 1-2: Java Basics

Sajjad Shami

Michael Brockway

School of Computing, Engineering and Information Systems

Northumbria University

Java


Slide2 l.jpg

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


Java facts l.jpg

Java Facts

  • Object oriented

  • Simple

    • Small language

    • Easy OO use, error handling

  • Platform independent

    • PC

    • Unix

    • Handheld

    • Smartcard

Java


Java facts4 l.jpg

Java Facts…

  • Network centric

    • Designed for network environment

  • Large number of libraries (Packages)

    • Graphics

    • Phone

    • Database

Java


Topics weeks 1 2 l.jpg

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


Applications and applets l.jpg

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


Applications procedure l.jpg

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


Example1 java l.jpg

//Adding integers using DialogBox

import javax.swing.JOptionPane;

publicclass Example1 {

publicstaticvoid 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 );

Example1.java

Java


Example1 java contd l.jpg

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


Example1 java again l.jpg

//Adding Integers using DialogBox

import javax.swing.JOptionPane;

publicclass Example1 {

publicstaticvoid 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);

}

}

Example1.java (again)

Java


Style l.jpg

Indent blocks {…}

Line up { and }

Split long lines

One parameter per line

At “punctuation”

Remember;

Names

CapitaliseClasses

notFirstWordForVariables

simple_data_types

CONSTANT_VALUES

Be consistent

Easy to read (aids)

Maintenance

you may be some time before revisiting

others may maintain

Use by others

extending

using from library

Clarity

Good choice of names

describe meaning

don’t abbreviate

Style

Java


Starters l.jpg

Starters

  • Make library class available

import javax.swing.JOptionPane;

  • Declare class, note same name as file

publicclass Example1 {

  • Declare main function (entry point)

publicstaticvoid main ( String args[] )

  • Declare and initialise variables

String firstNumber = null,

secondNumber = null;

int n1 = 0,

n2 = 0,

sum = 0;

Java


Get data l.jpg

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


Get data14 l.jpg

Get data …

  • get second number,

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

n2 = Integer.parseInt(

JOptionPane.

showInputDialog(

"Enter second integer"

)

);

Java


Process and output l.jpg

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


Built in data types l.jpg

Built in Data types

  • 8 types

  • Have wrapper class supplying utility functions

Java


Operators some l.jpg

Operators (some)

Java


Increments et al l.jpg

Increments et.al.

  • pre and post

int a,b,y,z;

a = b = 3;

y = z = 2;

y = a++;

z = ++b;

a = 4

b = 4

y = 3

z = 4

  • assignment and operation

int a,b,y,z;

a = b = 3;

y = z = 5;

y += a;

z %= b;

y = 8

z = 2

Java


Conditionals and or l.jpg

ConditionalsAnd && Or ||

  • Short-circuit evaluation

    • evaluates left to right as far as needed to get result

int a = 5, b = 6

  • 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


Exercises chapter 2 l.jpg

Exercises Chapter 2

  • All examples in text

  • 2.14

  • 2.17

  • 2.26

  • 2.32

Java


Applets ch 20 l.jpg

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

  • Three methods: init( ), paint( ) and start( )

  • .java and the .html files are usually stored in the same directory

> appletviewerexample1.html

Java


Applets procedure l.jpg

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


Sampleapplet java l.jpg

SampleApplet.java

//Class SampleApplet.java: displays two strings

import java.awt.Graphics;

import javax.swing.JApplet;

publicclass SampleApplet extends JApplet{

publicvoid paint ( Graphics g)

{

super.paint(g);

g.drawString( “Welcome to”, 25, 25 );

g.drawString( “Java Programing!”, 25, 40 );

}

}

Java


Sampleapplet html l.jpg

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


Exercises chapter 20 l.jpg

Exercises Chapter 20

  • All examples in text

  • 20.4

  • 20.5

  • 20.9

Java


Control structures ch 4 5 l.jpg

Control Structures (Ch 4 & 5)

  • Decision

  • Selection

  • Repetition

    • counter

    • logic test

      • top

      • bottom

  • Exits

Java


If then else l.jpg

if…then…else

  • Simple decision

  • else is optional

if ( a==7 )

do_a();

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


Switch selection l.jpg

switch … selection

switch(a)

{

case1:

do_this();

case2:

case3:

do_that();

break;

case4:

do_then();

break;

default:

do_other();

}

  • Must test integral typebyte, short, int, long

  • once matched falls through untilbreak.

  • default is optional(but good practice)

  • a:

  • this, that

  • that

  • that

  • then

  • other

Java


While and do while l.jpg

while and do…while

while ( a<100 )

a*=2;

tests at TOP of loop

  • loop may never execute

do

a*=2;

while ( a<100 );

  • tests at BOTTOM of loop

    • loop will execute once

  • Ensure loops terminate!

Java


Slide30 l.jpg

for

  • equivalent to…

    • initialisation

    • test

    • <body>

    • increment

for(int a=0 ; a<=10 ; ++a)

b+=a;

int a=0;

while(a<=10)

{

b+=a;

a++;

}

  • be aware

    • test occurs after increment and before next iteration!

Java


For loops l.jpg

for loops…

  • counter controlled loops

    • need not be simple increments

    • can use complex tests

for(

Enumeration e=a.getElements();

e.hasMoreElements();

e.nextElement()

);

A common idiom for traversing sets of data (Vector class)

multiple counters and increments

for( int a=0,b=2; a<100; a*=2,b++ )

for( int a=1,b=1; b<=10; a*=++b )

geometric progression

Java


Loop exits break and continue l.jpg

Loop Exitsbreak and continue

line:

while(a>=1)

{

if (b==2) break;

for(int c=10 ; c>0 ; c-=b)

{

if(b==c) continue;

if(b==a) break line;

if(c%2==0) break;

b=a%4;

}

--a;

}

break

exits loop

continue

skips to next iteration

Java


Blocks and scoping l.jpg

Blocks and Scoping

publicclass Scope {

int a;

{

int x;

/*

*/

}

int b;

for(int c=10;c>0;--c)

{

a ^= c/b;

}

}

  • “visibility” of variables

    • from declaration

    • until end of enclosing block

scope of a

scope of x

scope of b

scope of c

Java


Strings l.jpg

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


Packages libraries l.jpg

Packages(libraries)

  • No import

    • Use full package path and class name

    • long winded

    • clear in context what class is

n2 = java.lang.Integer.parseInt(

javax.swing.JOptionPane.showInputDialog(

"Enter second integer");

Java


Package single class import l.jpg

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


Package package import l.jpg

Package: Package import

import javax.swing.*;

publicclass Sample2 extends JApplet

{

JOptionPane. showInputDialog( ...

  • Package import

    • makes all classes available

    • use class name

    • 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


Exercises chapter 4 5 l.jpg

Exercises Chapter 4 & 5

  • All examples in text

  • 4.17, 4.20, 4.22, 4.30

  • 5.11, 5.17, 5.24

Java


Methods functions l.jpg

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


Invocation of methods l.jpg

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


The anatomy of a method l.jpg

The Anatomy of a Method

publicdouble cube( double x )

{

return x*x*x;

}

  • Definition

    • publicdouble 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


An aside type casting l.jpg

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


Recursion l.jpg

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)

return1;

else

return n * factorial( n-1 )

}

Java


Recursion44 l.jpg

Recursion…

  • Fibonacci series

    • f(0) = 0f(1) = 1f(n) = f(n-1)+f(n-2)

  • What would this be as a for loop?

long fibonacci(long n)

{

switch(n)

{

case0:

case1:

return n;

default:

return fibonacci(n-1) + fibonacci(n-2);

}

}

Java


Method overloading l.jpg

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)

{

returnthis.indexOf(ch,0);

}

Java


Extensions l.jpg

Extensions

publicclass 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


Implementations l.jpg

Implementations

publicclass 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


Example casino game craps l.jpg

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


Craps java applet version l.jpg

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 classCraps extends JApplet implements ActionListener

  • declares Applet

    • extends JApplet – gains basic Applet behaviour

    • implements ActionListener – responds to GUI events

Java


Craps java japplet l.jpg

Craps.java: JApplet

  • Initialise constants

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

final intWON = 0, LOST = 1, CONTINUE = 2;

public voidinit()

  • 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


Craps java gui l.jpg

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


Craps java gui bits l.jpg

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

    • make it un-editable

    • add it to the Applet

die1Label = new JLabel( "Die 1" );

c.add( die1Label );

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


Craps java events l.jpg

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


Exercises chapter 6 l.jpg

Exercises Chapter 6

  • All examples in text

  • 6.8 – calculation

  • 6.14 – loops

  • 6.22 – multiple event sources

  • 6.38 – calculation

Java


Strings and characters ch 29 l.jpg

Strings and Characters (Ch 29)

s1 = new String( "Hello World" );

s2 = new String( charArray);

s3 = new String( byteArray);

s4 = new String( charArray, 2, 3);

s5 = new String( byteArray, 2, 3);

  • Constructors

    • String

    • Byte and Char arrays

      • with indexes

  • Once created the size (length) of a string is fixed

  • methods for

    • determining the length

    • extracting characters

    • comparisons

    • extracting sub-strings

    • changing the characters in the string

int l = s1.length();

char c = s2.charAt(5);

Java


Comparisons l.jpg

Comparisons

  • Methods compare strings using the value (ACSII/Unicode) of the characters

    • lexicographical comparison – case sensitive!

s1 = new String( "Hello" );

s1.equals("hello");//falses1.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


Comparing regions l.jpg

Comparing regions

s1 = new String( "Hello Worlds" );

s2 = new String( "world" );

s1.regionMatches(6, s2, 0, 5);//false

  • Parameters

    • is position to start match at

    • is string to match

    • is position in parameter string to start at

    • 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


A note on l.jpg

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

  • then

String s1 = new String("hello");

s1 == "hello"

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

Java


Slide59 l.jpg

==

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


Other methods l.jpg

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


Stringbuffer l.jpg

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


Stringtokenizer l.jpg

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 = st.countTokens();

while(st.hasMoreTokens())

st.nextToken();

  • count() returns the number of tokens

  • The while loop shows how to work through the string extracting tokens in turn

Java


Stringtokenizer63 l.jpg

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


Character tests l.jpg

Character tests

  • and many others…

    • the letter tests work with the Unicode set so they also test forÙ ù Â â æ etc…

Java


Exercises chapter 29 l.jpg

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


  • Login