14.07.2013 Views

Contents - Cultural View

Contents - Cultural View

Contents - Cultural View

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Java syntax 190<br />

There are also static constructors, whose purpose is to initialize static fields when the class is initialized. They are<br />

declared using static keyword:<br />

class Foo {<br />

}<br />

static {<br />

}<br />

//Initialization<br />

Since Java has a garbage collection mechanism, there are no destructors. However, every object has a finalize()<br />

method called prior to garbage collection which could be overridden to implement finalization.<br />

Methods<br />

All the statements in Java must reside within methods. Methods are similar to functions except they belong to<br />

classes. A method has a return value, a name and usually some parameters initialized when it is called with some<br />

arguments. Similar to C++, methods which return nothing have return type declared as void. Unlike in C++, methods<br />

in Java are not allowed to have default argument values and methods are usually overloaded instead.<br />

class Foo {<br />

}<br />

int bar(int a, int b) {<br />

}<br />

return (a * 2) + b;<br />

int bar(int a) { /* Overloaded method with the same name but<br />

}<br />

return a * 2;<br />

different set of arguments */<br />

A method is called using . notation on a specific variable, or as in the case of static methods, the name of a type.<br />

Foo foo = new Foo();<br />

int result = foo.bar(7, 2); // Non-static method is called on foo<br />

int finalResult = Math.abs(result); // Static method call<br />

Methods throwing exceptions use throws keyword to indicate that. All checked exceptions are mandatory to be<br />

declared.<br />

void openStream() throws IOException { // Indicates that IOException may be thrown<br />

}

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!