Week 2 Answers


  1. Find out how many classes get loaded when you run "helloworld"

    You might be able to do this by using calls from within your program to ask the JVM how many classes are loaded, but a much easier way is to say:

    java -verbose:class helloworld

    and then count the number of lines that is output.

  2. Produce some html documentation for a program you've written

    Hopefully you found out about the javadoc command for this, and that you have to write your comments in a particular format in order for javadoc to pick them up.

  3. write a "hello world" program and another program which says "goodbye world". Now make the "helloworld" program execute the "goodbyeworld" program.

    Do this by invoking the main method of goodbyeworld from within helloworld. E.g.

    public class helloworld {
        public static void main(String[] args) 
        {
            System.out.println("hello world");
    	goodbyeworld.main(args);   // Note you have to pass a "String[]" argument
        }
    }
    
    When you compile "helloworld", you may find that the compiler complains that it can't find "goodbyeworld", because it may not (depending on what you have CLASSPATH set to) be looking in the right directory. Assuming both your programs are in your current directory, then use either:
    javac -sourcepath . helloworld.java
    
    or
    javac -classpath . helloworld.java
    
    The difference between these commands is that when you specify "sourcepath", the compiler will look for goodbyeword.java and compile it, and will fail if it can't find it - even if goodbyeworld.class exists.

    In the second case, the compiler will look for goodbyeworld.class, and if it can't find it will then look for goodbyeworld.java and compile it. So it will fail if neither goodbyeworld.class NOR goodbyeworld.java is found.

  4. Write a program that counts the number of words in sentences

    One way of doing this is:

    import java.util.*;
    
    public class countwords 
    {
        public static void main(String[] args) 
        {
    	int numSentence = args.length;
    	System.out.println("You gave me " + numSentence +
    			   " sentence" + ((numSentence == 1 ? "" : "s")));
    	
    	for (int i=0; i<args.length; i++) {
    	    System.out.print("Sentence " + (i + 1) + " has ");
    	    StringTokenizer st = new StringTokenizer(args[i]);
    	    int words = 0;
    	    while (st.hasMoreTokens()) {
    		words++;
    		st.nextToken();
    	    }
    	    System.out.println("" + words + " word" 
    			       + ((words == 1) ? "" : "s"));
    	    
    	    
    	}	
        }
    }
    
    

Back to index page