0% found this document useful (0 votes)
57 views

Java Syntax: Basic Program

The document discusses key concepts in Java including basic programs, types, conditionals, loops, exceptions, and classes. It provides code examples to demonstrate a basic HelloWorld program, use of primitive types and operations, if/else and switch statements, for, while, and do-while loops, try/catch exception handling, and definition of a simple MyVector class. The examples are intended to illustrate core Java syntax and programming concepts.

Uploaded by

feparekored
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views

Java Syntax: Basic Program

The document discusses key concepts in Java including basic programs, types, conditionals, loops, exceptions, and classes. It provides code examples to demonstrate a basic HelloWorld program, use of primitive types and operations, if/else and switch statements, for, while, and do-while loops, try/catch exception handling, and definition of a simple MyVector class. The examples are intended to illustrate core Java syntax and programming concepts.

Uploaded by

feparekored
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Java Syntax

[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

// primitive type operations


smallest++; // smallest now equals 18
small -= 5; // small now equals 3360
num = (20/5 + 2*3) % 3; // num now equals 10 modulus 3 which is 1
small = (0x1|0xf)^(0x7&0x3);// small now equals 0x0a
small = -8 >> 3; // small now equals -1, >>> without sign
extension
large = ~num & 0xffffffff; // larger types and masks simulate unsigned
bool = !bool; // bool now equals true
smallest = (byte)large; // cast between types (can loose some data)
System.out.print(number); // print can handle all primitive types
int_arr[0] = 33 + ml[0][0]; // c-like array access, 0 is first element
int len = int_arr.length; // Arrays have a length member

// complex classy types (allocate with new, contain methods)


String str = new String("hello"); // String is immutable (not changable)
String hi = new String(chr_arr); // String has many possible ctors
String no_alloc = null; // allocating the String is not a must
String str_arr[] = new String[9]; // even Strings can come in arrays
StringBuffer b = new StringBuffer();// StringBuffer is mutable (unlike
String)
b = new StringBuffer("hello"); // StringBuffer also has many ctors
Integer integer = new Integer(237); // primitives have wrapper classes
int i = integer.intValue(); // primitive value easily accessible

// complex classy operations


bool = str instanceof String; // bool is true since str is String
str = str + " world"; // a new String is allocated with
concat
char h = str.charAt(0); // no str[0] access, String is no array
int strlen = str.length(); // String has many useful methods
int strcmp = str.compareTo("hi"); // no ==, strcmp return values (-,0,+)
str.append("at end"); // immutable - allocates a new String
b.append("at end"); // mutable - tries to change current b
str = num.toString(); // everything in java has toString
method
num = Integer.valueOf("2").intValue(); // wrapper class has
conversions
real = Float.valueOf("3.14").floatValue(); // each primitive has its own

// arguments (pass by value, pass by reference)


arg_int = 5; // caller arg is not changed (by value)
arg_sb.append("\n"); // caller arg is changed (ref to same
obj)
arg_str = new String("new"); // new String placed in local ref only
arg_sb = new StringBuffer("new"); // caller arg is not changed here as
well
arg_arr[0] = 5; // caller arr[0] is of course changed
}

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

// switch block, instead of many if-else blocks


// only primitive types char,byte,short,int can be switched upon
switch (age)
{
case 17:
case 53:
score++; // give extra bonuses for these ages
score = score * 2;
break;
default:
score = 0; // for all others start again from zero
}

// do something with the score


handle_score(score);
}

Loops and Iterations


/////////////////////////////////////////////////////////////////////////////
/
// name: showFlow
// purpose: show some basic flow blocks
// args: none
// returns: total score
/////////////////////////////////////////////////////////////////////////////
/
public int showFlow()
{
// vars
int score = 0;

// for statement
for (int i=0; i<10; i++) score++; // loop 10 times

// while statement, check condition before


int j = 3;
while (j>0) // loop 2 times
{
score++;
j = j - 2;
}

// do-while statement, check condition after


do // loop 1 time
{
score++;
j--;
} while (j>0);

// continue and break can help decide locally


char ch;
while (1) // loop forever
{
ch = getInputFromUser();
if (ch == 'q') break; // exit the loop
if (ch == 's') continue; // continue to the next iteration
score++;
}

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

// example of a function that can be called without an instance (static)


public static int getNumCreated()
{
return this.num_created; // access can be through this keyword
}

// ctor with no arguments (if emitted, caller will have to supply


arguments)
// private,protected ctor will enable appropriate class instantiation only
public MyVector()
{
this(0,0); // invoke the other ctor in this class (below)
}
// overloaded ctor (overloading possible with any method like in c++)
// no default parameters possible, unlike c++
public MyVector(float x, float y)
{
_x = x; _y = y; // init the members
num_created++; // access may have to be synchronized if multi-threaded
}

// regular public method to return size of the vector


public float getSize()
{
return Math.sqrt(_x*_x+_y*_y);
}
}

//////////////////////////////////
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;

// ctor (note that no no-param ctor exists)


// emitting a ctor will create a default empty no-param ctor
public MyObject(float weight)
{
_weight = weight;
}

// declaration only, must be implemented in derived (virtual by default)


public abstract void printName();

// non-virtual method, cannot be overriden in derived (also faster to call)


// by default, all methods are virtual (ptr to base will call derived
method)
public final float getWeight()
{
return _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;

// ctor (note that no no-param ctor exists)


public Soap(String brand)
{
super(1.33); // parent ctor must be first line, if emitted calls no-
param
_brand = new String(brand); // since final must be initialized here
}

// implementation of abstract printName


public void printName()
{
System.out.print("Soap produced by " + _brand + " which weighs ");
System.out.println(super.getWeight()); // calls explicitly parent method
}

// theoretically called by garbage-collector when object is freed


// when or if it will run is not promised(!) - refrain from using it
protected void finalize() throws Throwable
{
super.finalize(); // unlike c++ dtor, parent's finalize is called
manually
}
}

//////////////////////////////////
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)

Interfaces and Packages


// package name should be included in start of every source file
// if emitted, all classes / interfaces are declared globally
package com.chiquita;

/////////////////////////////////////////////////////////////////////////////
/
// 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();

// do the actual eating


while (this.state != "gone")
{
takeBite();
chewAndSwallow();
}

// how can you not love a banana?


return goodTaste;
}
}

//////////////////////////////////
usage /////////////////////////////////////
import com.chiquita.*;
Banana my_banana = new Banana();
System.out.println(my_banana.eat());

Threads and Synchronization


import java.io.*; // for file operation

/////////////////////////////////////////////////////////////////////////////
/
// 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;

// good practice to work with collections through abstract interfaces only


// this enables later hassle-free implementation changes (even to 3rd
party)

// ArrayList - ordered sequence, unlike a regular array this is resizable


List al = new ArrayList(500); // initial capacity //
unsynchronized
List sal = Collections.synchronizedList(new ArrayList(500));// synchronized
size = al.size(); // num of objects stored in the collection
(O1)
if (!al.isEmpty()) al.clear; // check if not empty (O1) and empty
collection
al.add(num); // add Integer num to end (O1)
al.add(0,"first"); // add String "first" at index 0 (0n)
obj = al.get(1); // obj is reference to String "first" (O1)
al.set(0,new Integer(88)); // change Object at index 0 to Integer 88
(O1)
al.remove(0); // remove Object at index 0 (On)

// HashSet - a group that cannot contain duplicates


Set hs = new HashSet(500); // initial capacity //
unsynchronized
Set shs = Collections.synchronizedSet(new HashSet(500)); // synchronized
size = hs.size(); // num of objects stored in the collection
(O1)
if (!hs.isEmpty()) hs.clear; // check if not empty (O1) and empty
collection
hs.add(num); // add Integer num, no order, no dups (O1)
if (!hs.contains("hello")) // compares Objects using equals() method
(O1)
hs.add(str); // add String str ("hello") (O1)
hs.remove("hello"); // remove String "hello" (O1)

// HashMap - a key-value coupling that cannot contain duplicates


Map hm = new HashMap(500); // initial capacity //
unsynchronized
Map shm = Collections.synchronizedMap(new HashMap(500)); // synchronized
size = hm.size(); // num of objects stored in the collection
(O1)
if (!hm.isEmpty()) hm.clear; // check if not empty (O1) and empty
collection
hm.put(num, "jim"); // add key Integer num with value String (O1)
obj = hm.get(new Integer(17));// obj is reference to value String "jim"
(O1)
if (!hm.containsKey("key")) // compares Objects using equals() method
(O1)
hm.put("key", str); // add key String "key" with value String str
hm.remove("key"); // remove key-value pair of key "key" (O1)
Set keys = hm.keySet(); // changes to Set keys will be reflected in
hm
}

Powered by Notepad.
RT 8

You might also like