September 22, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

SJCP Exam Preparation: Language Fundamentals, Part 1

  • January 2, 2002
  • By Koray Guclu
  • Send Email »
  • More Articles »

Objectives

You are going to be asked to answer questions in the exam regarding the following subjects. So be sure that you understand everything. After reading each article I suggest you write and compile small Java programs. I believe that practice is always better than theory. At the exam, you will be asked to address the following topics[2]. 
  • Identify correctly the construction of a java source file
  • package declaration
  • Importing classes, and the declaration of import statements
  • class declarations
  • interface declarations
  • Constructor declarations
  • Method declarations
  • main() method and correspondence between the index values and arguments passed to the main() method

If you have any questions after studying this document, do not hesitate to drop me an e-mail, and I will try to clarify things as best as I can.

You can read more information about SJCP certification from the SJCP Web page [2] and you can download the .pdf file called Sun Certified Programmer for Java 2 Platform Success Guide [3].

Koray Guclu

The Structure of Java Source Files

A java source file consists of class or interface declarations. Every  source file has a .java extension and a file name in the form filename.java. After compilation, a valid java byte code file has a .class extension and a file name in the form filename.class. A Java source file can be compiled by the javac executable utililty, to compile a java source file you must use "javac filename.java"  command. If there are no compile time errors then a java executable file will be created. The name of this newly created file will be filename.class. This is a Java executable file. We can run this file by typing "java filename.class" in the command prompt. The extension of the source file changes after compilation of a source file but the filename remains the same.

There is a correlation between the file name and class names inside the java source file. If there is a class or interface declared as public, then the name of the java source file must match the class or the interface name which has been declared as public.


// File name: Employee.java
public class Employee {
// class body
}
/* File name must be 
*  Employee because we have 
*  a public class called 
*  Employee. Since this is 
*  a source file the extension 
*  must be .java   */

What you should bear in mind is the public accessibility modifier. If the source file doesn't contain any public class or interface then the compiler will not complain. In this case, the file can be given a name which is different from the class or interface name declared inside the source file. Please note, the file name given should have some relevance to whatever the classes function is.


// File name: Order.java
class PendingOrders {
// class body
}
/* File name can be any 
*  because we don't have a 
*  public accessibility 
*  modifier. Since this is 
*  a source file the extension 
*  must be java. */

We have seen two possible cases for source code declaration. What if we have two or more class declarations in a source file? How should we name the source file in this case? Lets remember the previous rule. If a class declaration has a public accessibility modifier then the name of the source file must match the public class name. This is the only rule that we must bear in mind. The file name of the source code can be anything, if there is no public class declaration at all. This means that we can have more than one class defined in a source file. Because they are not declared as public, we don't care about the class name and the file name. So what if we have a source file which has more than one public class declaration? According to the rule, the file name must match the name of the public class declaration. Because there are more than one public class declarations, the compiler will complain and throw up a compile time exception. There can only be at the most one public class declaration in a source file.


// File name: Order.java
public class PendingOrders { // ERROR !
// class body
}
public class Order {
// class body
}
/* More than one public class 
*  declaration will cause a compile 
*  time error.
*  In that case the compiler will 
*  complain about PendingOrders() class
*  because Order{} class has the same 
*  name as the source file. 
*  We can solve this problem 
*  by deleting "public"  
*  in front of the PendingOrders  
*  class   */

A source file cannot have more then one public class declaration. At most only one public class declaration is allowed per source file and the name of the source file must match this public class declaration name.

If the accessibility modifier is not declared, which means default accessibility, then any number of classes can be declared in a source file. In this case there is no relation between the name of the source file and the name of the classes.


// File name: Order.java
class PendingOrders {
// class body
}
class Orders {
// class body
}
/* More than one class can
*  be declared in a source file
*  and the filename can be anything.
*  Because, there is no public
*  classes declared. */
 

Besides that, it is not allowed to define more than one class, which has the same name, in a source file. The names must be unique or else each class must be declared in a different package.


// File name: Order.java
public class Order { // ERROR !
       // class body
}
class Order { // ERROR!
       // class body
}
/* There can not be more 
*  than one class declaration
*  with the same name.*/

There can be at the most only one public class declaration in a source file. If there is a public class declaration inside the source file then the name of that class  must match the name of the source file. 


// File name: Order.java
public class Order { // OK
          // class body
}
class PendingOrder { //OK
          // class body
}
/* The name of the source
*  file and public class 
*  declaration is the same.*/

A valid Java source code, compilation unit, can have three basic elements. None of these elements are mandatory. The compiler will not complain even if there is an empty source file. But if they are present they must be in the following order.

  • A package declaration (you can only have one package declaration)
  • import declarations
  • class or interface declarations

package com.earthweb.java.certification;
import java.util.*;
public class Flower {
        // class body
}

The compiler will complain if the order is not correct. For example, for the following code snippet the compiler will throw a compile time error because the package and import statements are present, but they are not in the correct order thus - package->import(s)->class(es)/interface(s).


public class Flower {
        // class body
}
package com.earthweb.java.certification; //ERROR!
import java.util.*; // ERROR!

Declaration of package  

Packages are used as a naming organization unit. They don't have any relationship to the scope of the variables in the source code. If a package statement is used in a source file, compilation of that source file will create a directory structure that is similar to the package structure. For example, compilation of the following code will create the Flower.class file at the end of the directory structure "com/earthweb/certification". As we can see the directory structure is the same as the package naming structure.


package com.earthweb.certification;
public class Flower {
         // class body
}

There can be at most only one package declaration per source file and if a package name is used it must be the first statement in the source code.

Importing classes, and declaration of import statement 

An import declaration is the first declaration following the package declaration. Contrary to packages, there can be more than one import statement. If there is no package declaration then the import statements can be the first statement(s) in a source file.


import javax.servlet.*;
import java.util.*;
public class Flower {
        // class body
}

The compiler ignores duplicate imports. If we import java.util.Date twice the compiler will simply import one and ignore any others.

The Java compiler imports java.lang.* package by default. For this reason, there is no need to declare the statement in order to use java.lang.System, java.lang.Math, java.lang.Thread classes which are included in the java.lang.* package. Any classes which fall under the java.lang.* package can be used without declaring the import statement.

Note, importing a package does not import sub packages recursively. Importing java.* does not mean that we also import java.util.*.

Declaration of class or interface

They are called as a top-level class or interface. A top-level class is a class whose declaration is not enclosed by another class.


public class Car { // Top-level class
       // class body
}

The file name of this source code must be Car.java because, as I am sure you remember from the rule, it is declared as public and the class name must match the file name. Inside of a class we have member methods and member variables. The following code snippets show the use of member variables and member methods.


public class Lamp {
 // Member variables 
    int voltage; 
 // Member Method  
    void turnOn() {
    }         
    void turnOff() {
    }         
}

Interfaces only have method names without any implementation of those methods. The following code shows a simple interface declaration.


public interface Engine {  
       void start();
}
 

When does a compiler error occur?

The compiler will throw a compile time error if a class is imported twice by using its exact name with its package structure.


import java.util.Date;
import com.earthweb.certification.Date; // ERROR!

To get rid of this problem, the whole package can be imported instead of the exact class name. The following code snippet shows the solution to the problem.


import java.util.*;
import com.earthweb.certification.Date; // OK!

Declaration of a class, which has the same name as the imported class, will cause a compile time error. 


import com.earthweb.certification.Date; // OK!
public class Date { // ERROR!
         // class body
}

It is not allowed to use the same class name as the name of the imported class.

Declaration of a Class/Interface

In a class declaration, there can be member variables,  constructors, method declarations & implementations. Multiple inheritance is not allowed in java. For that reason, you can not extend multiple classes. You can only implement multiple interfaces. The general syntax for a class declaration is as follows.


[modifiers] class ClassName
          [extends SuperClassName_OneAndOnly]
          [implements SuperInterfaceName,
           SuperInterfaceName1,
           SuperInterfaceNameN] {
           // Class body
}

A simple example for a sports car class which extends the car class is shown below. Multiple inheritance is not allowed in Java. 


class SportsCar extends Car { // OK
         //Class body
}

Since multiple inheritance is not allowed in java, doing so will cause the compiler to throw a compile time error.


class SportsCar extends Car, Engine { // Error !
         //Class body
}

Contrary to that, Java allows for the implementation of multiple interfaces. As shown in the following code snippet car class implements engine and sports wheels interfaces.


class SportsCar extends Car implements Engine, SportsWheels { // Ok !
         //Class body
}

It is not mandatory to declare an access modifier. If we do not define any access modifier, this means the default access will be applied. The modifiers are shown below.
public protected private  
abstract static final strictfp

These modifiers don't suit every case. There are some special conditions for use of these modifiers. As an  example, you can not use private, as a top-level class modifier. You can only use the public modifier or no modifier (default access) for this top-level class declaration. The private and the public modifiers can only be used by the member classes. You can read the SCJPE Preparation series Top-level and Inner Classes section to learn more about this topic.

An interface declaration may seem like a class declaration. The difference being, an interface can not have a method implementation. They can only have method names and member variables. An interface can extend multiple interfaces. The general syntax of an interface is shown below.


[modifiers] interface InterfaceName
             [extends SuperInterfaceName,
              SuperInterfaceName1,
              SuperInterfaceNameN] {
               // Interface body
}

I will mention the details of a class, an abstract class and an  interface in the following chapters. Here is an example of an interface declaration


interface Player {
   void run(); 
}

Method declarations

The general structure of a method inside a class is as follows.


class ClassName {
      [modifiers] returnType MethodName( [Arguments] ) {
      // Method body
      }
}

Methods defined inside classes may have implementations. For example, we have an implementation for the move method of the Car class as follows


class Car {
      public int move(int amount) {
      // Method body
      }
}

For interfaces, we can not define method bodies. Interfaces are only to define method signatures as shown below


interface Car {
      public int move(int amount);
}

Constructor declarations

Inside of the class body we have constructors, variables and method declarations. The syntax of a constructor declaration is like this.


class ClassName {
     [ContructorModifiers] ClassName( [Arguments] ) {
     // Constructor body
     }
}

As you can see from the above syntax a constructor can never have a return type.  Besides that, only the following modifiers can be used as a valid modifier for constructors.

public protected private

The following code snippet shows a class with a valid constructor.


class Car {
   int velocity;
   //Constructor 
   Car() {
    velocity = 0;
   }
   //Constructor
   Car(int initial) {
    velocity = initial;
   }
}

An interface can not have a constructor because an interface does not provide the facility for implementations. For that reason, trying to compile the following will cause an error.


interface Player {
     Player(); //Error
}

The main() method

Every Java application must have a main() method. The structure of Applets and Servlets are different, for this reason they have special mechanisms to execute the code and they don't need a main() method in order to do this. The structure of the main() method is shown below 


class Game {
      public static void main( String arg[]) {
      // Method body
      }
}

We can define the argument in various different ways and they are all acceptable with the exception of the last.

// OK!
public static void main(String args[]){ }

// OK!
public static void main(String[] args){ }

// OK!
public static void main(String [] args){ }

// OK!
public static void main(String args []){ }

// OK!
public static void main(String s []){ }

// ERROR!
public static void main(String args) {}
// No error at compile time but when
// you try to execute JVM will throw an error
// java.lang.NoSuchMethodError: main

The signature of the main() method must be the same. Basically the main() method must have a string array argument, must return void , it must be static and have a public modifier. Since main() is a method, you can inherit the main() method. It acts like other methods. The following examples illustrates valid and invalid definitions of the main() method.

// OK!
public static void main(String args[]){ }

// OK!
static public void main(String args[]){ }

// OK!
final public static void main(String args[]){ }

// OK!
final static public void main(String args[]){ }

// ERROR!
static void public main(String args[]){ }

The main() method can take a string array as an argument. This argument gives us commands entered at the command prompt. For example, we have the given arguments to the Game application at command prompt.


C:\Gamelan>java Game.class param1 param2

We can get the number of arguments by args.length. The first arguments is the first element of the args[] array, which is args[0]. For the previous example args[0] will return param1. It will not return the program name or something else. It will return the first parameter param1.

Questions

1.)    Which of the following are legal Java programs. Select all the correct answer.
        a.)// The comments come before the package
      package com.gamelan.certification;
      import java.util.*;

        b.)import java.util.*;
     
package com.gamelan.certification;
      class Game();

        c.)package com.gamelan.certification;
      import java.util.*;
 
      d.)package com.gamelan.certification;
     
package com.gamelan.certification;
      import java.util.*;
      class Game();

       e.)package com.gamelan.certification;
      class Game{};

       f.)import java.util.*;
      class Game{};


2.) Which of the following statements are correct. Select all correct answers. 
        a.) A Java program must have a package statement. 
        b.) A package statement if present must be the first statement of the program 
        c.) An empty file is a valid source file. 
        d.) A Java file without any class or interface definitions can also be compiled. 
        e.) If an import statement is present, it must appear before any class or interface definitions. 

3.) Which of these are valid declarations for the main method? Select all correct answers. 
        a.) public static void main(); 
        b.) public static void main(String args[]); 
        c.) static public void main(String); 
        d.) public static char main(String args[]); 

4.) What gets printed on the standard output when the class below is compiled and executed by entering "gamelan is the best java source". 
    public class test {
        public static void main(String args[]) {
            System.out.println(args.length+" "+args[0]+" "+args[args.length-1]);
        }
    }

        a.) The program will print "5 gamelan java" 
        b.) The program will print "6 gamelan java"  
        c.) The program will throw an exception.  
        d.) The program will print "5 gamelan source"  
        e.) The program will print "6 gamelan source"  
        f.) The program will compile without an exception and will not print anything.  


 Answers

I suggest you compile and try other possible combinations by yourself. Practical work is important for the exam. Instead of just looking at the answers try to compile code and learn from the results you receive.

1.) a,c,e,f
2.) b,c,d,e
3.) b
4.) e

References ]
[ 1 ]. Java Language Specification (Second Edition) by James Gosling, Bill Joy, Guy Steele
[ 2 ]. Information about SCJP Certification
[ 3 ]. Sun Certified Programmer for Java 2 Platform Success Guide
[ 4 ]. SJCP Exam Preparation: Top-level and Inner Classes
Previous Articles ]
[ 1 ]. Top-level and Inner Classes
Credits ]
I would like to thank to Francis Hutchings for his valuable efforts for the review of this text. 

About the Author

Koray Guclu works as a freelance writer and software developer. You can reach him at korayguclu@yahoo.com. His Web site is http://www.geocities.com/korayguclu/.






Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel