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