Java Exam Prep          < 2 marks = four sentences >

Red means "not sure". So does italics. These are just my personal study notes... check everything!! I passed but only just.

Q1. The Internet

 

  1. Images and forms. Why did these extensions to HTML trigger an explosive growth of interest in the Web? (1 mark)  1998 paper.

 

Level 2 html introduced forms. With server-side CGI technology, it revolutionised the web.

 

 

 

 

 

 

  1. Explain the following features of a modern browser: helper applications, plug ins, image maps, frames. (2 marks)  1998 paper.

 

Helper applications: Suffix in file name indicates data type. Rather than browser being bloated with every possible type of data, browser copies the data file to the local disk then launches a helper application to read and process the file. Server sends details of the MIME (= Multiple Internet Mail Extension) type of data as part of the header. Eg: .wav, .gif, .au.

Plug ins: Browser provides functions that can be used by extension code to get config info for data the browser is not equipped to handle. Plug ins can be dynamically linked – when extension code doesn’t have to be part of the browser. Plug ins must be native (machine) code, compiled to run on a particular platform, = are not platform independent, so users must get the appropriate plug in for their system.

Image maps: Client side image maps now, eg.

…

Frames: Divides a window into separate named (scrollable) parts. The master html document (/index.html) has instead of and name of target frame where fetched document is to be displayed.

 

  1. What is a "denial of service" attack? (1 mark). 1998 paper.

 

2 types: 1. network based (= against the IPS).

4000 per week, says ASTA. Attacks are from <10 minutes to 1 hour. 500 packets/sec will overwhelm the server. Flood attack (to overwhelm server with trivial requests, = a loop sending UDP ping, time or echo requests, or a loop sending http GET requests) is common so users can't access the victim computer. Hacker can also recode the SYN protocol – remove the confirm – this ties up one OS slot for minutes each time.

Tracing only identifies the compromised machines.

Backscatter is when the victim computer replies to the random "source" Ips, = the compromised machines.

Type 2. Against CPUs. Done by putting JavaScript, Java applet or ActiveX on attractive sounding webpage. This uses up CPU time, thus slows it down – also locks up processes till they have to die. No damage to CPU or to data. To prevent, cause JS interpreter to pause after 1 second to ask user whether to continue.

Serious attacks on your CPU are a different matter: executing code on your CPU or interfering with content or delivery of networked messages (not covered here) – hacker may have left trapdoor programs.

 

  1. Rand's original proposals for "packet switching" offered both increased reliability in the context of vulnerable network connections, and improvements  in the effective utilisation of the data transmission capacity of network connections.  Explain how packet switching achieves these goals.(2 marks)

 

Packet switching:  Data is sent in packets, each has to and from addresses. Goes through routers. If no ack is received, packet is re-sent.

Reliability: When lost packets are not acknowledged, are re-sent automatically. All messages are heard by all machines on the network.

Effective transmission: Multiple (redundant) routes. Transmission is via best available route, as determined by packet switches (= routers), using address tables of IP addresses. Packets are queued at routers, so may arrive out of order. Uses sliding window flow control.

 


  1. Explain briefly how computers communicate on a broadcast network such as the original Alohanet or a local Ethernet. (1 mark)

 

Every computer on network has unique address.

All computers hear all messages but ignore what's not got their address.

Listen, if quiet, you can transmit.

Listen as you transmit - if collision, retransmit after random time.

 

  1. ARPA's vision for an "inter net" was of a "network of networks".  Explain how this is reflected in the IP addresses used to identify computers. (1 mark)

 

32 bit unique addresses were based on idea of a network number (prefix) and a machine number (suffix).

Uses dotted decimal notation.

Divided into Class A, B, C networks.

IP address is really the address of a network connection.

 

 

 

 

 

  1. What is a "domain name" and how can it be converted into the network part of an IP address?  (1 mark)

 

Domain names are meaningful to humans, whereas IP addresses are numeric. Domain name servers use a systematic approach that maps names to IP addresses. Based on Machine.unit.organisation.domain

(= hostname.localdomain.group.supergroup)

My computer will ask a DNServer to translate the domain name I type into an IP address. If my local DNS doesn’t know the domain I'm looking for, it asks its next DNS, etc.

 

  1. Apart from the Web, the Internet provides many services; examples include file transfer, email, network news.  Explain how each of these services works.(3 marks)   

 

File transfer: FTP is for efficient transfer of multiple files between sites. You specify the remote machine (ftp serverName) or start ftp and use 'open' . Then login with password. Session stays open. Menu of about 20 commands. FTP uses port 21.

Email: Incoming mail is queued in your mailbox files – you get access through another program. Outgoing messages wait on another queue. MIME allows non-text to also be sent.

Net news: Network administrators select certain news groups – when line is free, downloading happens. One fetch, many readers. Postings can be anonymous. News

 

  1. Summarize the essential behaviours of a client, a forking server, and a threaded server.  (3 marks)   

 

Client: When you start a program on your computer, you're running a client.

It asks other machine (server) to run a process. (gh)

Forking server: Server = program that is running constantly, listening for clients trying to connect (= the receptionist process). A new "worker" process is started (=is forked off) in a new connection which handles client interactions. Receptionist waits for next client. This is the normal system outside of Java, but rare with Java.

Threaded server:  A single process handles concurrent connections from multiple clients. This is the normal Java system, uses ClientHandler class – create an instance for each client (passing new socket), run(). Eg: Web browser fetching 2+ pictures, displaying Java animation and responding to user input. "A multi-threaded process is like a time share system on a micro scale" (NG).

 

  1. How are "port" numbers used?  (1 mark)

 

To identify the application. In the OSI model, port numbers are part of ?Application layer.

Port 80 is WWW, ftp is port 21.

Ports belong to the OS.

 


  1. When and where did the http protocol and HTML language for the Web originate?  Why was this hypertext system more successful than earlier attempts?  (1 mark)

 

http: Client program (= the browser) sends simple message (line of text) saying GET /…./…..html

then server program (httpd, d =daemon) uses a reply code like ftp, eg 200 – success (file appended), 404 - file doesn’t exist).

 

When/where originate?

 

 

 

HTML: Tim Berners-Lee created HyperText Markup Language from SGML.

Why more successful?

 

 

 

 

  1. What is a URL?  (1 mark)

 

URL = text address (cf. numeric IP address) of a website. Eg, protocol.computerDomainName.port.fileName or if called from within same path, just fileName.

 

  1. How are inter- and intra- document links defined in HTML?    (1 mark)

 

Inter: Links between documents. Needs to know which computer + server program + document name, so give URL. hypertext

Intra: Links within a file. The hypertext links to the anchor which is and opens here.

 

  1. Explain how HTML-forms/CGI-programs can be used to process data  entered by a user.  How are the data entered by the user delivered to the processing program?  How is the program's response returned to the user? (2 marks)   

 

User fills in form which has an "action" – which usually specifies the URL of a CGI program.

Press "Submit" action button to submit the form.

Web client then packages the data and sends it to web server, asking it to run a program identified by a URL in the form description.

Web server program starts the requested program (can be written in any language) and passes data to it (by using name-value pairs to specify the environment variables).

Program creates an html page which is returned.

Web client displays the received page.

 

  1. What types of information are typically found in the ... section of an HTML page.   (1 mark)

 

Most data in section is for use by other programs (eg web search engines) and is never displayed to the user. Eg, keywords in tags, define styles, define functions and global variables for JavaScript. Also special effects, eg.

 

  1. Explain all the HTML tags in the following:  (2 marks)   

 

XYX Corporation // string to appear in title bar<o:p></o:p></span><P></p> <p class=MsoNormal><span style='font-size:11.0pt;mso-bidi-font-size:12.0pt'>

// defines a rectangular grid of frames

...

If your browser doesn't handle frames, <a href="noframe.html">alternative source</a> is available.  

 

 

  1. The attributes of a
    tag can include: method, name, action, onSubmit.  Explain the use of each of these attributes. (2 marks)   

 

Method:

 

 

 

Name:

 

 

 

Action:

 

 

 

OnSubmit ΰ data is encoded and sent to web server, new process forks off, program reads data, sends ??? back to client.

 

  1. Illustrate the various forms of input element in a form (such as radio button, checkbox, text, select, and submit buttons) by providing HTML and sketching an annotated diagram of the corresponding form's appearance.  (Use an example like the pizza order example from the lectures, or something equivalent). (3 marks)    

 

Radio buttons: choose 1 of many.

 

 

 

Checkbox = 2 state, on/off, true/false.

 

 

 

Text:

            TextField text = new TextField(20, "Enter your name"); // CREATE empty textfield with default width

            TextArea text = new TextArea("Type here", 10, 40); // where numbers are R, C sizes.

            Use add(TextField); or add(TextArea); // ADD textfield to an applet (always Create before Add !!)

Use setText and getText methods.

            Use text.setEchoChar('*'); for passwords.

Select:

 

 

 

Submit:

 

 

 

Choice: A large set of radio button that displays as a popup list – can select only one. [ 1Choice. ]

 

 

 

List: A variation of Choice. Allows multiple selections, in a scrollable window. [ List-has-many. ]

 

 

 

Label: Neither Choice nor List displays a label, so you can add a non-editable string using Label.

            public void init() {

                        Label label = new Label ("Hello");

                        add(label); }

            OR: add(new Label("Hello"));

 

  1. Javascript - a typeless, event driven, object oriented language.  Discuss.  (3 marks) 

 

>>>> Review lecture notes to give NG what he wants.

 

 

 

JS is a scripting language, not a programming language. For developing client and server applications.

Typeless: No??. Its code switches between text and numerics. A little sloppy about variable declarations (JS is weakly-typed.) You can define a variable and the runtime system will check whether the requested operations are appropriate to the data type. As it is typeless, there is no return type.

"Variable data types not declared (loose typing)". "JS is a loosely typed language. You don’t have to declare a data type of a variable. Data types are converted automatically with JS statements."

"If data types and variables are not declared, JS is dynamically typed."

 

Event driven: No, JS is not an event handling system. But most JS code specifies functions to be called when events occur. Mostly these are user events that trigger Just-in-time ?compilation.

"Most JS functions are called in association with an event for an element involving something on a HTML page." (NG)

"JS is able to respond to events on a web page – these features are called event handlers. Eg onMouseover, onLoad event handlers."

"JS applications in Navigator are largely event-driven. Events are actions that occur, usually as a result of something a user does. Event handlers = scripts that are automatically executed when an event occurs. They are embedded in documents as attributes of HTML tags." (JS book).

Event driven (Harrington, Java book p167) = GUI programs are event driven which means they wait for something to happen, identify what has happened, and act based on what happened. Events include mouse movements, clicks, menu choices, etc. (A true event driven program responds to more than a menu choice that uses a switch construct.) Event driven programs therefore require event listeners. These must be attached to the objects they want to listen to.

            By this definition, JS is not a true event driven program.

 

Object oriented: No. JS is "object-based" (correct term) (Book also calls it "an object oriented script language", p.81) to a limited extent but it lacks true classes in the OOP sense – "its code uses built-in extensible objects but has no classes or inheritance". You can define data types and functions and tell data objects to act. But mainly JS uses objects provided by the browser (eg, that provide info about the browser, window, current page, forms, date, etc).

JS is used to validate form data on the client side, put a comment in the browser status bar, calculate,  ……………..

 

  1. Explain how "events" can be coded in HTML tags and used to invoke Javascript functions. (1 mark)

 

By placing function calls inside the tag. Eg, onLoad, onUnload, onBlur, onFocus, onMouseOver, onSubmit, onSelect, onChange,

Function definitions and global variables go inside the tags – this code is executed as the page loads.

In the body of the page, you put the event-related calls to functions.

 

>>>Check NG notes, because book says:

"JS can be embedded in an HTML document in one of 2 ways: as statements and functions using the SCRIPT tag, or as event handlers using HTML tags… Functions are executed by events in the page. Define the functions (using the SCRIPT tag) in the HEAD. This guarantees that functions are loaded before the user has a chance to do anything that might call them."  Book, p.66-9.

 

 

 

  1. What is a "cookie"?  (1 mark)

 

Web and http are mostly stateless, ie no memory. But cookies provide memory – an alternative to expensive database. Persistent client state http cookies. Cookies = text records of URL and name value pairs, stored (unencrypted) on client browser. When this URL page is fetched next, cookie's name value pairs accompany the request and a new page is dynamically generated (by the CGI program).

 


  1. Explain what is happening when a hacker "sets the interface in promiscuous mode to sniff the ethernet traffic", and when she "spoofs  an IP address".(2 marks)   

 

Promiscuous: Hacker can have a machine listening to broadcasts of network traffic. How? He sets the interface on his machine to promiscuous mode, so it filters all packets looking for specified address headers. Can pick up passwords if he sets filters to look for sequences that start telnet, ftp, login sessions.

Sniff: In a non-switched network, Ethernet frames broadcast to all machines on the network, but only the computer that the packets are destined for will respond. All of the other machines on that network still see the packet, but if they are not the intended receiver, they will disregard it. When a computer is running sniffer software and it’s network interface is in promiscuous mode (where it listens for ALL traffic), then the computer has the ability to view all of the packets crossing the network.

Sniffers = network traffic analyzers. Crackers install sniffers to obtain usernames, passwords, credit card numbers, personal information, etc.

Spoofing: Is harder. Have to change DNS tables or router tables, so hacker machine looks like either a local machine (where password may not be required) on your network or a server.

Ethernet = local area network – it sends data by packets.

Spoof = to capture, alter, and retransmit a communication stream in a way that misleads the recipient. As used by hackers, refers especially to altering TCP/IP packet source addresses or other packet-header data in order to masquerade as a trusted machine. To spoof an IP address, that means that in the header of the packet, you are changing the source address as to conceal the real source address.

 

  1. What is a "message digest"  and why might you want one? (1 mark)

 

A checksum adds up the value of bytes, does a modulo, and sends the result with the message.

A message digest is more complex, sensitive (128 bit often) – it combines data from each character

To help detect if data has changed in subtle ways, eg $109 to $190.

 

  1. Explain how a public-private key pair can be used in the creation of a "digital signature". What is the role of an certification service, such as that provided by Verisign, in this approach to identification? (2 marks)   

 

Public-private key pairs: Most encryption systems use the same key for encrypt and decrypt – called symmetric. Called DES. But can have 2 keys – asymmetric. You publish your public key for anyone to use if they want to send you a message. Inputs into the encryption algorithm are your public key + their message. Result is garbled text. You use the same encryption algorithm with your private key + garbled text to decode the message. Safe but slow. Thus:

To confirm I'm talking with Joan, we swap our agreed text string – it's encoded using her private key. I decode it with her public key. If it's right, it's her.

To be even more sure, a certification company can confirm the name, address and public key of my correspondent. 3 levels of service: his entry in their database, that entry was confirmed, Verisign phoned him.

 

  1. Java claims to provide security in relation to downloadable code through: being a secure language, the "sandbox" execution environment, and code signing.  Explain each of these concepts.(3 marks)   

 

Secure language:

Examples of Java being a secure language:

Array bounds checks – attempts to overrun a buffer will result in runtime exception.

No direct manipulation of pointers

Type case verification by compiler

Access to member functions checked by compiler.

Also ClassLoader – it's a supplied class that defines operations needed to resolve a class being loaded – it keeps track of the source of classes by keeping the newly loaded classes separate from java.* classes.

  [java.security provides a means to examine a class at loadtime, to determine its level of access to the local system. With Java you can fix the openings for hacking in.]

Sandbox execution environment: Is a very limited environment in which applets run, with no access to these—local system files; execution of local commands; any socket connection (except the originating URL that loaded the applet – note: a new TCP/IP connection is opened to the server to ask for byte codes of the compiled Java program – when the code is loaded, the byte array is passed to the JVM for execution); any GUI resources not managed by the browser; Also, windows open by the browser on behalf of the applet are tagged as "Untrusted".

With applets and applications, a SecurityManager class is used to determine access characteristics – asks: is he allowed to write to that? [Applications are considered trusted.]

Code signing: "digital signing, which allows you to unequivocally know everyone that wrote all the programs that have special access to your system" – relevant??

 

 

 

 

  1. Explain two-tier and three-tier models for systems involving Java clients and databases.    (1 mark)

 

2tier: Client machine has (B) Java app + JDBC --- connects through DBMS-proprietary protocol to --- (C) DBMS database server. "In the 2 tier model, a Java applet or application talks directly to the data base. This requires a JDBC driver that can communicate with the particular database management system being accessed. A user's SQL statements are delivered to the dbase and the results are sent back to the user."

3tier: (A) Java applet or HTML browser on client machine --- connects through HTTP, RMI or CORBA (= Common Object Request Broker Architecture) calls to --- (B) Application server (Java) + JDBC --- to --- (C). "In the 3 tier model, commands are sent to a middle tier of services which then send the SQL statements to the dbase. It processes them and sends results back to the middle tier which sends them on to the user." Benefits of 3 tier: MIS managers can maintain control over access; can use higher level API (with its GUIs on the clients); often performance advantages with 3tier.

 

  1. How does the Java Database Connectivity (JDBC) API make it possible to write Java programs that use databases while remaining independent of the actual relational database system employed.   (1 mark)

 

JDBC is a low-level interface so it invokes SQL commands directly. Thus JDBC is the base for higher level interfaces and tools that are user-friendly.

 

  1. JDBC provides the classes: DriverManager, Connection, Statement, ResultSet.  What are the roles for instances of these classes?  Sketch an outline of code for submitting a simple query to a database and    processing each of the retrieved records.    (2 marks)   

 

Roles

DriverManager: Keeps track of available drivers, makes and manages connections.

Connection: Represents a session with a database. Events are: establish connection, pass SQL statements to database

Statement: Sends simple SQL statements. Also available are PreparedStatement (is pre-compiled), CallableStatement (to execute a stored SQL procedure).

ResultSet: Contains the rows that satisfy the query conditions – like an Iterator, it uses next().

 

Sketch code

Connection dbx = driverManager.getConnection (db_URL, myuserID, myPassword);

Statement stmt = dbx.createStatement();

…

String query = "SELECT Name, Address FROM CustomerTable WHERE …";

 

ResultSet results = stmt.executeQuery(query);

While (results.next()) {

            String custName = results.getString ("Name");

            …

}

 

  1. Contrast the "Remote Method Invocation" and "ports and sockets" approaches for the implementation of distributed programs.  (2 marks)   

 

RMI: Is object oriented communication, Java to Java. There's no need to invent protocol – use standard mechanisms for passing arguments for method calls.

Ports and sockets: Java client can communicate with servers written in other languages, BUT programmer must devise an application specific protocol defining how the data are sent. Java to other languages. (Socket = a software abstraction for a medium of network communication; it connects a stream of network data to a java program.)

 

  1. "A Java Bean is a reusable software component that can be manipulated visually in a builder tool." Explain (both what and why!).  (2 marks)   

 

"Java 1.1 includes the Java Beans standard, which is a way to create components that can be used in visual programming environments. This promotes visual components that can be used under all vendor’s development environments. Since you aren’t tied to a particular vendor’s design for visual components, this should result in greater selection and availability of components. In addition, the design for Java Beans is simpler for programmers to understand; vendor-specific component frameworks tend to involve a steeper learning curve."

 

 

 

What:   Beans API = (1) mainly interfaces (BeanInfo, Customizer, PropertyEditor, PropertyChangeListener, VetoChangeListener). Serializable is not in Beans API but is an important interface which all beans must implement. And (2) and a few classes to provide support structure (Beans, Introspector, PropertyEditorManager) and about the individual beans (BeanDescriptor, etc).

Builder tool =

Why:

 

 

 

Q2. Java language

 

  1. A java class can extend one parent class and implement many interfaces. Explain. (1 mark). 1998 paper.

 

Extends allows for single not multiple inheritance. "Java uses a singly-rooted hierarchy, so all objects are ultimately inherited from the root class Object."

            Eg. class Alien extends Object

"Java uses the extends keyword to indicate inheritance from a base class and the super keyword to specify methods to be called in the base class that have the same name as the method you’re in."

Parent = super class. A subclass can only extend one superclass.

Interfaces have no implementation. interface is just an interface (has no data members, no definitions, it just captures some general functionality) – contrast extends, which extends existing functionality. To create a version of the interface that can be instantiated, use the implements keyword:

public interface Face {
   public void smile();
}
 
public class Baz extends Bar implements Face {
   public void smile( ) {
      System.out.println("a warm smile");
   }

}

The interface keyword takes care of combining multiple interfaces.

 

Seems to me that an object can have the qualities/methods/? of various other classes/?objects, thus you can interface with several other ?classes (objects). Right?? Word it better??

 

  1. Explain, and provide illustrative code for, Java's exception handling constructs. (2 marks) 1998 paper.

 

Because any input operation can fail, bracket them in try{} catch{} exception handling code.

Exception = situation that could crash the program. ?or corrupt the results.

Eg RuntimeException class – when trying to access an out of bounds array index.

 

In Java, specifying is not optional. If a member function can throw an exception, this must be stated in the declaration. Eg:

Class Integer … {

            …

            public static int parseInt (String s) throws NumberFormatException

            …

            }

"Exception handling in Java is different because there are no destructors. A finally clause can be added to force execution of statements that perform necessary cleanup. All exceptions in Java are inherited from the base class Throwable, so you’re guaranteed a common interface. Main subclasses are IOException and RuntimeException.

public void f(Obj b) throws IOException {
   myresource mr = b.createResource();
   try {
      mr.UseResource();
 
   } catch (MyException e) {
      // handle my exception
   } catch (Throwable e) {
      // handle all other exceptions
   } finally {
      mr.dispose(); // special cleanup
   }

}"

 

The base class for all exceptions is Throwable, which has 2 types (Exception and Error). Relevant?

 

Can add a throws clause to any method declaration to indicate that it can throw an exception,

eg:        public void Foo ( )

                        throws Exception1, Exception2, Exception3 // could be more in the list.

            { … }

Then you create a new object of the type of the required exception class, using the keyword throw to deliver it:

            throw new IOException ("Bad file name");

 

Catching it:        try { … // code that we're testing }

                        Catch (MyExceptionClass e) { … // exception handler code }

 

May also optionally add a finally block that does not depend on there being an error or not, eg:

                        finally

{                     

                                    try

{ f.close( ); }

                                    catch (IOException e)

                                                {          System.err.println "Exception closing file" + e);

                                                            return;

}

                                    }

                        {

 

  1. The Java language: "Object-oriented, robust, secure, architecture neutral, portable, high performance, interpreted, threaded, and dynamic." (claims by its creators Gosling and McGlinton). Explain the terms used in this description and how they relate to Java. (4 marks)   

 

Object-oriented. Object = data + methods (procedures) that act on that data. Are encapsulated.

Robust: "Generally, Java is more robust, via:

Object handles initialized to null (a keyword)

Handles are always checked and exceptions are thrown for failures

All array accesses are checked for bounds violations

Automatic garbage collection prevents memory leaks

Clean, relatively fool-proof exception handling

Simple language support for multithreading

Bytecode verification of network applets"

Secure:

Architecture neutral: Because it's based on the bytecode-interpreter model where each machine has its own unique interpreter that interprets the bytecode into code readable by that particular machine. "Bytecode is easy to interpret on any machine, and easily translated into native machine code at load time."

Portable: Cf native. [ =?Platform independent because it compiles source code files into (?byte) code files that JVM can decode. The JVM is a platform-specific byte code interpreter – it translates byte code into native instructions on the host computer that can be executed on that computing platform. Byte code is executable and has a .class file extension.]  Java specifies number ranges to ensure portability.

High performance: Java was designed to run well on low-power CPUs with the bytecode designed to translate directly into native machine code for very high performance.

Interpreted: Because it uses bytecode as an intermediary. Most computer languages are either compiled (and they can only run on the type of computer they were compiled for) or interpreted (and they can run on a variety of platforms because they exist only in source code form, eg scripts) – Java is both.

Threaded:

Dynamic: 

 

  1. Explain the compilation, linking, and execution systems of Java and compare them with those of C or C++.  (3 marks)   

 

.java ΰ

COMPILER ΰ

.class ΰ

INTERPRETER

ΰ Native code

Source code (a text file written in Java programming language using NotePad etc) with a .java extension…

is compiled (if there are no errors) into…

executable generic binary bytecode (named after the class with a .class file extension) that is executed/run by…

[bytes of code are instructions in machine language to a virtual (unreal) microprocessor called JVM]

the web browser's built-in Java interpreter…

[ This requires the machine to have JVM installed ]

which produces native code (ie. This new button looks like every other button on your system).

.java

Called javac.

.class

Called java.exe

 

 

ό      In C++, source code is Compiled into object (.o) files, then these are Linked with libraries to get an Executable, then Run. Memory: COLER.

ό      In Java, all details of class are in one file (= a single syntactic unit that contains the definitions of all member functions), ie no separate header file as in C++.

Compilation: Javac (=compiler) compiles the source code (text files) into executable Java programs (= bytecode) with .class file extensions that are generic.

When you compile in Java, you don’t generate instructions for one specific machine – you generate bytecode which is instructions for the JVM, so your compiled program will run on any machine on any platform that has its own JVM.

Linking:  Java loads code for classes when it needs to – there is no link step.

Execution: Starts with the main() method of the driver class (which has the same name as the source file).

 

Step 1. Create the source file, eg. MyProgram.java This is text written in the Java programming language.

Step 2. Compile it with the javac compiler into a bytecode file. javac MyProgram.java The compiler javac translates it into bytecode, = instructions that the JVM can understand

Step 3. Run the bytecode progam on my computer. If it's an application, run it with java -- if it's an applet, run it with appletviewer or your web browser (eg. Netscape). java myProgram  Each computing platform has its own version of an interpreter, ie. Win32 is different to MacOS or Solaris. The Java interpreter on my computer loads and runs the .class files, ?= it "implements the JVM", = translates into instructions that my computer can understand.

 

  1. Explain the "package" concept (you should cover both namespace and access control aspects of packages). (2 marks)   

 

Package = collection of classes and interfaces that in some way belong together, and whose instances often interact. An organisational unit that is greater than a single file. Eg: java.math, java.io, java.awt

Over 50 packages.

Namespace: Java offers a "universe of classes", a systematic way of uniquely naming every class invented by any Java programmer on the network. Similar control in C++ is through namespace.

"Java uses packages in place of namespaces. The name issue is taken care of by putting everything into a class and by using a facility called "packages" that performs the equivalent namespace breakup for class names. Packages also collect library components under a single library name. You simply import a package and the compiler takes care of the rest."

" Java packaging provides the equivalence of namespaces, so that isn’t an issue. Java 1.1 has inner classes that look just like nested classes. However, an object of an inner class secretly keeps a handle to the object of the outer class that was involved in the creation of the inner class object. This means that the inner class object may access members of the outer class object without qualification, as if those members belonged directly to the inner class object."

Access control: Similar to friend in C++. C++ has class, subclasses, clients, friends. Java has class, other classes in same package, subclasses in same package, other subclasses, clients.

 


??Relevant: " Instead of controlling blocks of declarations like C++ does, the access specifiers (public, private, and protected) are placed on each definition for each member of a class. Without an explicit access specifier, the default for that element is "friendly," which means that it is accessible to other elements in the same package (equivalent to them all being C++ friends) but inaccessible outside the package. The class, and each method within the class, has an access specifier to determine whether it’s visible outside the file."

  From most to least restrictive, it's private (only accessible to its own class/the defining package), default (accessible to whole package), protected (accessible to subclasses too), public (no restriction on which classes can access it).

 

  1. In C++, classes are "first class types"; instances of classes can be created as statics, automatics, or dynamics; a class may have data members that are instances of other classes. In Java, class types are all reference types. A variable declared as an instance of a class type is actually an object reference variable (pointer). All objects have to be created dynamically using new. Describe one advantage and one disadvantage of Java's approach relative to that of C++. (2 marks)   

 

Object reference variables contain either null or the address of the object created by new (= the address returned by the new operator).

Advantage: ?? Don’t have to specify the size of an array before you start. More?

 

 

Disadvantage: Java's object reference variables can't be used in calculations – only to access objects.

 

  1. What are the advantages and disadvantages of Java's approach to memory management as opposed to that used in C++?   (2 marks)   

 

Advantages:

C++ classes have destructors to free up resources (most commonly memory but also sockets).

Java has automated garbage collection so you don’t have to explicitly free memory by using destructors.

Java has finalize() which serves similar role to destructor – but no guarantee when it will be done so can't rely on it. Instead put your resource release code in a method you define, eg: tidy_up(), dispose() or destroy().

Disadvantages:

 

 

 

  1. How does Java provide for generic collection classes such as Vector?  (1 mark)

 

Collection class = ……………………… Eg: dictionary, stack, hashtable, vector.

Vector: = A general purpose resizable array class that is very useful when working with collections of objects. It handles all the details of adding and removing elements from arrays, and tries to use memory efficiently. It is a type safe dynamic collection class, therefore efficient memory management. Is a list of items, more powerful than an array, can grow in size dynamically.

"Java has no templates or other implementation of parameterized types. There is a set of collections: Vector, Stack, and Hashtable that hold Object references, and through which you can satisfy your collection needs, but these collections are not designed for efficiency like the C++ Standard Template Library (STL). The new collections in Java 1.2 are more complete, but still don’t have the same kind of efficiency as template implementations would allow." (book)

How? "In order to be used in a vector, simple data types (ie, boolean, char, double, float, int, long) need to be converted to objects using the java.lang wrapper classes." Because you can only store objects in a vector.

Vectors are allocated as objects using the new operator: Vector theVector = new Vector();

Vector is a resizable one-dimensional array. Because it's an object, manipulation requires using class methods.

 

 

 

 

  1. What are the advantages and disadvantages of Java's approach as opposed to the template style used in C++?   (1 mark)

 

Advantages: Flexibility; control – you can move elements; can add/delete/insert on the fly. Efficient – no allocated but unused memory.

Disadvantages: Each access requires a method call; slower – needs array creation and data recopying each time.

 


  1. Explain the Java language constructs that provide built in support for multithreading. (2 marks)   

 

Thread class is in java.lang package, has basic thread operations (start, yield, kill, priorities)

(You create a thread object then call its start() method.)

Use a Runnable interface (ie, thread object + runnable object) – { runnable provides run() ?? }

Use synchronized qualifier for methods – every object has a lock – these put locks on objects; you have exclusive control while you're in a block of code.

Use wait() and notify() operations defined at Object.

 

Eg: You want to gain control of anyObject—

            Synchronized (anyObject) {

                        // the code involving anyObject

            }

The above code blocks until anyObject is not locked, locks anyObject, does the code, releases the lock.

 

There's a better way (less likely to make errors): Make synchronization part of the signature, eg:

Public final synchronized void anyClass (parameters, if any) { … }

 

"There’s a Thread class that you inherit to create a new thread (you override the run( ) method).

Mutual exclusion occurs at the level of objects using the synchronized keyword as a type qualifier for methods. Only one thread may use a synchronized method of a particular object at any one time. Put another way, when a synchronized method is entered, it first "locks" the object against any other synchronized method using that object and "unlocks" the object only upon exiting the method.

There are no explicit locks; they happen automatically.

You’re still responsible for implementing more sophisticated synchronization between threads by creating your own "monitor" class.

Recursive synchronized methods work correctly. "Synchronization lock is a form of ??recursive mutex" (NG)

Time slicing is not guaranteed between equal priority threads." (book)

 

To prevent multithread access conflicts:

" The simplest method is to make your variables private (but you do that already,  right?) and to use synchronized accessor methods. Accessor methods allow access to private member variables, but in a controlled manner."

 

 

 

  1. What is Unicode, and why does Java use it?   (1 mark)

 

Unicode characters = unsigned 16bit (not 8bit), thus value range of 0-65,536.

To be able to represent all human languages in a platform-independent and portable way.

 

  1. There are both advantages and disadvantages in using Java for numeric applications rather than C/C++.  We all know that the disadvantages include inferior execution rate. What is Java's main advantage in  relation to numeric applications?  (1 mark)

 

Standardized definitions of int (it's always 32bits, on all platforms) – thus Java is robust, safe and cross-platform portable.

 

 

  1. How does a Java class specify that a method cannot be overridden by subclasses?  (1 mark)

 

Use the keyword/qualifier final.

Classes, member functions, variables can all be final – but can methods?? (I think so)

In Java, public and protected functions can be overridden if not specified as final; private functions can never be overridden.

 

  1. What is the role of the "static" qualifier? (1 mark)

 

Static = this member exists once per class (not per instance of the class).

Static has same meaning as in C++:

STatic data member = shared by all inSTances of the class.

Static member function (method) = has no data members (or only uses static data members).

 

  1. What is a "static initializer" block? (1 mark)

 

Sometimes a class requires some type of initialisation before it is ready to create objects. Here Java allows you to declare a static block. This is code that gets executed when a class is first loaded. Thus it is executed before the class can be used for any purpose, eg. before any objects are constructed. This is useful when you want to create constant data that is useful to all the instances and subclasses of a class. Eg – myBook p253. Eg:

class User {

static String userList[] = new String[3]; // note use of static keyword

static {

userList[0] = "Ed";

userList[1] = "Fred";

userList[2] = "Joe";

System.out.prinln("Users loaded and initialised."); ί this line optional.

     }

}

 

  1. What is the role of the "transient" qualifier? (1 mark)

 

Transient denotes that a field in a class object will not be persistent through serialisation. The value of a transient variable need not persist when an object is stored. A transient field is one that does not affect the state of an object.

The transient qualifier says 'don’t try to save this object, it has a link to a collaborator' (= ???).

Keyword transient is added along with private/protected/static/etc.

Example of use: you wouldn’t want to save the state of the Canvas object during continual repainting, so make it transient.

How to use: Define the class as one that implements Serializable, then use transient type qualifier for any references that are not 'state' data and which are not to be saved.

 

  1. When a class is loaded into the Java Virtual Machine, the Verifier checks the byte codes. What checks can the Verifier make? (2 marks)   

 

Prior to execution, it checks—

ό      Variable initialisation

ό      Scope – are all accesses to local variables within scope of the expected stack frame?

ό      Size – nothing too large created on stack?

ό      Matching – do the operations invoked on objects match their class signatures and accessibilities?

 

  1. Like any other stack, the stack of the Java Virtual Machine is constructed out of stackframes. In what way does it differ from the call stack in something like C?  (1 mark)

 

A stack is a FILO (first-in last-out) list. Like a stack of plates. MyBook p 187

A stack is a subclass of Vector which implements a LIFO stack. Naughton p206

 

 

 

 

Question 3: Java programming

 

  1. Explain the "peer class" mechanism used to achieve native look and feel for Components in the java.awt package. (2 marks) 1998 paper.

 

Native = of the platform it's running on. Delivered by Swing library in Java 2.

The objectives of AWT is "write once, run anywhere" (= platform independent code) and to support the look and feel of each platform. java.awt.peer defines a set of interfaces.

 

AWT is a thin software layer that gives access to the system's API (application programming interface). Peer classes = the underlying classes that provide specific windowing functions. If AWT creates a button on a Mac, it's a Mac button – peer classes give it the look and feel of their host op sys. Button has an intermediary (proxy) that does the work.

  In contrast to API components, Swing components work the same on all platforms. Memory: Same Swing!

 

  1. How are "layout managers" used with Containers? Describe the arrangement of components produced for two commonly employed layout managers. (2 marks) 1998 paper.

 

Layout managers are used to arrange positioning of subwindows.

How used:        setLayout(Layout Manager m)

                        add(Component c) –or-  add(Component c, constraints)

Example 1: A Frame with a FlowLayout manager will display components left to right across the page, creating a second/etc row if necessary. FlowLayout class is the default.

Example 2: BorderLayout specifies region names, eg West, center, etc.

Example 3: GridLayout.

Eg: setLayout(new GridLayout(2,2)); // creates 2x2 table.

 

  1. The Event Listener mechanism introduced in Java 1.1 replaces a "chain of command" pattern used previously.  Explain briefly how the "chain  of command" pattern worked and why it was replaced. (2 marks)    [1998 paper: Explain the Event Listener mechanisms used in Java to handle user interaction.]

 

There are 2 strategies for handling events: 1. old and widely used, 2. new.

1. How chain of command pattern worked: event (eg keystroke, mouse action, menu choice) is reported to series of "next handlers" until it reaches an object that deals with it.

Why it was replaced: Inefficient (lots of processing), restrictive (event handlers must be components).

2. Dependency (Observer) pattern. Listeners/dependents/observers register an interest. If an object is changed, all its dependents are notified and updated automatically, eg: addActionListener(ActionListener 1)

Different types of listeners interested in different types of events, eg: the AdjustmentEvents interface, the MouseListener interface (doesn’t track motion), the MouseMotionListener interface, the ActionListener interface

 

  1. The java.util. package contains class Observable and interface Observer which were originally designed to handle the kind of change management and dependent notification needed in the Listener mechanism.  Why were Observable and Observer not used for the implementation of the Event Listener?   (1 mark)

 

 

 

 

 

[[ An interface defines the general characteristics that are shared among multiple classes, = a group of public methods that can be implemented and then used as the basis for interacting with an object; it has unimplemented methods only. Relevant??

Interface is more abstract, has no data members, no definitions – whereas abstract class can have data members, can have member functions defined. Interface class has only un-implemented methods – abstract class can have implemented methods and member variables.

Abstract keyword now only = "partially implemented abstract class".

Because interfaces are not full blown classes, you don’t extend them – you implement them. Relevant?

Cf. abstract data types are partially implemented (eg. Regions in Ass2), can also have implemented methods and member variables. ]]

 

  1. Graphics objects.  What are their responsibilities?  (2 marks)   

 

 

 

 

"When a Java program needs to redraw an object on the screen, it eventually calls the object's paint method, which is the only location for drawing text or graphics. The method takes a single object of the Graphics class as a parameter. The Graphics class, from which your program never creates objects directly, acts as a base class for all graphic elements. The graphic element being painted is therefore typecast to a Graphics object. All calls to methods that draw text or graphics shapes do so using this object." (Book, Harrington p201).

"Whenever the applet must redraw its output, paint() is called. The paint() method has one parameter of type Graphics. This parameter will contain the graphics content, which describes the graphics environment in which the applet is running." (my book, p478).

 


User event ΰ message ΰ op sys (event manager) ΰ message ΰ application code (event handler).

Graphics programming is by means of a set of packages called JFC (Java Foundation Classes) including AWT (for GUIs), Swing…

java.awt.Component has buttons, menus, scroll bars, etc – these are all Components (= controls).

 

  1. Pixel colours are defined in terms of Red, Green, Blue and "Alpha channel" components.  What is the alpha channel?  (1 mark)

 

Graphics system have red, green and blue values for each pixels, plus transparency. The "transparency" is the "alpha channel" of a pixel.

 

 

 

 

  1. How are Images loaded?  How are ImageObservers and MediaTrackers involved in this process? (1 mark)

 

Images are loaded …

 

 

 

ImageObserver keeps track of images as they are loading, gets called regularly as data arrive, then (eg.) repaints a bit at a time.

 

 

 

 

MediaTrackers: ? If you want to delay painting till a picture or group of pictures is fully loaded, use a MediaTracker object. So create a MediaTracker object to work with the ImageObserver object that is loading, and give it a reference to each image that it is to monitor, then tell MediaTracker to delay until specified image/s has arrived.

 

 

 

 

 

  1. Why are off screen Images frequently needed? (1 mark)

 

Continuous motion requires 24 repaints per second and small motions. For a flicker free display of graphics, use double buffering – ie, create a new off screen buffer. Draw to a memory image map, then copy cleanly to the screen.

 

  1. Explain why synchronised methods are needed in a class like Vector. (1 mark)

 

Vector is dynamic, so several methods could be each trying to modify the Vector at the same time, eg one wants to add an element, another to delete one. By using sync, the first sync method to access the vector gets to lock it; other waits till first has completed task and releases its lock. Other threads trying to call an in-use synchronised object will enter a wait state. When a thread leaves a synchronised method, the object is unlocked.

 

  1. How can your provide atomicity and isolation for a transaction involving several successive operations on an object.  (1 mark)

 

Atomic: see B13, pg.8.

 

 

 

Isolation: 

 

 

 


  1. Explain the operation of the wait(), notify() and notifyAll() methods of class Object. (1 mark)

 

?? Basic idea is that when a thread is operating on an object, it blocks access by other threads. Those other threads wait.

Wait() and notify() are final methods of Object – and they can only be called from inside synchronized methods.

wait(): #Tells the current thread to sleep until another thread notifies it.

A thread that owns a lock on an object can wait on that object – the thread is blocked (waiting for this object to change), then lock is released. Wait can have a time in (). Format: while(! a_condition) wait ()

notify(): #Wakes up the first thread that called wait on this object. A thread that owns the lock on an object can notify of changes. "Allows another thread waiting on the object to resume." (NG)

notifyAll(): #Wakes up all the threads that call wait on that object – the highest priority thread then runs first.

 

Provide code that illustrates the use of these constructs in the solution of a typical scheduling problem.  (2 marks)   

 

Eg: printer controller (printer runs at constant speed, input is in bursts).

Lecture B13

 

 

 

 

 

  1. A Java Applet can access both information and "Applet Context" information (getAppletContext()). What are data used for?  Where are they defined? (1 mark)

 

Applet is contained in a webpage, runs on any java-compatible browser.

What for: data is used in name/value pairs to specify colours, text values, ……. Both name and values are strings.

Where defined: data is defined within the tags.

 

  1. Why might an Applet need to communicate with its AppletContext? (1 mark)

 

Relevant?? Class Applet— an applet is a Panel (provides space for components), is a Container (thus has a Canvas that can hold Buttons, Checkboxes, etc and can divide its space into subareas and allocate them differently), is a Component (thus has a display area and a paint() method), is an Object.

getAppletContext() returns an object which allows some communication with browser and html pages.

 

 

 

 

  1. The use of object i/o (with ObjectInputStream and ObjectOutputStream) raises problems relating to polymorphism and reference data members. Explain these problems and their solution via Java's Serializable mechanisms.    (2 marks)   

 

Relevant?? Polymorphic = many forms. Eg: m.run() allows each monster runs in its own way. Actually run() is the same, but the functions called from run() vary.

 

 

 

 

 

  1. Identify the classes from the java.net package that would be required, and sketch code for:

(a) A client that needs to establish a connection to a Java server with which it wishes to exchange Unicoded character streams; (1 mark)

 

Classes: Client, ClientGUI, ClientProgram. (I think so).

 

(b) A server that wants to open a "listening" port and then to serve clients (using an individual Thread to handle each client). (2 marks)   

 


?? Thread, ClientHandler, Observable,

?? Canvas, TextField, Button,

[ Below is from lecture MicroIRC, B12: ]

class ClientGUI extends Frame { … }

class Client implements Runnable, ActionListener, WindowListener { … }

public class ClientProgram { … }

 

Sketch code: -- ?? isn't this the client code??

Main() checks command line arguments, build Inet address.

Have 2 threads, one in Client.run(), other in awt GUI framework.

SetLayout – new Canvas, panel, label, TextField, Button, addActionListener.

Establish connection, promote socket to BufferedReader/Writer – if anything fails, give up.

If connection established, construct GUI.

REGISTER + fName, INITIALSTATUS, …

 

The other thread is ready to add/remove clients.

 

AGAIN, I THINK THE BELOW IS FOR THE CLIENT – SHOULD BE FOR SERVER

 

Classes: Server, Info, ClientHandler (which is a Runnable and an Observer), SharedData (yes).

Sketch code:

Server (summary):      

-Receptionist listening at port.

-Main() in class Server checks command line args, creates a server object and sets it looping (to accept clients, create ClientHandler objects and threads, and to terminate).            

-Accept connection.

-Create ClientHandler objects and associated threads for clients.

 

For shared data:        

-Array with the most recent messages.

-Vector with ClientHandlers.

-Automatically notify changes (eg, posts, adds, disconnects) to clients via ClientHandlers

 

Shared data object will pass changes to update() method, ClientHandler will pass changes to the client.

 

ClientHandler:

-REGISTER, INITIALSTATUS

-in the main loop, reads and responds to POST, Quit

-on exit, deregister this ClientHandler and terminate.

 

Shared data:

-an Observable (to inform Observers of changes)

-vectors to store recent messages

 

==

 

Create a thread object, then call its start() method.

 

 

 

 


  1. Explain the streams and filters model used in the java.io package. (1 mark)

 

Package = collection of classes and interfaces.

?? Source is a stream of bytes (which come from/through file, pipe, socket) which is then wrapped in a filter that adds functionality.

Filter =

 

 

 

Eg. wrap a FileReader object in a BufferedReader object and use the methods of the BR class (eg. readLine(), close()) to read the file data.

Pipe = data buffer, one process writes to it, one reads from it. Pipes are recommended mechanism to pass character streams between threads; pipe acts as a buffer (one thread writes to the buffer if it's not full, the other stream reads from the buffer if not empty).

 

  1. Identify major classes (and their responsibilities) for both the byte oriented Input/ Output hierarchy and the Unicode oriented    Reader/Writer hierarchy. (1 mark)

 

 

 

 

Question 4: Java coding

 

  1. A Java application is required that will display ... and allow ....  

 

The program will:  

₯ allow the user to select an input file

₯ read ... from that file

₯ display ... 

₯ allow the user to ... 

 

67.   Sketch the form for the program's display, identifying the classes of the specific Components nested within a main FrameWindow and noting the layout managers needed. (1 mark)

 

Sketch:

 

 

Classes:

 

 

 

Layout managers:

Layout managers = a container property. ………… (Means what??)

Container = a component that serves as a context to group other components.

 

68.   List the classes that you would define for this application; for each class note the data owned by instances and the principal methods. (2 marks)   

 

Classes with data owned:

 

 

 

Methods:

 

 

 

 

  1. Explain in detail the mechanism that you will use to support ...  (3 marks)   

 

  1. Provide the Java code for the function that constructs the visual display by instantiating java.awt classes and appropriately linking up the objects.   (2 marks)   

 

?? Is this "instantiating java.awt classes and linking up the objects"?? :

 

Frame = new Frame();

frame.setLayout (new BorderLayout());

frame.addWindowListener(this), GUI object handles the window closing;

 

Text = new TextArea();

text.setnoEdit();

frame.add(text,'East');

 

I am assuming frames, text, etc. are instance variables of correct type in GUI class.

 

Scrollpane s = new Scrollpane();

frame.add(s, center);

 

myCanvas = new MyCanvas(data object);

DataObject.setLink(myCanvas);

 

DataObject and Canvas need to communicate so set links between them:

            MyCanvas.setMouseListener (myCanvas);

            s.add(myCanvas);

           

Finally I need a panel at  bottom for 2 things: Choice and Action buttons.

            Load choice with file names,

GUI objects will listen to them.

 

Q. How to read data files?
StringTokenizer.

 

  1. Provide the Java code for the function(s) that will read the data …..  (2 marks) 

 

  1. Server side scripting – not sure what the question might be, so here are the basic facts:

 

Q. Why use SSI? Cost. Separate pages that do/don’t need to be processed at the server. How? By using different file extension. When this processing option is activated, server now acts as 1. agent to fetch static html pages, 2. generator for pages with regular dynamic content, 3. agent for launching CGI.

 

Q. Why sub-launch a process when the cost is the same? (Does the same things: Pack the environment variables, set up pipe connection,  read response and incorporate in page.) Web designer can easily redesign an HTML page which has a place (eg, a table) for program outputs. So now we have .shtml pages with HTML directives, content, and these SSI directives (conditional code, loops, database access, process sub-launches) that make web pages with dynamically generated text.

 

Q. Why is ASP wildly successful? Microsoft's IIE 4 (Internet Information Server) included Active Server Pages that do all that SSI does, plus VBScript is now a full programming language, plus database access is standardised.

 

Q. Identify some alternative server scripting technologies? ASP, PERL, PHP4 (Personal Home Page).

Client/server architecture in databases, ftp (= to transfer binary files over the internet), web, Java applets (= part of the webpage transferred from the web server to client browser).

 

 


Last question (Neil went through it): Image Map Program

 

Will need a GUI and some data from a file.

Tell me about the interface – what classes – how to build the interface – how to read the files.

** Review Ass2.

How to display the data? Click causes the screen to be cleared.

 

Sketch the display: < see drawn sketch >

 

What classes do you need in the program?

ExamProgram

            Creates GUI object

GUI

            Owns frame etc

            Handles action button

Handles WindowClosingEvent

Sets up connection among Components

MyCanvas (subclass of Canvas)

            Owns data object

            Passes on paint requests to data objects

            Passes mouse clicks to data objects

Data objects

            Owns collection of regions

            Handles MouseEvents from MyCanvas

 

Class Region (   abstract class)

                        owns

title string

                                    description string

                        does

                                    return title

                                    return description

                                    loads standard data

 

RectRegion       )

CircleRegion     )

PolyRegion       ) all subclasses of Region

            All        does     check containsPoint(pt)

                                    LoadData()

                                                invokes super.loadDad

                                                ihen reads own specific data

                        owns individual coordinate data

 

Use polymorphic collection, eg as Vector

            Vector myRegions = new Vector()

            Add regions to vector.

 

Checking for mouselinks

            Iterator for Vector

            while iterator.hasNext()

                        Region X = (Region)iterator.next……..

                        if (X.containsPoint(1)

                                    …….

 

 


A panel always has a --------- manager.                                      Layout.

 

T/F? Java applications have no ties to web pages.                       T. or to browsers.

 

Java applets are stored as -----                                                   Binary class files, not txt files like HTML does.

 

T/F? Java provides a standardised GUI for all platforms?             T.

 

API = the Java class library?                                                     T.

 

T/F? Applications are secure by default.                                     T.

T/F? Applets are secure by default.                                            F.

 

T/F? Applet class is a subclass of Panel class.                            T.

 

Applets are Java programs that execute where? And do what, overall?    Within the browser. They expand the functionality of the browser by providing logic and data processing capacity.

 

??

In Java, all arguments are passed to methods by ------

Value. Another statement says "all Java arguments are passed by reference." ????????????

 

Running an applet requires a JVM (to run/interpret the bytecode).

But does running an application require JVM.                  Yes, to interpret the byte code Java .class files

 

 

Q. Mouseclicks on canvas.

Are picked up by runtime. Canvas would have to implement MouseListener interface.

The MouseClickEvent() function of the canvas would get called.

It passes request to data object (or we could have made the data object the MouseListener).

DataObject's MouseClickEvent gets called.

DataObject handles the event.

            Get x,y coordinates from event data.

Iterates through its collection of Regions, asking each if it contains Pt.

            If a Region does, ask it for title and description.

Clear main text areas, append the title and description.

 

----------------------

 

Script = A program in a scripting language (a "script") is often interpreted. Function declarations are in the section, with function call later.

scripting language = A loose term for any language that is weakly typed or untyped and has little or no provision for complex data structures.

 

Interpreter = A program that translates an instruction into a machine language and executes it before proceeding to the next instruction.

interpreter = A program which executes other programs. This is in contrast to a compiler which does not execute its input program (the "source code") but translates it into executable "machine code" (also called "object code") which is output to a file for later execution.

Interpreting code is slower than running the compiled code. Access to variables is also slower in an interpreter because the mapping of identifiers to storage locations must be done repeatedly at run-time rather than at compile time.

 

setstats 1