June 20, 2023

Java on Fedora - a second program

I am trying things and experimenting. Can I introduce other methods and classes and how does it all work?
import java.lang.Thread;
import java.util.stream.IntStream;

class MyCounter {
    static public void Sleeper( int sec ) {
	try {
	    Thread.sleep(sec*1000);
	} catch (InterruptedException e) {}
    }

    static private void test1 ( int num ) {
	for ( int i=0; i System.out.println(x));
    }

}
The above all works just fine. One odd thing is that when I call Thread.sleep, I must do it inside a try block. The story is that an exception just might happen during the sleep and I must be ready to handle one.

The only other surprise is when I put a second class into this one file. After I run javac, I have two class files!

-rw-r--r-- 1 tom tom 1201 Jun 20 13:55 MyCounter.class
-rw-r--r-- 1 tom tom 1076 Jun 20 13:55 Tester.class
However when I type "java MyCounter", everything works just fine.

What about a second file?

As software becomes complex, it is often beneficial to break it up into multiple files. Java does have "packages", but I don't know a thing about them.

It is easy enough to put a class in its own file and compile it with javac to get (in my case) Pickle.class. And it turns out that nothing extra is required to tell Java about this other file, the following just works:

javac count.java
javac pickle.java
java MyCounter
No need to put import statements into count.java or to put package declarations anywhere.
Here is "pickle.java" --
class Pickle {
    public Pickle ()
    {
    }

    public void show ()
    {
        System.out.println("Showing the pickle!");
    }
}
And here is "count.java" that uses the Pickle class --
import java.lang.Thread;
import java.util.stream.IntStream;

class MyCounter {
    static public void Sleeper( int sec ) {
	try {
	    Thread.sleep(sec*1000);
	} catch (InterruptedException e) {}
    }

    static private void test1 ( int num ) {
	for ( int i=0; i System.out.println(x));
    }

}
No shocking surprises or unpleasant hassles.
Have any comments? Questions? Drop me a line!

Adventures in Computing / tom@mmto.org