CT 229 Arrays in Java 27/10/2006 CT229
Next Weeks Lecture Cancelled Lectures on Friday 3 rd of Nov Cancelled Lab and Tutorials go ahead as normal Lectures will resume on Friday the 10 th of Nov 27/10/2006 CT229 1
Lab Assignments Current lab assignment is due today: Nov 3 rd There will be a new lab assignment up on Nov 3 rd Before submission make sure that the name of each.java file matches the name given in the assignment sheet!!!! Remember: Electronic Submission @ http://ecrg-vlab01.it.nuigalway.ie/uploader/submissions.html 27/10/2006 CT229 2
Lab Assignments Results of Lab Assignment 2 will be up on the website this evening http://www.nuigalway.ie/staff/ted_scully/ct229/labs.html Again most marks lost due to formatting!! Naming Conventions Comments Space and Indentation 27/10/2006 CT229 3
Review of Last Week - Arrays Declare an Array int[] numbers; Initialise Array of length 3 numbers = new int[3] Place a value in an Array numbers[0] = 10; arrayname.length returns size of array numbers.length (returns 3) 27/10/2006 CT229 4
Review of Last Week - Arrays Passing an Array to a Method dosomething(arr); public static void dosomething(int[] a) {.. } Returning an Array from a Method Public static int[] somemethod() {.. } 27/10/2006 CT229 5
Review of Last Week - Arrays When an Array is passed as a parameter to a method it is passed by reference Changes made to the array inside the method are reflected in the main When a primitive type (int, double, etc) or an element of an array is passed as a parameters to a method it is passed by value If the method changes the value of the parameter it is not reflected in the main 27/10/2006 CT229 6
Review of Last Week - Arrays 2D Arrays int[][] a = new int[3][4]; [ROWS][COLUMNS] Ragged Arrays int[][] ragged = new int[3][]; ragged[0] = new int[2]; ragged[1] = new int[4]; ragged[2] = new int[3]; 27/10/2006 CT229 7
Arrays and Command Line Arguments Popular technique for giving input to programs Supported by most programming languages In Java programs: When running program, any text typed after program name is split on spaces and put in a String array, args This is passed by JVM as parameter to main method Program can inspect args to determine what was typed Example: SayHello.java Program that says hello, given name in input Usage: java SayHello Ted Scully 27/10/2006 CT229 8
SayHello.java public class SayHello { public static void main(string[] args) { if (args.length == 1) System.out.println("Hello there, " + args[0] + "."); else if (args.length == 2) System.out.println("Hello " + args[0] +" "+ args[1]); else System.out.println("Usage: java SayHello <name>"); } } 27/10/2006 CT229 9
CT 229 Java Applets 27/10/2006 CT229
Applications and Applets So far with Java, we have covered writing applications. Standard, stand-alone programs Require a main() method in your code Alternative => Applets 27/10/2006 CT229 11
What is an Applet A java class that can be: Embedded within a HTML page and downloaded and executed by a Web browser. The following are the steps involved in running an applet: Step1 The browser loads the URL http://weblocation/page.html 27/10/2006 CT229 12
What is an Applet Step2 The browser loads the HTML document <html> <applet code = "SwitchTest.class" width = "260" height = "260"> </applet> </html> 27/10/2006 CT229 13
What is an Applet Step3 The browser loads the applet classes SwitchTest.class Browser 27/10/2006 CT229 14
What is an Applet Step4 The browser runs the applet Location: http://weblocation/page.html SwitchTest 27/10/2006 CT229 15
Writing an Applet import javax.swing.japplet; public class appletname extends JApplet {... } [Class X extends class Y to add functionality, either by adding fields or methods to class Y, or by overriding methods of class ] 27/10/2006 CT229 16
Life Cycle of an Applet init(): This method is intended for whatever initialization is needed for your applet. It is called when the applet is created and loaded into a browser. Can be used to initialise data values start(): This method is automatically called after init method. It is also called whenever user returns to the page containing the applet after visiting other pages stop(): This method is automatically called whenever the user moves away from the page containing applets. You can use this method to stop an animation destroy(): This method is only called when the browser shuts down normally 27/10/2006 CT229 17
Writing an Applet import javax.swing.japplet; public class appletname extends JApplet { public void init() { } public void start() { } public void stop() { } } public void destroy() { } 27/10/2006 CT229 18
Applet Display- paint(graphics g) method Applets are graphical in nature You can draw on an applets panel by calling the paint method Browser calls paint method each time the applets display needs to be refreshed. For example when the browser page needs to be refreshed after being minimized or inconified. The paint method takes an argument that is an instance of the java.awt.graphics class. 27/10/2006 CT229 19
Applet Display- paint(graphics g) method This Graphics parameter is always the graphics context of the panel that makes up the applet. You can use the Graphics parameter to draw or write on the applet Example g.drawstring("hello World", 25, 25); The above command draws the text Hello World on the applet panel at the (x,y) position 25, 25. Can also call repaint() method from code, which will automatically call the paint method. 27/10/2006 CT229 20
Applet Hello World import javax.swing.japplet; import java.awt.graphics; Examples: - helloworld.java - helloworldpaint.java public class HelloWorld extends JApplet { public void paint(graphics g) { g.drawrect(0, 0, getsize().width - 1, getsize().height - 1); g.drawstring("hello world!", 5, 15); } } 27/10/2006 CT229 21
What is appletviewer? A Java application that: Enables you to run applets without using a web browser Loads the html file supplied as an argument appletviewer HelloWorld.html 27/10/2006 CT229 22
Applet Example From Deitel & Deitel, 5 th Ed. Applet using switch statement Different choices of graphics, p183 SwitchTest.java and SwitchTest.html 27/10/2006 CT229 23
CT 229 Break and Continue Keywords 27/10/2006 CT229
break keyword break keyword: Can be used in body of any loop structure or switch Causes immediate exit from the structure Commonly used with switch statements May be used to terminate loops early E.g. enter 10 numbers; stop if -1 is entered 27/10/2006 CT229 25
break keyword - Example Example: int number = 0; final int MAX = 5; Output_A => 1 Output_A => 2 Output_A => 3 do { number++; System.out.println("OutputA => "+number); if (number==3) { } break; } while (number < MAX); 27/10/2006 CT229 26
continue Keyword continue keyword: Can be used in body of any loop structure Skips remaining statements in body, and moves onto next iteration of loop E.g. print numbers from 1 to 20, skipping multiples of 3 27/10/2006 CT229 27
continue keyword - Example Example: int number = 0; final int MAX = 5; Output => 1 Output => 2 Output => 4 Output => 5 do { number++; if (number==3) { continue; } System.out.println("OutputA => = "+number); } while (number < MAX); 27/10/2006 CT229 28
break and continue with labels Example: for (int i = 0; i <= 5; i++) { * ** *** **** ***** for (int j = 0; j < i; j++) { System.out.print( * "); } } System.out.println(); 27/10/2006 CT229 29
break keyword with labels Example: outer: for (int i = 0; i <= 5; i++) { * ** for (int j = 0; j < i; j++) { if (i == 3) { break outer; } System.out.print( * "); } } System.out.println(); 27/10/2006 CT229 30
continue keyword with labels Example: outer: for (int i = 0; i <= 5; i++) { * ** **** ***** for (int j = 0; j < i; j++) { if (i == 3) { continue outer; } System.out.print( * "); } } System.out.println(); 27/10/2006 CT229 31
break and continue Comment: Do not overuse break/continue statements Labelled break/continue are very rarely used Only use them when gain (efficiency, legibility) is clear 27/10/2006 CT229 32
CT 229 Introduction to Object-Oriented Programming 27/10/2006 CT229
What is an Object? Humans observe that the world in object oriented terms Objects are everywhere A Pen A Car A Laptop 27/10/2006 CT229 34
What is an Object? The world can be broken into objects e.g. an elephant Objects are things we have information about (name, age,..) we do something to (ask to pick up log) may be conceptual (bank account) or tangible (car)! Objects are similar all elephants are similar (belong to class elephants) Distinction between generic concept and particular instance (that elephant) classes are similar to other classes (e.g. all elephants are animals, all have age, height, ) Some classes have subclasses (e.g. African elephants, Indian elephants) 27/10/2006 CT229 35
What is the advantage of using Objects Objects provide a level of abstraction. They insulate someone from the underlying complexity I can think of a car and not about the individual components (engine, chassis, wheels, fuel, ECU) or how all these components work together to make the car move 27/10/2006 CT229 36
An Elevator Q: What is this object? A: An elevator Q: What can you ask it to do? A: Move to a different floor, open its doors, hold its doors, call a lift going up, call a lift going down, Q: How exactly does it work? A: Don t really know! Q: Do you really care? A: NO!!! 27/10/2006 CT229 37
An Elevator s Actions Are Defined By Its Interface We must have some means of interacting with an object. The button panel is the elevator s interface through this interface we can ask the elevator to invoke any of its actions. 27/10/2006 CT229 38
A Phone Q: What is this object? A: A mobile phone Q: What can you ask it to do? A: Dial a phone number, connect a call, send an SMS, store phone numbers, store reminders in my calendar, play video games, Q: How exactly does it work? A: Don t really know! Q: Do you really care? A: NO!!! 27/10/2006 CT229 39
A Mobile Phone s Actions Are Defined By Its Interface We must have some means of interacting with an object. The keypad and the menu options on the screen are a mobile phone s interface through this interface we can ask the mobile phone to invoke any of its actions. 27/10/2006 CT229 40
Objects in Java Java objects are no different than everyday objects like a mobile phone or an elevator. For each object that s needed in the problem, a programmer writes a CLASS this is a piece of Java code that describes the object. Think of it as a template or a blueprint that s used to create objects. Therefore, if our problem deals with lions and tigers and bears, a programmer must write a Lion class, a Tiger class and a Bear class 27/10/2006 CT229 41
Objects in Java Within our problem-solving code, if we want to represent a lion, we simply create a new instance of the Lion class (using our Lion blueprint). If we need ten lions, we create ten instances of the Lion class. Each instance of a class is called an OBJECT. Every Java object must provide some means of interaction Every action that an object can perform is represented by a method. 27/10/2006 CT229 42
Summary In software, a class is a description of an object. A class acts as a blueprint for an object A class describes the attributes and operations of an object EACH INSTANCE OF A CLASS IS CALLED AN OBJECT!!!! 27/10/2006 CT229 43