Java Basics
File Structure
The class MyClass
should be defined in a file called MyClass.java
.
Compiling
To compile a project, use the command line
javac MainClass.java
where MainClass.java contains the main method. If MainClass.java refers to other classes (through import statement or by belonging to a package), the compiler searches for the appropriate class files on the CLASSPATH. If it finds no .class file, or if it finds a corresponding .java file that has been modified more recently than the .class file, it will compile the .java file. Thus, the compiler has the functionality of make built in.
Running
java MainClass
will run the program.
java -Xmx1000M MainClass
sets the maximum heap size to 1000MB.
The classpath
I have packages/directories "utility" and "cluster" in my home directory. cluster depends on utility, so I compile utility first. To compile cluster, I give the following command from my home directory:
javac -classpath "." cluster/*.java
Example script:
#!/bin/bash
#!/bin/bash
cd /home/barney/work/mmm/code
CP=classes
CP=$CP:../../utility/classes
CP=$CP:lib/mysql-connector-java-3.0.11-stable-bin.jar
/opt/sun-jdk-1.4.2.05/bin/java -classpath $CP mmm.RunControl report
Packages
To include class MyClass in package betty.sue, the first line of MyClass.java should be
package betty.sue;
and MyClass.java, MyClass.class should be stored in directory sue, which is in directory betty.
To use a class from a package:
import <package_name>.<class_name>;
or
import <package_name>.*;
Each has the same performance, but the first form might serve as a mnemonic.
If the current class already belongs to a package (its first line uses the package statement), then the import is implied.
Classes have package visibility by default.
To execute something in a package, the directory containing the package directory structure must be in your classpath. In the example above, the directory containing betty/sue would be in your classpath.
Jar Files
Unzipping a jar file
jar xf jarfile.jar
Strings
String text = "abcde";
text.substring(2) == "cde"
text.substring(0,1) == "a"
text.substring(1,5) == "bcde"