JavaTest Yourself: Java Fundamentals, Part 1

Test Yourself: Java Fundamentals, Part 1

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.


Questions

Lesson 1


Welcome

The purpose of this series of tutorial lessons is to help you learn Java by approaching it from a question and answer viewpoint.

I recommend that you also make use of my online Java tutorial lessons, which are designed from a more conventional textbook viewpoint.  Those tutorial lessons are published at Gamelan.com.

For your convenience, I also maintain a consolidated Table of Contents on my personal web site that links to the individual lessons on the Gamelan site.

Insofar as possible, I will make use of Sun Java in these lessons.  However, it will not be possible for me to go back and do a full update each time Sun releases a new version, so over the course of time, I expect to use different versions of Sun Java.

Just in case you would like to sneak a peek, the answers to the questions, and the explanations of those answers are located (in reverse order) at the end of this file.

The questions and the answers are connected by hyperlinks to make it easy for you to navigate from the question to the answer and back.  It is recommended that you make your first pass through the questions in the order that they appear so as to avoid inadvertently seeing the answer to a question before you provide your own answer.


1. Source File Names:  True or false?  All Java source files must end with the extension .class

Answer and Explanation

2. Separate source File Requirements:  True or false?  A source file may contain an unlimited number of non-public class definitions.

Answer and Explanation

3. Class file names:  True or false?  If a source file includes a public class, the class name must match the unextended filename.

Answer and Explanation

4.  True or false: Each source file that you compile will produce one file with an extension .class

Answer and Explanation

5.  Required programming elements:  True or false.  At least one of the following three top-level elements must appear in every source file.  If they are included in the source file, they must appear in the following order.

A.  package declaration
B.  import declarations
C.  class definitions

Answer and Explanation

6.  Import directives:  True or false?  The compiler does not require you to use import directives.

Answer and Explanation

7.  Import directives:  What output is produced by the following program?

  • A.  A compiler error
  • B.  A runtime error
  • C.  OK
//File Q001_07.java
import java.awt.*;
public class Q001_07{
  public static void main
           
      (String args[]){
    Button aButton = 
            new
Button(“Button”);
    Label aLabel =
           
   new Label(“Label”);
    System.out.println(“OK”);
  }//end mail
}//end class Q001_07

Answer and Explanation

8.  goto and const:  True or false?  As in C and C++, goto and const are keywords that are actively used in Java.

Answer and Explanation

9.  Which of the following characters may be used as the first character in a Java identifier?

A.  x (the letter x)
B.  4 (the number 4)
C.  $ (the dollar sign character)
D.  _ (the underscore character)

Answer and Explanation

Bonus question.  The following question is considerably more difficult than the previous nine questions, and is included here to challenge you if the previous nine questions have been too easy.

10.  Access Control:  What output is produced by compiling and running the following program?  Note that the instance variable named x is declared private (as highlighted in boldface in the code).

  • A.  A compiler error
  • B.  A runtime error
  • C.  15
//File Q001_10.java
class Q001_10{
  public static void main(
           
       String args[]){
    AClass ref1 = new AClass(5);
    AClass ref2 = new AClass(10);
    System.out.println(
           
      ref1.add(ref2));
  }//end main()
}//end class definition

class AClass{
  private int x;
   
  AClass(int x){//constructor
    this.x = x;
  }// end constructor
   
  int add(AClass ref){
    return x + ref.x;
  }//end add()

}//end class AClass

Answer and Explanation


Copyright 2000, Richard G. Baldwin.  Reproduction in whole or in part in any form or medium without  express written permission from Richard Baldwin is prohibited.

About the author

Richard Baldwin is a college professor and private consultant whose primary focus is a combination of Java and XML. In addition to the many platform-independent benefits of Java applications, he believes that a combination of Java and XML will become the primary driving force in the delivery of structured information on the Web.

Richard has participated in numerous consulting projects involving Java, XML, or a combination of the two.  He frequently provides onsite Java and/or XML training at the high-tech companies located in and around Austin, Texas.  He is the author of Baldwin’s Java Programming Tutorial s, which has gained a worldwide following among experienced and aspiring Java programmers. He has also published articles on Java Programming in Java Pro magazine.

Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.

baldwin.richard@iname.com< /i>


 

Answers and Explanations

Answer 10

10.  The answer is C.  The output produced by compiling and running the program is 15.

Back to Question

Explanation

Even though the instance variable named x is private, the variable in the object referred to by ref2 can be accessed by the object referred to by ref1.

The important point is that access modifiers dictate which classes — not which instances of a class — may access features.  Thus, a private instance variable can be accessed by any instance of the class in which the private instance variable is defined.

Answer 9

9.  A (the letter x), C (the dollar sign character), and D (the underscore character) may be used as the first character of a Java identifier.  B (the number 4) cannot be used as the first character of a Java identifier.

Back to Question

Explanation

In Java, a legal identifier is a sequence of Unicode letters and digits of unlimited length.

The first character must be a letter.

All subsequent characters must be letters or numerals from any alphabet that Unicode supports.

The underscore character (_) and the dollar sign ($) are considered to be letters and may be used as any character including the first one.

Answer 8

8.  False.

Back to Question

Explanation

goto and const are reserved words, but are not actively used in Java.  Although they have no meaning in Java, you cannot use them as identifiers.  Apparently Sun did this to avoid confusion, but I have never seen an official explanation (but I admit that I haven’t searched very hard for an explanation).

Answer 7

7.  The answer is C.  This program will produce the output OK.

Back to Question

Explanation

Each import directive can specify the package containing a single class file.

Alternatively, an import directive can use the wildcard character (*) to “import” all of the class files in a specified package.  This program uses the following wildcard version of the import directive to import all of the class files in the package named awt.

import java.awt.*;

This includes both Button and Label.  Therefore, it is not necessary to provide fully-qualified path and package information when referring to either of these classes in the program code.

A word of caution is in order, however.  The purpose of packages is to resolve name clashes among class files having the same names.  If you find yourself referring to two or more different class files that have the same name, they must be stored in different packages, and you cannot use import directives for those class files.  In that case, you must provide a fully-qualified path and package name each time you refer to one of those classes.

It is possible that you could use the wildcard character to import two different packages that contain one or more duplicate class file names.  This could lead to problems.

Therefore, the safest approach is to avoid the use of the wildcard character altogether and to use a separate import directive for each class that you need to refer to in the program.  I have worked as a Java consultant for a couple of companies whose internal programming standards prohibit the use of the wildcard character in import directives.

Answer 6

6.  True.

Back to Question

Explanation

The import directive is provided strictly as a convenience to the programmer.  The compiler does not require you to use import directives.

However, you can often save yourself a lot of extra work by using import directives.  If you don’t use import directives, every reference to a class must provide a fully qualified path and package name for the package that contains the class file.

For example, the following simple program contains references to two classes:  Button and Label.  An import directive, highlighted in boldface, is used to inform the compiler where it can find the class file for the Button class.  No such import directive is provided for the Label class.

As a result, the code required to refer to the Label class (highlighted in red) must specify the package that contains the class file for the Label class.  Otherwise, the program cannot be compiled.  As you can see, considerably more typing is required to refer to the Label class than is required to refer to the Button class (highlighted in blue).
 

//File Q001_06.java
import java.awt.Button;
public class Q001_6{
  public static void main
           
      (String args[]){
    Button aButton = 
            new
Button(“Button”);
    java.awt.Label
aLabel = 
     new java.awt.Label(“Label”);
    
    System.out.println(
           
   aButton.getLabel());
    System.out.println(
           
     aLabel.getText());
  }//end main
}//end class

Answer 5

5.  False.

Back to Question

Explanation

Actually, this is sort of a trick question constructed by joining two separate questions with an implied and.  (You need to learn to appreciate logical expressions constructed using and and or.)

First, it is easy to demonstrate that none of these programming elements are required to be present in a source file, by using the Sun javac.exe program to compile an empty source file.  The fact that javac.exe will happily compile an empty source file (producing no output) causes the overall answer to the question to be false.

However, and this is more important, if any of the three programming elements are included in the source file, they must appear in the following order, so the answer to the second question is true.

A.  package declaration
B.  import declarations
C.  class definitions
 

Answer 4

4.  False.

Back to Question

Explanation

One class file is produced for each class definition in your program regardless of the number of source files and regardless of whether they are top-level classes or inner classes.  Even each anonymous inner class produces an output class file, and the name given to the class file for the anonymous inner class is created by the system.

Answer 3

3.  True.  However, see the qualification below.

Back to Question

Explanation

According to The Complete Java 2 Certification Study Guide, by Roberts, Heller, and Ernest, “This is not actually a language requirement, but is an implementation requirement of many compilers, including the reference compilers from Sun.  It is therefore unwise to ignore this convention.”

Answer 2

2.  True.  A source file may contain an unlimited number of non-public class definitions.  In fact, the source file may  contain one public class definition and an unlimited number of non-public class definitions.  However, the rules change if two or more of the classes are declared to be public.

Back to Question

Explanation

While it is true that a source file may contain an unlimited number of non-public class definitions, such is not the case if the classes are declared public.  Each public class and interface must be contained in its own source file.

The fact that each public class requires its own source file is easy enough to demonstrate.  The following simple Java application fails to compile with a compiler error to the effect that “Public class Dummy must be defined in a file called “Dummy.java”.”

If the public modifier is removed from the definition of the class named Dummy, leaving only one public class in the source file, the application will compile and execute successfully.

(Note that boldface and color were used here to assist the eye in separating the different parts of the program.)
 

public class Q001_2{
  public static void main
           
      (String args[]){
    System.out.println(“OK”);
  }//end main
}//end class

public class Dummy{
  //empty class definition
}//end class definition

class AnotherDummy{
  //empty class definition
}//end class definition

Answer 1

1.  False.  Java source files must not end with the extension .class.  Rather, all Java source files must end with the extension .java

Back to Question

Explanation

1.  When you create Java source files, you need to use a text editor that will produce clean character codes (sometimes referred to as ASCII codes).

The output from the editor must not contain any control characters indicating bold, italics, underline, etc.

Just about any text editor can be used for this purpose.  Various text editors are available on the web that can make the creation of source code easier.  These editors provide features such as causing the various parts of the program to appear in different colors during the editing process , or automatically indenting each line of source code according to generally accepted indentation standards.

Some of the available editors will allow you to compile and execute the Java program from within the editor program, which can be a real time saver during development.  Editors of this type are often referred to as Integrated Development Environments (IDE).

Back to the point of the discussion, the file name of all source code must end with the extension .java  If your editor doesn’t put it there, you will need to rename the file manually to create the correct extension.

When you successfully compile the program, one or more files will be produced by the compiler having the extension .class


Copyright 2000, Richard G. Baldwin.  Reproduction in whole or in part in any form or medium without  express written permission from Richard Baldwin is prohibited.

About the author

Richard Baldwin is a college professor and private consultant whose primary focus is a combination of Java and XML. In addition to the many platform-independent benefits of Java applications, he believes that a combination of Java and XML will become the primary driving force in the delivery of structured information on the Web.

Richard has participated in numerous consulting projects involving Java, XML, or a combination of the two.  He frequently provides onsite Java and/or XML training at the high-tech companies located in and around Austin, Texas.  He is the author of Baldwin’s Java Programming Tutorial s, which has gained a worldwide following among experienced and aspiring Java programmers. He has also published articles on Java Programming in Java Pro magazine.

Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.

baldwin.richard@iname.com

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories