Showing posts with label scjp. Show all posts
Showing posts with label scjp. Show all posts
Monday, 21 February 2011
Wednesday, 28 July 2010
Declarations and Access Control - Java
te that declares, constructs and initializes arrays of any base type using any of the permitted forms both for declaration and for initialization.
Declaring arrays:
For example,use eitherint[] x;or
int x[];Both are legal positions for the brackets. To declare a multidimensional array, use multiple sets of brackets, e.g.
int i[][]; declares a two dimensional array. Note that, for example, int[]i[]; is also legal, and means the same thing. In Java, multidimensional arrays can be "not square" i.e. they are just arrays of arrays, and each of those constituent arrays can be of a different size. Construct arrays:
Arrays are objects. Use thenew keyword to construct them. For example having declared an array i: int[] i;you then construct the array and assign it to i as follows:
i = new int[10];The size of the array is in the brackets (in this example 10). It is common to do both operations in one statement:
int i[] = new int[10];
To initialize an array using loop iteration:
An example:int array[] = new int[15];
for(int j=0; j
array[j]=j;
}
Write code to initialize an array using the combined declaration and initialization format:
An example:char c[]= new char[] {'a','b','c','d','e'};or you can usechar c[]= {'a','b','c','d','e'};Some terms and their synonyms:
Scope/Visibility: Where something can be seen / is accessable from.Nested/Inner Class: A class whose code sits inside the body of another 'outer' class. It exists 'inside' the class in that it can see the private methods and variables.
Instance/Member: Means the method/variable/nested class belongs to each object which is an instance of the class. The term 'a member' is often used to refer to both methods and variables of this type. Cannot be accessed by statically i.e. without having an instance of the class.
Class/Static: The method/variable/nested class belongs to the class as opposed to the instances of the class. Can be used without creating an instance of the class, but static methods/nested class cannot use instancts variables/methods.
Local/Automatic variable: A variable which is declared within a method or as a parameter to the method. Cannot be seen outside the method.
Scoping Types
"default" or "friendly" - this is where no modifier is used. Means something is only visible to classes in the same package.protected - can only be accessed by classes in the same package or subclasses of this class. This frequently surprises experienced developers, especially those with a prior backround in the mutant hybrid of object orientated programming and assembly language known as 'C++' :-) To fair the name is misleading, as it sounds like it restricts access, where as it in fact it adds subclasses outside the package to the list of things that can access the item in question, as compared to using "default" access. public - can be accessed by any other class. private - can only be accessed from inside the class. Declare classes using the modifiers public, abstract or final:
public - is visible outside of its package. Without this modifier, the class cannot be accessed outside its package. abstract - cannot be instantiated, is allowed to contain abstract methods. final - cannot be subsclassed. Using the modifiers private, protected, public, static, final, native or abstract:
private - can only be accessed from inside the class. Private members are not inherited by subclasses. Inner classes can be declared private. protected - can only be accessed by classes in the same package or subclasses of this class. public - can be accessed by any other class. static - belongs to the class rather than any particular instance of the class. For variables, effectively, there is just one copy of this variable for all instances of the class, and if an instance changes the value, the other instances see that new value. For methods, it means the method can be called without having created an instance, but within the methodd you cannot use the this keyword, or refer to instance variables and methods directly (without creating an instance and referring to the variable/class in that instance). For inner classes, it means they can be instantiated without having an instance of the enclosing class, but as with static methods, the methods of the inner class cannot refer to instance variables or methods of the enclosing class directly. final - cannot be changed. Variables are constants, methods cannot be overridden, classes cannot be subclassed. Since Java1.1 you can declare the variable without assigning a value. Once you assign a value, you cannot change it. The are known as 'blank' finals, are frequently used for things like constants you wish to initialise from a configuration file. native - a method which is not written in java and is outside the JVM in a library. abstract - a method which is not implemented. Must be implemented in a subclass if that subclass is to be 'concrete' and allow people to instantiate it. Nested Classes
To define a non-static nested class either in a class or method scope:
Place the class definition (for the nested class) inside another class definition (the outer class) or a method.To define, in method scope, an anonymous nested class that implements a specified interface:
An anonymous nested class is defined where is it instantiated (in a method). An anonymous nested class must either implement an interface or extend a class, but theimplements or extends keywords are not used. For example the following line causes the method to return an object which is an instance of an anonymous nested class: return new SomeClass() { /*body of the anonymous class goes here*/ };You might like to think of an anonymous nested class as part of a really long new statement, which happens to contain a class definition, and which is why it has a ";" at the end. The following example calls someMethod(), passing an instance of the anonymous nested class: someMethod(new SomeClass() { /*body of the anonymous class goes here*/ });In both cases SomeClass() is not the name of the anonymous class (anonymous means it has no name) rather is it the name of the class that you are extending or the interface you are implementing. These classes cannot define a constructor, as they do not have a name that you can use to declare the constructor method. If SomeClass() is a class, the default constructor of that class is called, if you want to use a non-default constructor instead, you supply arguments e.g.: return new SomeClass(12) { /*body of the anonymous class goes here*/ };will call the SomeClass constructor which takes an int.Write code in a non-static method of the outer class to construct an instance of the nested class.
Inner x = new Inner(); constructs an instance of Inner where Inner is a nested class defined in the current class. Write code to construct an instance on a nested class where either no this object exists, or the current this object is not an instance of the outer class.
You must create an instance of the outer class first. Given a class, Outer, containing a nested class Inner: Outer.Inner y = new Outer().new Inner();The above creates an instance of Inner called y, but it had to construct an instance of Outer first. The following example creates the Outer instance on a separate line, the syntax in the second line is the one you use when you already have an instance of the outer class.
Outer x = new Outer();If Inner is static, you can use:
Outer.Inner y = x.new Inner();
Outer.Inner I= new Outer.Inner();
State which variables and methods in enclosing scopes are accessible from methods of the inner class.
A non-static inner class has access to all member variables and methods of the containing class. If the inner class is defined inside a method, it has access to those method (a.k.a. automatic or local) variables which are declaredfinal, in addition to the above. A static inner class is restricted in the same way as a static method: it cannot refer to instance variables and methods of the containing class directly (without creating an instance and referring to the variable/class in that instance).
| For a given class, determine if a default constructor will be created and if so state the prototype of that constructor. |
classname() where classname is the name of you class. A default constructor is automatically created only if you do not create any constructors in your class. If you create a non-default constructor (i.e. one that takes an argument), then you may have to create a default one yourself, if you want there to be one. All constructors call the default constructor of its parents class (if there is one), and so on up the hierarchy to Object, unless you specify a different constructor using
super(...) (to use a constructor in the parent) or this(...). If you use such calls, they must be the first thing in the constructor.
Tuesday, 4 May 2010
Casting
The cast operator (type) is used to convert numeric values from one numeric type to another or to
change an object reference to a compatible type.
A widening conversion is a conversion from a smaller numeric type to a larger numeric type. An
example of a widening conversion is when a byte value is promoted to an int value. A narrowing
conversion is a conversion from a larger numeric type to a smaller numeric type. A conversion from a
long value to a short value would be an example of a narrowing conversion. Narrowing conversions
require the use of the cast operator.
double d = 123.456;
byte b;
b = (byte) d;
Rules for casting
When casting is used with object references, the following rules apply:
1. A reference to any object can be cast into a reference to an object of class Object.
2. A reference to an object can be cast into a reference to an object of class C', if the actual class of the object is a subclass of C'.
3. A reference to an object can be cast into a reference to an object of interface I, if the actual class of the object implements I, if the object is of interface type I' and I' is a subinterface of I, or if the object is an array type and I is the Cloneable interface.
4. A reference to an object can be cast a reference to an object of an array type (with element reference type T), if the object is of an array type (with element reference type T') such that T' can be cast into T.
Casting to array types is more complicated. In order to cast to an object reference to an array type reference, the object must be an array of a component type that is compatible with the component type of the array type reference.
As an example of object type casting, consider the following program. Without the (String) cast operator, the result returned by v.elementAt(0) is an object of the Object class. The compiler recognizes this inconsistency and generates an error message. When the (String) cast operator is used, the compiler recognizes that you are casting the reference to an Object object into a String object and proceeds with the compilation.
change an object reference to a compatible type.
A widening conversion is a conversion from a smaller numeric type to a larger numeric type. An
example of a widening conversion is when a byte value is promoted to an int value. A narrowing
conversion is a conversion from a larger numeric type to a smaller numeric type. A conversion from a
long value to a short value would be an example of a narrowing conversion. Narrowing conversions
require the use of the cast operator.
double d = 123.456;
byte b;
b = (byte) d;
Rules for casting
When casting is used with object references, the following rules apply:
1. A reference to any object can be cast into a reference to an object of class Object.
String s = "abcd';
Object o = s;
2. A reference to an object can be cast into a reference to an object of class C', if the actual class of the object is a subclass of C'.
Subclass s = ... ;
Base b = s;3. A reference to an object can be cast into a reference to an object of interface I, if the actual class of the object implements I, if the object is of interface type I' and I' is a subinterface of I, or if the object is an array type and I is the Cloneable interface.
class X implements I{}
X x = ... ;
I i = x;
For example, a Vector object can be cast to a List object, and a List object can be cast to a Collection object. Because the array type implements the Cloneable interface, any array can be cast into a Cloneable object. 4. A reference to an object can be cast a reference to an object of an array type (with element reference type T), if the object is of an array type (with element reference type T') such that T' can be cast into T.
Casting to array types is more complicated. In order to cast to an object reference to an array type reference, the object must be an array of a component type that is compatible with the component type of the array type reference.
As an example of object type casting, consider the following program. Without the (String) cast operator, the result returned by v.elementAt(0) is an object of the Object class. The compiler recognizes this inconsistency and generates an error message. When the (String) cast operator is used, the compiler recognizes that you are casting the reference to an Object object into a String object and proceeds with the compilation.
String s1 = "abc";
String s2 = "def";
Vector v = new Vector();
v.add(s1);
s2 = (String) v.elementAt(0);
System.out.println(s2);
String s2 = "def";
Vector v = new Vector();
v.add(s1);
s2 = (String) v.elementAt(0);
System.out.println(s2);
Monday, 3 May 2010
Numeric promotion
When binary operations are applied to numeric arguments (integer and floating-point), numeric
promotion is performed before the operation takes place. The numeric promotion consists of converting
the values of the operands to a common type. The rules for this conversion are straightforward.
to know them to work through related questions.
One thing that you probably will see on the test is + operations involving a numeric value and a String value. These questions test your knowledge of the difference between the arithmetic + operator and the String + operator. The String + operator results in the concatenation of two String objects. For example, "abc" + "def" results in "abcdef". But what about, 10 + "0" or "2.4" + 2.5?
The rule that you should remember is that when one of the operands in a + operation is a String, then
the other operand is converted to a String. Therefore, 10 + "0" results in the String "100" and
"2.4" + 2.5 results in the String object "2.42.5". The other operand is converted to a String
object in one of two ways, depending on whether the operand is an object or a value of a primitive type.
If the other operand is an object, then its toString() method is invoked to convert it to a String
object. If the other operand is a value of a primitive type, then an object of the type's wrapper class is
created and the object's toString() method is invoked
to convert it to a String object.
promotion is performed before the operation takes place. The numeric promotion consists of converting
the values of the operands to a common type. The rules for this conversion are straightforward.
- If one of the operands is a double, then the other is converted to a double.
- Otherwise, if one of the operands is a float, then the other is converted to a float.
- Otherwise, if one of the operands is a long, then the other is converted to a long.
- Otherwise, both operands are converted to int values.
to know them to work through related questions.
One thing that you probably will see on the test is + operations involving a numeric value and a String value. These questions test your knowledge of the difference between the arithmetic + operator and the String + operator. The String + operator results in the concatenation of two String objects. For example, "abc" + "def" results in "abcdef". But what about, 10 + "0" or "2.4" + 2.5?
The rule that you should remember is that when one of the operands in a + operation is a String, then
the other operand is converted to a String. Therefore, 10 + "0" results in the String "100" and
"2.4" + 2.5 results in the String object "2.42.5". The other operand is converted to a String
object in one of two ways, depending on whether the operand is an object or a value of a primitive type.
If the other operand is an object, then its toString() method is invoked to convert it to a String
object. If the other operand is a value of a primitive type, then an object of the type's wrapper class is
created and the object's toString() method is invoked
to convert it to a String object.
Language Fundamentals : The main() Method and command line arguments
The main() method is used as the entry point for a Java application program. All programs must have
a main() method or they cannot be run. The main() method is a method of the class that is executed
to run the program.
Note Importing java.lang The java.lang package is always imported by default and does not need to be imported by an import statement.
For example, if your program's name is MyProgram, then the MyProgram class must be defined in a
file named MyProgram.java. The MyProgram class must have a correctly defined main() method.
A correctly defined main() method has the following form:
public static void main(String[] args) {
// Statements go here
}
The main() method must be declared as public, static, and void.
The void keyword must appear immediately before main().
The public and static keywords may be interchanged.
The main() method has one argument—an array of String arguments. This argument may be defined as
String[] args or String []args or String args[]. The args argument may use any valid
identifier. For example, you can use arg, myArgs, or parms. However, args is standard, and you
should probably stick with it. As a convention, when I refer to args, I'm referring to the argument to a
program's main() method.
The args array is used to access a program's command-line arguments. These arguments are passed
to a program when it is invoked. They are passed as part of the command that is used to invoke the
program.
Note Applets Applets are not required to have a main() method.
For example, to run the MyProgram program, you would enter
java MyProgram
Suppose that you wanted to pass the arguments 2 and 3 to MyProgram. You would invoke it as follows:
java MyProgram 2 3
The String object "2" would be accessed as args[0], and the String object "3" would be accessed as args[1]. If you are a C or C++ programmer—pay attention. Java accesses commandline
arguments using different indices than do C and C++ programs.
The ArgsTest program of Listing 2.1 shows how command-line arguments are accessed using the
args array. When you run the program using the following command line
java ArgsTest this is a test
it displays the following results
args[0] = this
args[1] = is
args[2] = a
args[3] = test
Listing 2.1: The Argstest Program
class ArgsTest {
public static void main(String[] args) {
for(int i=0;i
System.out.println("args["+i+"] = "+args[i]);
}
}
}
a main() method or they cannot be run. The main() method is a method of the class that is executed
to run the program.
Note Importing java.lang The java.lang package is always imported by default and does not need to be imported by an import statement.
For example, if your program's name is MyProgram, then the MyProgram class must be defined in a
file named MyProgram.java. The MyProgram class must have a correctly defined main() method.
A correctly defined main() method has the following form:
public static void main(String[] args) {
// Statements go here
}
The main() method must be declared as public, static, and void.
The void keyword must appear immediately before main().
The public and static keywords may be interchanged.
The main() method has one argument—an array of String arguments. This argument may be defined as
String[] args or String []args or String args[]. The args argument may use any valid
identifier. For example, you can use arg, myArgs, or parms. However, args is standard, and you
should probably stick with it. As a convention, when I refer to args, I'm referring to the argument to a
program's main() method.
The args array is used to access a program's command-line arguments. These arguments are passed
to a program when it is invoked. They are passed as part of the command that is used to invoke the
program.
Note Applets Applets are not required to have a main() method.
For example, to run the MyProgram program, you would enter
java MyProgram
Suppose that you wanted to pass the arguments 2 and 3 to MyProgram. You would invoke it as follows:
java MyProgram 2 3
The String object "2" would be accessed as args[0], and the String object "3" would be accessed as args[1]. If you are a C or C++ programmer—pay attention. Java accesses commandline
arguments using different indices than do C and C++ programs.
The ArgsTest program of Listing 2.1 shows how command-line arguments are accessed using the
args array. When you run the program using the following command line
java ArgsTest this is a test
it displays the following results
args[0] = this
args[1] = is
args[2] = a
args[3] = test
Listing 2.1: The Argstest Program
class ArgsTest {
public static void main(String[] args) {
for(int i=0;i
System.out.println("args["+i+"] = "+args[i]);
}
}
}
Language Fundamentals : Main methods and Java program structure
The Structure of Java Programs
Java programs are composed of declarations of classes and interfaces. Classes define variables, which
provide named access to data, methods, which perform actions consisting of operations on the data,
and constructors, which create instances of classes, referred to as objects. Data items consist of
primitive data values—such as byte, char, and int values—and objects—such as arrays, I/O
streams, and GUI elements.
Interfaces define collections of methods that are implemented by classes. They are also used to define
constants, which are data values that cannot be changed.
Java programs are written using one or more compilation units, which are Java source code files. Every
source code file consists of the name of a class or interface followed by the .java extension. Since java identifiers are case-sensitive, source code filenames are also case-sensitive.
Source file : Each source code file may contain at most one public class or interface. If a class or interface is
declared as public, the source code filename must be the name of the class or interface (followed by
the .java extension). If a source code file does not contain a public class or interface, it may take on
a name that is different from its classes and interfaces.
Identifying Packages
Java classes and interfaces are organized into packages. Packages provide a naming context for
classes and interfaces. In other words, packages enable different programmers (or even the same
programmer) to create classes and interfaces with the same name. For example, if you and I both
create a class named Cool and then use the two different versions of Cool in the same program, the
compiler and runtime system won't know which version to use. But, if I put my Cool class in the My
package, and you put your Cool class in the You package, the compiler and runtime system will have
no problem, as long as we refer to Cool using its package name.
Packages are identified by the package statement. It must appear as the first statement in a source
code file
package packageName;
Note Use of Packages In addition to being used as a naming context, packages are used to organize related classes and interfaces into a single API unit to which access may be controlled.
If a package statement is omitted, the classes and interfaces declared within the package are put into
the default no name package. In the Java 2 Platform Software Development Kit (SDK), the package
name and the CLASSPATH environment variable are used to find a class or interface that is located in
another package.
Importing Classes and Interfaces from Other Packages
The import statement is used to reference classes and interfaces that are declared in other packages
(without having to specify their names each time they are referenced). There are three forms of the
import statement:
import packageName.className;
import packageName.interfaceName;
import packageName.*;
The first and second forms enable the identified classes and interfaces to be referenced without
specifying the name of their package. The third form allows all classes and interfaces in the specified
package to be referenced without specifying the name of their package.
The Main method and command line arguments
Java programs are composed of declarations of classes and interfaces. Classes define variables, which
provide named access to data, methods, which perform actions consisting of operations on the data,
and constructors, which create instances of classes, referred to as objects. Data items consist of
primitive data values—such as byte, char, and int values—and objects—such as arrays, I/O
streams, and GUI elements.
Interfaces define collections of methods that are implemented by classes. They are also used to define
constants, which are data values that cannot be changed.
Java programs are written using one or more compilation units, which are Java source code files. Every
source code file consists of the name of a class or interface followed by the .java extension. Since java identifiers are case-sensitive, source code filenames are also case-sensitive.
Source file : Each source code file may contain at most one public class or interface. If a class or interface is
declared as public, the source code filename must be the name of the class or interface (followed by
the .java extension). If a source code file does not contain a public class or interface, it may take on
a name that is different from its classes and interfaces.
Identifying Packages
Java classes and interfaces are organized into packages. Packages provide a naming context for
classes and interfaces. In other words, packages enable different programmers (or even the same
programmer) to create classes and interfaces with the same name. For example, if you and I both
create a class named Cool and then use the two different versions of Cool in the same program, the
compiler and runtime system won't know which version to use. But, if I put my Cool class in the My
package, and you put your Cool class in the You package, the compiler and runtime system will have
no problem, as long as we refer to Cool using its package name.
Packages are identified by the package statement. It must appear as the first statement in a source
code file
package packageName;
Note Use of Packages In addition to being used as a naming context, packages are used to organize related classes and interfaces into a single API unit to which access may be controlled.
If a package statement is omitted, the classes and interfaces declared within the package are put into
the default no name package. In the Java 2 Platform Software Development Kit (SDK), the package
name and the CLASSPATH environment variable are used to find a class or interface that is located in
another package.
Importing Classes and Interfaces from Other Packages
The import statement is used to reference classes and interfaces that are declared in other packages
(without having to specify their names each time they are referenced). There are three forms of the
import statement:
import packageName.className;
import packageName.interfaceName;
import packageName.*;
The first and second forms enable the identified classes and interfaces to be referenced without
specifying the name of their package. The third form allows all classes and interfaces in the specified
package to be referenced without specifying the name of their package.
The Main method and command line arguments
Friday, 2 April 2010
File Handling and Input/Output
- java.io package
- Classes related to input and output are present in the JavaTM language package java.io . Java technology uses "streams" as a general mechanism of handling data. Input streams act as a source of data. Output streams act as a destination of data.
- File class
- The file class is used to store the path and name of a directory or file. The file object can be used to create, rename, or delete the file or directory it represents. The File class has the following constructors -
File(String pathname); // pathname could be file or a directory name File(String dirPathname, String filename); File(File directory, String filename);The File class provides the getName() method which returns the name of the file excluding the directory name.String getName(); - Byte Streams
- The package java.io provides two set of class hierarchies - one for handling reading and writing of bytes, and another for handling reading and writing of characters. The abstract classes InputStream and OutputStream are the root of inheritance hierarchies handling reading and writing of bytes respectively. Figure : InputStream class hierarchy (partial)
Figure : OutputStream class hierarchy (partial)
- read and write methods
- InputStream class defines the following methods for reading bytes -
int read() throws IOExceptionint read(byte b[]) throws IOExceptionint read(byte b[], int offset, int length) throws IOExceptionSubclasses of InputStream implement the above mentioned methods. OutputStream class defines the following methods for writing bytes -void write(int b) throws IOExceptionvoid write(byte b[]) throws IOExceptionvoid write(byte b[], int offset, int length) throws IOExceptionSubclasses of OutputStream implement the above mentioned methods. The example below illustrates code to read a character.//First create an object of type FileInputStream type using the name of the file.FileInputStream inp = new FileInputStream("filename.ext");//Create an object of type DataInputStream using inp.DataInputStream dataInp = new DataInputStream(inp);int i = dataInp.readInt(); - Reader and Writer classes(l.w. = chr = character and last r = reader )
- Similar to the InputStream and OutputStream class hierarchies for reading and writing bytes, Java technology provides class hierarchies rooted at Reader and Writer classes for reading and writing characters. A character encoding is a scheme for internal representation of characters. Java programs use 16 bit Unicode character encoding to represent characters internally. Other platforms may use a different character set (for example ASCII) to represent characters. The reader classes support conversions of Unicode characters to internal character shortage. Every platform has a default character encoding. Besides using default encoding, Reader and Writer classes can also specify which encoding scheme to use.The Reader class hierarchy is illustrated below.
The Writer class hierarchy is illustrated below.
The table below gives a brief overview of key Reader classes.
The table below gives a brief overview of key Writer classes.CharArrayReader The class supports reading of characters from a character array. InputStreamReader The class supports reading of characters from a byte input stream. A character encoding may also be specified. FileReader The class supports reading of characters from a file using default character encoding.
The example below illustrates reading of characters using the FileReader class.CharArrayWriter The class supports writing of characters from a character array. OutputStreamReader The class supports writing of characters from a byte output stream. A character encoding may also be specified. FileWriter The class supports writing of characters from a file using default character encoding. //Create a FileReader class from the file name.FileReader fr = new FileReader("filename.txt");int i = fr.read(); //Read a character
Threads
- Threads
- A thread is in process in execution within a program. Within a program each thread defines a separate path of execution.
- Creation of a thread
- A thread can be created in two ways a) By implementing the Runnable interface. The Runnable interface consists of only one method - the run method. The run method has a prototype of
public void run();b) By extending the class Thread. - Execution of a thread
- To execute a thread, the thread is first created and then the start() method is invoked on the thread. Eventually the thread would execute and the run method would be invoked. The example below illustrates the two methods of thread creation. You should note that the run method should not be invoked directly.
When the run method ends, the thread is supposed to "die". The next example shows the creation of thread by implementing the Runnable interface.
public class ThreadExample extends Thread {
public void run() {
System.out.println("Thread started");
}
public static void main(String args[]) {
ThreadExample t = new ThreadExample();
t.start();
}
}
Example - Creation of Thread by extending the
Thread class.
public class ThreadExample2 implements Runnable {
public void run() {
.../* Code which gets executed when
thread gets executed. */
}
public static void main(String args[]) {
ThreadExample2 Tt = new ThreadExample2();
Thread t = new Thread(Tt);
t.start();
}
}
Example - Creating thread by implementing Runnable - States of thread
- A thread can be in one of the following states - ready, waiting for some action, running, and dead. These states are explained below. Running State A thread is said to be in running state when it is being executed. This thread has access to CPU. Ready State A thread in this state is ready for execution, but is not being currently executed. Once a thread in the ready state gets access to the CPU, it gets converted to running state. Dead State A thread reaches "dead" state when the run method has finished execution. This thread cannot be executed now.Waiting State In this state the thread is waiting for some action to happen. Once that action happens, the thread gets into the ready state. A waiting thread can be in one of the following states - sleeping, suspended, blocked, waiting for monitor. These are explained below.
- Yielding to other processes
- A CPU intensive operation being executed may not allow other threads to be executed for a "large" period of time. To prevent this it can allow other threads to execute by invoking the yield() method. The thread on which yield() is invoked would move from running state to ready state.
- Sleep state of a thread
- A thread being executed can invoke the sleep() method to cease executing, and free up the CPU. This thread would go to the "sleep" state for the specified amount of time, after which it would move to the "ready" state. The sleep method has the following prototypes.
public static void sleep (long millisec) //sleep for millisec
throws InterruptedException;
public static void sleep (long millisec, int nanosec) //sleep for x millisec
throws InterruptedException; // and y nanoseconds - Synchronized state
- A code within the synchronized block is "atomic". This means only one thread can execute that block of code for a given object at a time. If a thread has started executing this block of code for an object, no other thread can execute this block of the code (or any other block of synchronized code) for the same object.
public synchronized void synchExample() {
/* A set of synchronized statements. Assume
here that x is a data member of this class. */
if(x == 0)
x = 1;
}
Various Classes in Java technology
- The Object class
- All classes in JavaTM technology are directly or indirectly derived from the Object class. Some of the subclasses of Object class are - Boolean, Number, Void, Math, String, StringBuffer etc.
Some of the important methods defined in the Object class are given below. These methods are available to all Java classes.
- boolean equals(Object obj) - The equals method in Object class returns true if two references point to the same object. Some classes like String and Boolean overload this method.
- String toString() - The function is used to convert objects to String. If a subclass does not override this method, the method returns a textual representation of the object, which has the following format :
@ ". - The following methods related to threads are also defined in Object class -
void notify()
void notifyall()
void wait(long timeout) throws InteruptedException
void wait(long timeout, int nanosec) throws InteruptedException
void wait() throws InteruptedException
- Wrapper classes
- Corresponding to all the primitive types Java technology defines wrapper classes. Some examples of these wrapper classes are - Character, Boolean, Integer, Double.
- Important methods in the Math class
- Some of the methods defined in the Math class are used frequently. These are explained below. Besides the functionality, it is important to understand the arguments and return type of these functions.
static double ceil(double(d)): The method ceil returns the smallest double value equal to a mathematical integer, that is not less than the argument. For example,
ceil(3.4) returns 4.0
ceil(-2.3) returns -2.0
ceil(3.0) returns 3.0static double floor(double(d)): The method floor returns the largest double value equal to a mathematical integer, that is not greater than the argument. For example,
floor(3.4) returns 3.0
floor(-2.3) returns -3.0
floor(3.0) returns 3.0static int round (float f)andstatic long round(double d): The method round returns the integer closest to the argument.
round(3.7) returns 4
round(3.2) returns 3
round(3.0) returns 3
round(-3.1) returns -3 - String class
- The String class is used to implement immutable character strings. This means that the character string cannot be changed once it has been created. Some of the important methods are explained below.
int length()- The number of characters in the String class are returned by the length() method.String substring(int startIndex) String substring(int startIndex, int endIndex)The method substring extracts a substring from a string. The method extracts a string from the startIndex to the index endIndex - 1. If endIndex is not specified then string till the end of input string is returned. The example below illustrates this
After the above statements str2 contains the string "am ". The string str still has the same value "I am a string". The variable len has value 13.
String str = "I am a string";
int len = str.length();
String str2 = str.substring(2,5); - StringBuffer class
- The StringBuffer class implements mutable strings. This means that the characters stored in the string and the capacity of the string can be changed.
- Garbage Collection
- Java technology's Garbage collection is complex. In this section I am only giving a brief overview of Garbage Collection. Java technology supports automatic garbage collection. This means that the programmer does not need to free the memory used by objects. Java technology's runtime environment can claim the memory from the objects that are no longer in use. Objects that are not being referred become candidates for garbage collection. It is important to note that these objects are candidates only. Java technology does not guarantee that Garbage collection would happen on these objects. Before actually freeing up the memory, garbage collector invokes the finalize() method of the Object being freed. The System.gc() method can be invoked by the program to suggest to Java technology that the Garbage Collector be invoked. However there is no guarantee when the garbage collection would be invoked. There is also no guarantee on the order in which objects will be garbage collected. The example illustrates when a string Object becomes available for Garbage Collection.
public class GCTest {
public static void main(String args[]) {
String a,b;
String c = new String("test");
a = c;
c = null; // The String "test" is not yet
//available for GC as a still points to "test"
b = new String("xyz");
b = c; // String "xyz" is now available for GC.
a = null;
//String "test" is now available for GC.
}
}
Subscribe to:
Comments (Atom)