Saturday, February 26, 2011

Chapter 62: Other Topics of Importance

So far, over the past chapters, we have covered a lot of topics that feature in the SCJP exam syllabus. Apart from this, there are a few other minor topics that you need to know which might feature in the exam questions.

Before we start, I have to tell you that this is going to be the penultimate chapter in this SCJP series and well, I am really glad that both of us have made it so far.

So without much delays, lets get started!!!

Compiling Java Programs

The javac command is used to invoke Java’s compiler and compile a Java source file.
A typical invocation of the javac command would look like below:

javac [options] [source files]

Both the [options] and the [source files] are optional parts of the command, and both allow multiple entries. The following are both legal javac commands:

javac -help

The first invocation doesn’t compile any files, but prints a summary of valid options. The second invocation passes the compiler two .java files to compile ( and Whenever you specify multiple options and/or files they should be separated by spaces.

This command would create the .class files that would be require to run the java progam.

Compiling with -d

By default, the compiler puts a .class file in the same directory as the .java source file. This is fine for very small projects, but once you’re working on a project of any size at all, you’ll want to keep your .java files separated from your .class files. The -d option lets you tell the compiler in which directory to put the .class files it generates (d is for destination).

Lets take a look at two example commands:

javac -d classes source/
javac -d ../classes com/scjp/test/

Example 1 – Compile file named “” that is present inside the “source” sub-directory of the current directory and put the .class file in the “classes” sub-directory of the current directory

Example 2 – Compile the file named “” that is present in the following directory hierarchy “com/scjp/test/” from the current directory and put the .class file in the folder “classes” that is present one level above the current directory

One thing you must know about the -d option is that if the destination directory you specify doesn’t exist, you’ll get a compiler error. If, in the previous example, the classes directory did NOT exist, the compiler would say something like:

java:5: error while writing MyTestClass: classes/ MyTestClass.class (No such file or directory)

Running Java Programs

The java command is used to invoke the Java virtual machine. This command invokes the JVM and asks it to run the program that is specified in the argument.

java [options] className [args]

The [options] and [args] parts of the java command are optional, and they can both have multiple values. You must specify exactly one class file to execute, and the java command automatically assumes that you’re going to send only a .class file, so you don’t have to specify the .class extension on the command line. Here’s an example:

java MyTestClass 1 2 3

The above command invokes the .class file of our test class MyTestClass and passes 1, 2 and 3 as command line arguments.

For fun, just assume that the hypothetical code inside MyTestClass expects 3 command line arguments. Don't worry, am not going to bore you with the code of that class here…

Using System Properties

For the exam you need to know how to access the properties of the system in which you are running your programs.

Java has a class called java.util.Properties that can be used to access a system’s basic information like the current versions of the operating system, the Java compiler, and the Java virtual machine. In addition to providing such default information, you can also add and retrieve your own properties. Ex:

import java.util.*;
public class TestProperties {
public static void main(String[] args) {
Properties p = System.getProperties();
p.setProperty("props", "value");

If this file is compiled and invoked as follows:
java -DcompileTimeProp=compileTimeVal TestProperties

You’ll get something like this:
... XP
java.specification.vendor=Sun Microsystems Inc.
There will be a lot more values printed on the console. To save space I just put out the information we are interested in…

Two name=value properties were added to the system’s properties: props=value was added via the setProperty method, and compileTimeProp=compileTimeVal was added via the -D option at the command line. When using the -D option, if your value contains white space the entire value should be placed in quotes like this:
java -DcompileTimeProp="compileTimeVal take 2" TestProperties

To repeat - when you use -D, the name=value pair must follow immediately, no spaces allowed.

The getProperty() method is used to retrieve a single property. It can be invoked with a single argument (a String that represents the name (or key)), or it can be invoked with two arguments, (a String that represents the name (or key), and a default String value to be used as the property if the property does not already exist). In both cases, getProperty() returns the property as a String.

Using Command-Line Arguments

You would probably know to handle or rather use command line arguments in your java program. But, just for the sake of completeness am putting out a simple example that handles command line arguments in the code. For the exam you need to know this (Why else would I bore you with such miniscule topics :-))

public class CommandLineArgExample {
public static void main(String[] args) {
int x = 0;
for(String s : args)
System.out.println(x++ + " element = " + s);

compiled and then invoked as follows

java CommandLineArgExample 1 A
the output will be
0 element = 1
1 element = A

Like all arrays, args index is zero based. Arguments on the command line directly follow the class name. The first argument is assigned to args[0], the second argument is assigned to args[1], and so on.

Exam Tip:
The main() method signature can be tweaked a little bit. So don't be confused or surprised if you see something you arent used to.
The following are all legal declarations for main():
static public void main(String[] args)
public static void main(String... x)
static public void main(String king_kong[])

Static Imports

Static imports is a new feature that was introduced as of Java 5. You already know that an import statement is required to include code from other java classes and APIs that are not part of the current class you are coding. These static imports were implemented to provide greater keystroke-reduction for programmers. Though, not many of us appreciate it, nonetheless, you may end up getting a question on this topic and hence it is my duty to cover this topic.

Without static imports:

public class RegularClassCode {
public static void main(String[] args) {

With static imports:

import static java.lang.System.out;
import static java.lang.Integer.*;
public class UseStaticImportsCode {
public static void main(String[] args) {

Both classes produce the same output:

I guess, you already figured out whats happening here. By importing the System class, we were able to directly invoke its static methods. So instead of saying System.out.println() we just said out.println().

I personally am a little skeptical about the usefulness of this feature because, though we don't have to write System.out.println() everytime, if a new programmer who doesn't know what static imports is (cant expect everyone to know everything, isnt it?) opens up your code, he’ll be confused as to how in the hell did this guy print stuff on the console without using System.out.println() method.

There are a couple of rules for using static imports:

• You must say import static; you can’t say static import.
• Watch out for ambiguously named static members. For instance, if you do a static import for both the Integer class and the Long class, referring to MAX_VALUE will cause a compiler error, since both Integer and Long have a MAX_VALUE constant, and Java won’t know which MAX_VALUE you’re referring to.
• You can do a static import on static object references, constants (remember they’re static and final), and static methods.

Previous Chapter: Self Test - Chapters 55 to 61

Next Chapter: Some last words before you take the SCJP Certification

No comments:

Post a Comment

© 2013 by All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.