Java Syntax: Basic Program
Java Syntax: Basic Program
[Basic Program]
[Basic Types]
[Conditionals]
[Loops and Iterations]
[Exceptions]
[Classes]
[Derived Classes]
[Interfaces and Packages]
[Threads and Synchronization]
[Collections]
other languages..
Basic Program
/////////////////////////////////////////////////////////////////////////////
/
// name: HelloWorldApp
// purpose: stand-alone executable class (has main) that prints "hello
world"
// notes: everything in java must be inside a class (no "floating"
functions)
// traditionally each source file represents one class (with its
name)
/////////////////////////////////////////////////////////////////////////////
/
public class HelloWorldApp
{
/////////////////////////////////////////////////////////////////////////////
/
// name: main
// purpose: entry point of the whole program
// args: (in) args - array of strings of command line arguments (no prog-
name)
// returns: nothing
/////////////////////////////////////////////////////////////////////////////
/
public static void main(String[] args)
{
/* c-style remarks are also possible */
System.out.println("hello world");
// or do the \n ourselves c-style
System.out.print("hello world\n");
}
}
Basic Types
/////////////////////////////////////////////////////////////////////////////
/
// name: showTypes
// purpose: show some basic types and type operations
// args: (in) arg_int - must be (in), primitives are passed by value
// (out) arg_sb - can be (out), Objects are passed by reference
// (in) arg_str - must be (in), String is immutable
// (out) arg_arr - out primitives can be achieved using 1-sized arrays
// returns: nothing
/////////////////////////////////////////////////////////////////////////////
/
void showTypes(int arg_int, StringBuffer arg_sb, String arg_str, int
arg_arr[])
{
// primitive types (regular c-like handling)
byte smallest = (byte)17; // whole signed num 1 byte size (cast needed)
short small = (short)3365; // whole signed num 2 byte size (cast needed)
int num = -90999999; // whole signed num 4 byte size (cast not
needed)
long large = 64L; // whole signed num 8 byte size (L for long)
float real = (float)0.01; // real num 4 byte size (cast needed)
double bigreal = 0.00001; // real num 8 byte size (cast not needed)
char letter = 'a'; // unicode character 2 byte size
char uniletter = '\u0061'; // same as letter (both equal 'a'), unsigned
boolean bool = false; // either true or false
final double pi = 3.14; // value cannot be changed anymore (const)
int int_arr[] = new int[9]; // allocate an empty int array with 9 elemets
char chr_arr[] = {'h','i'}; // allocate an array an initialize it
int ml[][] = {{1,2},{3,4}}; // multi-dimentional arrays are also possible
Conditionals
/////////////////////////////////////////////////////////////////////////////
/
// name: showConds
// purpose: show the basic conditionals
// args: (in) age - the age of the viewer
// returns: nothing
/////////////////////////////////////////////////////////////////////////////
/
public void showConds(int age)
{
// vars
int score = 0;
// if statement
if ((0 == age) && (age != 1)) return; // just born
// String and comparisons
String str1 = new String("hello");
String str2 = new String("hello");
if (str1 == str2) return; // not the same references, doesn't
ret
if (!str1.equals(str2)) return; // content isn't different, doesn't
ret
// if-else statement
if ((age < 18) || !(age <= 80))
{
// not in the right age to be here
return;
}
else score = 1; // give a bonus of 1 for the right age
// for statement
for (int i=0; i<10; i++) score++; // loop 10 times
return score;
}
Exceptions
/////////////////////////////////////////////////////////////////////////////
/
// name: MyException
// purpose: implement a very simple personalized exception class
// notes: Exception < RuntimeException < ArrayIndexOutOfBoundsException
// < IOException < EOFException
/////////////////////////////////////////////////////////////////////////////
/
public class MyException extends Exception
{ public MyException(String message) { super(message); } } // ctor only
/////////////////////////////////////////////////////////////////////////////
/
// name: showExceptions
// purpose: show some basic exception handling
// args: none
// returns: true on success, false on failure
/////////////////////////////////////////////////////////////////////////////
/
public boolean showExceptions() throws MyException // callers must handle
these
{
// vars
boolean ok = true;
try // block with "dangerous" code or API that throws
{
int arr[] = new int[3];
int index = getIndexWhichIsNegativeOnFailure();
if (index < 0) throw new MyException("Index is negative");
arr[index]++; // hopefully index will be < 3
}
catch (ArrayIndexOutOfBoundsException e) // potential problem
{
ok = false; // handle this silently (retval only)
}
catch (IOException e) // several allowed, catches all that derives from
{
System.out.println("Caught IOException " + e.toString());
e.printStackTrace();
throw e; // re-throw this exception (function will exit here)
}
finally // cleanup code that is guarenteed to always run
{
System.out.println("This will print regardless of exceptions");
}
return ok;
}
Classes
/////////////////////////////////////////////////////////////////////////////
/
// name: MyVector
// purpose: implement a simple class
/////////////////////////////////////////////////////////////////////////////
/
public class MyVector // without public usable only in its
package
{
// members
private static int num_created=0; // will exist regardlesss of instances
protected float _x, _y; // protected can be accessed by derived
too
//////////////////////////////////
usage /////////////////////////////////////
int total_num = MyVector.getNumCreated();
MyVector vec1 = new MyVector();
MyVector vec2 = new MyVector(0.23,0.98);
float vec2_size = vec2.getSize();
Derived Classes
/////////////////////////////////////////////////////////////////////////////
/
// name: MyObject
// purpose: implement an abstract class of a simple object
// notes: you can't make instances of an abstract class
/////////////////////////////////////////////////////////////////////////////
/
abstract class MyObject // not public, only classes in this package can use
{ // class without extends actually extends lang.Object
// members
private float _weight;
/////////////////////////////////////////////////////////////////////////////
/
// name: Soap
// purpose: implement a simple derived class (throwable branded soap)
// notes: only ctors are called in chains (overriden methods aren't)
/////////////////////////////////////////////////////////////////////////////
/
public final class Soap // final means this class cannot be subclassed
(faster)
extends MyObject // derived from MyObject, no multiple inheritence
{
// members
private final String _brand; // cannot be changed in runtime, ctor must
init
protected MyVector _speed;
//////////////////////////////////
usage /////////////////////////////////////
Soap my_soap = new Soap("Gillette");
float weight = my_soap.getWeight(); // calls MyObject implementation
MyObject my_obj = new Soap("Fa");
my_obj.printName(); // calls Soap implementation
(polymorphism)
/////////////////////////////////////////////////////////////////////////////
/
// name: Edible
// purpose: declare an interface (of an object available for eating)
// notes: interface can use extends to inherit from multiple super-
interfaces
/////////////////////////////////////////////////////////////////////////////
/
public interface Edible
{
// can include related constants
final String goodTaste = "yummi";
final String badTaste = "icky";
/////////////////////////////////////////////////////////////////////////////
/
// name: eat
// purpose: implement the process of eating the object
// args: none
// returns: a description of how it tasted
/////////////////////////////////////////////////////////////////////////////
/
String eat();
}
/////////////////////////////////////////////////////////////////////////////
/
// name: Banana
// purpose: implement an interface
// notes: interface can use extends to inherit from multiple super-
interfaces
/////////////////////////////////////////////////////////////////////////////
/
public class Banana implements Edible // can implement several interfaces
{
// eat method declared in the interface Edible
public String eat()
{
// must peel it first
if (this.state != "peeled") peelBanana();
//////////////////////////////////
usage /////////////////////////////////////
import com.chiquita.*;
Banana my_banana = new Banana();
System.out.println(my_banana.eat());
/////////////////////////////////////////////////////////////////////////////
/
// name: MultiThreadedInt
// purpose: implement an integer object safe for multi-threaded use
/////////////////////////////////////////////////////////////////////////////
/
public class MultiThreadedInt
{
// members
private int _value;
private FileWriter logFile;
// simple ctor
public MultiThreadedInt(int value) throws IOException // for file operation
{
_value = value;
logFile = new FileWriter("log.txt");
}
// synchronizes on class instance, threads will call this func one by one
public synchronized void setValue(int value)
{
_value = value;
}
// also syncs on class instance, so is synched with setValue too
public synchronized int getValue()
{
return _value;
}
// we don't want to synchronize on class instance (overhead)
public void logString(String msg) throws IOException // for file operation
{
// enough to sync on a specific object
synchronized (logFile) // this block is not synced with
getValue,setValue
{
logFile.write(msg);
}
}
}
/////////////////////////////////////////////////////////////////////////////
/
// name: MyThread
// purpose: implement a simple thread
/////////////////////////////////////////////////////////////////////////////
/
public class MyThread extends Thread
{
// override the run method with the thread actual body
public void run()
{
// just loop meaninglessly
for (int i = 0; i < 10; i++)
{
System.out.println(i);
try { sleep((long)(Math.random() * 1000)); }
catch (InterruptedException e) {}
}
}
}
//////////////////////////////////
usage /////////////////////////////////////
new MyThread().start();
Collections
import java.util.*;
/////////////////////////////////////////////////////////////////////////////
/
// name: showCollections
// purpose: show use of the handy collection classes
// args: none
// returns: nothing
/////////////////////////////////////////////////////////////////////////////
/
public void showCollections()
{
// vars
String str = new String("hello");
Integer num = new Integer(17);
Object obj = null;
int size;
Powered by Notepad.
RT 8