650 likes | 962 Views
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
E N D
CG0093: Application Design in Java Weeks 1-2: Java Basics Sajjad Shami Michael Brockway School of Computing, Engineering and Information Systems Northumbria University Java
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 • Object oriented • Simple • Small language • Easy OO use, error handling • Platform independent • PC • Unix • Handheld • Smartcard Java
Java Facts… • Network centric • Designed for network environment • Large number of libraries (Packages) • Graphics • Phone • Database Java
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 • 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 • 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
//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 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
//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
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 • 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 • 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 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 • 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 • 8 types • Have wrapper class supplying utility functions Java
Operators (some) Java
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
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 • All examples in text • 2.14 • 2.17 • 2.26 • 2.32 Java
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 • 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 //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 //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 • All examples in text • 20.4 • 20.5 • 20.9 Java
Control Structures (Ch 4 & 5) • Decision • Selection • Repetition • counter • logic test • top • bottom • Exits Java
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 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 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
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… • 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 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 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 • 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) • 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 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 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 • All examples in text • 4.17, 4.20, 4.22, 4.30 • 5.11, 5.17, 5.24 Java
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 • 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 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 • 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 • 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
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 • 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 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 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’ • 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) 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 • 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