Java API versions
- Q: What's the difference between the Java versions?
-
A: The major release versions of the Sun Java Software Development Kit (SDK, also known as the Java Development Kit, JDK) include significant Application Programming Interface (API) changes that provide extra programming features built upon the core Java software platform. That means that the basic features of the Java language do not change from one release to the next, so most existing programs will run successfully when compiled with the new SDK.
Some core packages may gain additional features in new Java releases, but it is very rare for established API features to be removed, which would break backwards compatibility. Superseded or problematic API methods are usually marked deprecated before they are removed altogether, to give programmers the chance to upgrade their code to the new standard. Deprecated classes and methods can still be used to develop and run Java programs, but the compiler will issue warnings.
Oracle publish a set of release notes for each SDK release with their archive of previous Java SDK releases.
- Q: What are legacy classes?
-
A: The term legacy has a similar meaning to its everyday usage; something that is left behind from an earlier time or passed down from one's ancestors.
In Java, legacy classes are system components that we continue to work with, even though they may be deprecated, use deprecated methods or sub-optimal programming techniques, for example. Systems may use legacy classes from third party suppliers that are no longer maintained, for which no source code is available.
Ideally, one would replace such legacy classes with contemporary implementations, but sometimes the extent of a system's dependence on legacy classes makes them difficult or un-economical to replace. In this case, it is often necessary to use adapter classes that enable legacy classes to work with new programming interfaces.
- Q: What is the difference between API and help in Java?
-
A: A Java Application Programming Interface (API) is a packaged set of classes, interfaces, variables and methods that a programmer can use to write their own Java programs. The Java language has a syntax to include documentation comments amongst the code of a program to explain its purpose, example usage and advisory notes. The Java Software Development Kit (SDK) includes a JavaDoc tool to automatically generate HTML format API documentation from these embedded documentation comments, which are a form of online help.
Many Java Integrated Development Environments (IDE) also include code completion as you type, based on the API packages used in a project. When the IDE recognises the start of a method name associated with a known Java type it may prompt to complete the statement. This type of context-aware help is based on the contents of a Java API but is not part of the API itself.
- Q: Where can I find out more about the Java API?
-
A: You should download the Java SDK API documentation or read online. The standard Java documentation gives full details of all public methods and usage guidelines for all classes and is an excellent place to start, and for quick reference.
Java system integration
- Q: How do I get the name of the operating system?
-
A: To get the operating system name in Java use the static
System.getProperty("os.name")method, which returns a string. Other operating system property keys includeos.archfor the hardware architecture andos.versionfor the version number, as below. - Q: What is
System.out? -
A:
System.outis a static variable that refers to the console output. The object type ofSystem.outisPrintStream, notPrintWriter, but it has similar overloadedprintlnmethods. These print methods can be called by any class using the staticSystem.outreference. - Q: Are the Java console streams subclasses of
System? -
A:
System.outis a static variable of theSystemclass that holds a reference to aPrintStreamused to channel output to the host system's console.System.erris also aPrintStreamandSystem.inis anInputStream. When the Java runtime system starts up it automatically hooks-up these object references to the host system's output, error and input streams.The
PrintStreamandInputStreamtypes used to interface with the host system are not subclasses of theSystemclass, they are a subclasses of thejava.io.OutputStreamandInputStreamhierarchy. Notably thePrintStreamclass never throwsIOException, though you can use thecheckError()method to discover any problems.The common technique of making print calls with
System.out.println()gives the impression thatprintln()may be a method of theSystemclass but it is not, it is a method of thePrintStreamclass. - Q: How do I find the size of an object in Java?
-
A: There is no direct management of the storage size of code that is held in memory by the Java Virtual Machine (JVM). The virtual machine manages the allocation and de-allocation of storage through an integral garbage collection system. The JVM keeps track of all object references and periodically disposes of de-referenced objects to free memory.
It is possible to check the overall memory use of a Java application with methods in the
java.lang.Runtimeclass. ThefreeMemory()method returns the spare memory available to the runtime system, thetotalMemory()method reports the total memory allocated to the virtual machine, so you can deduce the memory in use, as below. - Q: How can I copy process information from Windows task manager?
-
A: Getting information from Windows system applications relies on the programs having command line interfaces that a Java program can read from. Windows Task Manager program does not seem to support command line arguments to interrogate running processes, nor standard output, so you may need to interface with a different program to get the information you seek.
The example below uses the Java
ProcessBuilderclass to create aProcessthat opens the Task Manager graphical user interface application. The same approach can be used to run other system tools or installed applications, provided you know the path to the executable program and can supply any appropriate arguments.
Java exceptions
- Q: What's the difference between checked and un-checked exceptions?
-
A: A Java checked exception represents a problematic case that can be anticipated when one instantiates an object or calls a method. A typical example is when you attempt to create a file or open a URL connection, which may fail for many reasons. Checked exceptions must be declared in the
throwsstatement of a method header, and any class that calls the method must ensure that it handles all checked exceptions that may occur. - Q: What is a
NullPointerExceptionin Java? -
A: A
NullPointerExceptionis a runtime exception that indicates the Java Virtual Machine attempted to call a method on an object, but the object reference wasnull. This case may occur when a reference is assigned from another method call that may return anullvalue, such as aHashtablelook-up. - Q: What's the best way to handle a
NullPointerException? -
A: The best way to handle a
NullPointerExceptionis to prevent one being thrown to begin with. ANullPointerExceptionhappens when anullvalue is assigned to an object type variable, then a method is called on that variable. The variable is expected to hold a "pointer" or reference to an object, but actually holds anullvalue, hence "null pointer".This type of exception can also happen when you try to get or set a field on a
nullobject reference, operate on the reference as if it was an array, or throw it as if it was an exception.A
NullPointerExceptionis a runtime exception that you should not try to catch. Avoid the exception by checking the value before a call, as in the example below with theSystem.getProperty(String)method. ThegetProperty()method is expected to return aStringvalue for a given system property, ornullif the property does not exist. - Q: Can you give an example of catching an exception?
-
A: One common example of catching an exception is when you try to read from a file that may not exist. You may enter a file name as the first argument on the command line, for example:
- Q: How can I throw a
NumberFormatExceptionback to themain()method? -
A:
NumberFormatExceptionis an un-checked exception. That means that the compiler will not enforce that your application catches the exception and handles the case. For example, users may enter an invalid number at runtime and the application would throw an exception and crash.If you want to handle runtime exceptions it is important to handle them in the methods in which they may occur. The callers of such methods cannot be expected to know that they would throw a runtime exception and handle them. Your methods should include validation and handling for specific, anticipated runtime exceptions.
If you want to signal a problem that cannot be handled locally by your method, you should catch the runtime exception and throw a checked exception, as below. This is a typical case for creating your own checked exception type, though rather heavyweight for this simple example.
Class loading
- Q: How can I get a class reference without using
newoperator? -
A: There are two questions here, first why would you want to get a class reference without using the
newoperator? Often this is the case when you need to load a class at runtime, but you do not know in advance what class it is. In this case, you might configure the class name in a properties file and load it using the staticClass.forName(String)method, as below. - Q: What's the difference between the
Class.forName()method and thenewoperator? -
A: The
Class.forName()method is different from invoking the new operator for a class because it does not return an instance of the class. TheforName()method initialises a class and returns aClassobject. - Q: What is the return type for the
Class.forName(String)method? -
A: The return type for the static
Class.forName(String)method is aClassobject reference for the class named in the string argument. This is not the same as an instance of the class itself. You must use thenewInstance()method on the class reference to obtain an instance of the named class. You can also create an instance indirectly by obtaining aConstructorreference from the class and call itsnewInstance(Object[])method. - Q: How can I implement the
Class.forName()scheme? -
A: To use this method of class loading, the dynamically loaded class only requires a default constructor, with no arguments, and be a known type. Once the class is loaded, then use the
Classobject'snewInstance()method to get a new object reference for the class. You must also handle a number of exceptions that may be thrown if the class is not found, cannot be loaded, etc. The example below expects to load a class that implements theShapeinterface and has a default constructor. - Q: How can I cast an unknown sub-class returned by
newInstance()? -
A: When you want to instantiate one of several possible sub-classes at runtime it is best to create an interface type that defines the common behaviour of those classes. For instance, you might define a
Processorinterface with one common method, as shown below. - Q: Is
Class.forName()runtime polymorphism? -
A: The
Class.forName()scheme is an application of polymorphism that is applied at runtime, so can be regarded as an example of runtime polymorphism. However theClass.forName()scheme has to be designed into an application in advance, the polymorphic aspect is not created at runtime, it is only expressed at runtime.
Java Abstract Window Toolkit classes
- Q: How do I draw a
Rectangleon aGraphicsinstance? -
A: When you have a method that takes an object as an argument, you must pass an object of the specified type in the method call. There is no
Graphicsmethod that accepts aRectangleto draw, nor aRectanglemethod that accepts aGraphicsobject to render to.Since
Graphicsis an abstract class, you must obtain a concrete implementation. You can then use itsdrawRect(int x, int y, int width, int height)method to draw an outline of your rectangle, as below. - Q: What is the difference between heavyweight and lightweight components?
-
A: Java Graphical User Interface (GUI) components are called heavyweight when they rely on components from the underlying operating system to be displayed. This is because these native "peers" have a relatively heavy processing demand to render on screen and maintain their state representation. Thus applications composed of many heavyweight components can become slow to render on screen.
No comments:
Post a Comment