Tuesday, August 26, 2008

Multitasking Vs. Multithreading

Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between:

  • Process-based multitasking

  • Thread-based multitasking

At the coarse-grain level there is process-based multitasking, which allows processes (i.e., programs) to run concurrently on the computer. A familiar example is running the spreadsheet program while also working with the word-processor. At the fine-grain level there is thread-based multitasking, which allows parts of the same program to run concurrently on the computer. A familiar example is a word-processor that is printing and formatting text at the same time. This is only feasible if the two tasks are performed by two independent paths of execution at runtime. The two tasks would correspond to executing parts of the program concurrently. The sequence of code executed for each task defines a separate path of execution, and is called a thread (of execution).

In a single-threaded environment only one task at a time can be performed. CPU cycles are wasted, for example, when waiting for user input. Multitasking allows idle CPU time to be put to good use.

Some advantages of thread-based multitasking as compared to process-based multitasking are

  • threads share the same address space

  • context switching between threads is usually less expensive than between processes

  • cost of communication between threads is relatively low

Java supports thread-based multitasking and provides high-level facilities for multithreaded programming. Thread safety is the term used to describe the design of classes that ensure that the state of their objects is always consistent, even when the objects are used concurrently by multiple threads.

Threads

A thread is an independent sequential path of execution within a program. Many threads can run concurrently within a program. At runtime, threads in a program exist in a common memory space and can, therefore, share both data and code, that is, they are lightweight compared to processes. They also share the process running the program.

Every thread in Java is created and controlled by a unique object of the java.lang.Thread class. Often the thread and its associated Thread object are thought of as being synonymous.

The Main Thread

The runtime environment distinguishes between user threads and daemon threads. As long as a user thread is alive, the JVM does not terminate. A daemon thread is at the mercy of the runtime system: it is stopped if there are no more user threads running, thus terminating the program. Daemon threads exist only to serve user threads

Thread Creation

A thread in Java is represented by an object of the Thread class. Implementing threads is achieved in one of two ways:

  • implementing the java.lang.Runnable interface

  • extending the java.lang.Thread class

Friday, August 8, 2008

Nested Classes and Interfaces

A class that is declared within another class or interface, is called a nested class. Similarly, an interface that is declared within another class or interface, is called a nested interface. A top-level class or a top-level interface is one that is not nested.

In addition to the top-level classes and interfaces, there are four categories of nested classes and one of nested interfaces, defined by the context these classes and interfaces are declared in:

static member classes and interfaces

non-static member classes

local classes

anonymous classes

The last three categories are collectively known as inner classes. They differ from non-inner classes in one important aspect: that an instance of an inner class may be associated with an instance of the enclosing class. The instance of the enclosing class is called the immediately enclosing instance. An instance of an inner class can access the members of its immediately enclosing instance by their simple name.

A static member class or interface is defined as a static member in a class or an interface. Such a nested class can be instantiated like any ordinary top-level class, using its full name. No enclosing instance is required to instantiate a static member class. Note that there are no non-static member, local, or anonymous interfaces. Interfaces are always defined either at the top level or as static members.

Non-static member classes are defined as instance members of other classes, just like fields and instance methods are defined in a class. An instance of a non-static member class always has an enclosing instance associated with it.

Local classes can be defined in the context of a block as in a method body or a local block, just as local variables can be defined in a method body or a local block.

Anonymous classes can be defined as expressions and instantiated on the fly. An instance of a local (or an anonymous) class has an enclosing instance associated with it, if the local (or anonymous) class is declared in a non-static context.

A nested class or interface cannot have the same name as any of its enclosing classes or interfaces.

Table 7.1 presents a summary of various aspects relating to nested classes and interfaces. The Entity column lists the different kinds of classes and interfaces that can be declared. The Declaration Context column lists the lexical context in which the class or interface can be defined. The Accessibility Modifiers column indicates what accessibility can be specified for the class or interface. The Enclosing Instance column specifies whether an enclosing instance is associated with an instance of the class. The Direct Access to Enclosing Context column lists what is directly accessible in the enclosing context from within the class or interface. The Declarations in Entity Body column refers to what can be declared in the class or interface body. Subsequent sections on each nested class elaborate on the summary presented in Table 7.1. (N/A in the table means not applicable.)

Nested type (i.e., nested classes and interfaces) can be regarded as a form of encapsulation, enforcing relationships between types by greater proximity. They allow structuring of types and a special binding relationship between a nested object and its enclosing instance. Used judiciously, they can be beneficial, but unrestrained use of nested classes can easily result in unreadable code.

Nested type (i.e., nested classes and interfaces) can be regarded as a form of encapsulation, enforcing relationships between types by greater proximity. They allow structuring of types and a special binding relationship between a nested object and its enclosing instance. Used judiciously, they can be beneficial, but unrestrained use of nested classes can easily result in unreadable code.

Table 7.1. Overview of Classes and Interfaces

Entity

Declaration Context

Accessibility Modifiers

Enclosing Instance

Direct Access to Enclosing Context

Declarations in Entity Body

Top-level Class (or Interface)

Package

public or default

No

N/A

All that are valid in a class (or interface) body

Static Member Class (or Interface)

As static member of enclosing class or interface

All

No

Static members in enclosing context

All that are valid in a class (or interface) body

Non-static Member Class

As non-static member of enclosing class or interface

All

Yes

All members in enclosing context

Only non-static declarations + final static fields

Local Class

In block with non-static context

None

Yes

All members in enclosing context + final local variables

Only non-static declarations + final static fields

In block with static context

None

No

Static members in enclosing context + final local variables

Only non-static declarations + final static fields

Anonymous Class

As expression in non-static context

None

Yes

All members in enclosing context + final local variables

Only non-static declarations + final static fields

As expression in static context

None

No

Static members in enclosing context + final local variables

Only non-static declarations + final static fields


Wednesday, August 6, 2008

Object Class

The Object Class
All classes extend the Object class, either directly or indirectly. A class declaration, without the extends clause, implicitly extends the Object class. Thus, the Object class is always at the top of any inheritance hierarchy. The Object class defines the basic functionality that all objects exhibit and that all classes inherit. Note that this also applies for arrays, since these are genuine objects in Java.

The Object class provides the following general utility methods :

int hashCode()

When storing objects in hash tables, this method can be used to get a hash value for an object. This value is guaranteed to be consistent during the execution of the program.

boolean equals(Object obj)

Object reference and value equality are discussed together with the == and != operators (see Section 3.10, p. 68). The equals() method in the Object class returns true only if the two references compared denote the same object. The equals() method is usually overridden to provide the semantics of object value equality, as is the case for the wrapper classes and the String class.

final Class getClass()

Returns the runtime class of the object, which is represented by an object of the class java.lang.Class at runtime.

protected Object clone() throws CloneNotSupportedException

New objects that are exactly the same (i.e., have identical states) as the current object can be created by using the clone() method, that is, primitive values and reference values are copied. This is called shallow copying. A class can override this method to provide its own notion of cloning. For example, cloning a composite object by recursively cloning the constituent objects is called deep copying.

When overridden, the method in the subclass is usually declared public to allow any client to clone objects of the class.

If the overriding clone() method relies on the clone() method in the Object class, then the subclass must implement the Cloneable marker interface to indicate that its objects can be safely cloned. Otherwise, the clone() method in the Object class will throw a checked CloneNotSupportedException.

String toString()

If a subclass does not override this method, it returns a textual representation of the object, which has the following format:

"(name of the class)@(hash code value of object)"

This method is usually overridden and used for debugging purposes. The method call System.out.println(objRef) will implicitly convert its argument to a textual representation using the toString() method.

protected void finalize() throws Throwable

This method is called on an object just before it is garbage collected, so that any cleaning up can be done. However, the default finalize() method in the Object class does not do anything useful.

In addition, the Object class provides support for thread communication in synchronized code, through the following methods :

final void wait(long timeout) throws InterruptedException
final void wait(long timeout, int nanos) throws InterruptedException
final void wait() throws InterruptedException
final void notify()
final void notifyAll()

A thread invokes these method on the object whose lock it holds. A thread waits for notification by another thread.

Tuesday, August 5, 2008

Do u know Java well! Try these questions.. already asked in MNC's interviews

Question: What is the package?
Answer: The package is a Java namespace or part of Java libraries. The Java API is grouped into libraries of related classes and interfaces; these libraries are known as packages.

Question: What is native code?
Answer: The native code is code that after you compile it, the compiled code runs on a specific hardware platform.

Question: Is Java code slower than native code?
Answer: Not really. As a platform-independent environment, the Java platform can be a bit slower than native code. However, smart compilers, well-tuned interpreters, and just-in-time bytecode compilers can bring performance close to that of native code without threatening portability.

Question: What is the serialization?
Answer: The serialization is a kind of mechanism that makes a class or a bean persistence by having its properties or fields and state information saved and restored to and from storage.

Question: How to make a class or a bean serializable?
Answer: By implementing either the java.io.Serializable interface, or the java.io.Externalizable interface. As long as one class in a class's inheritance hierarchy implements Serializable or Externalizable, that class is serializable

Question: How many methods in the Serializable interface?
Answer:There is no method in the Serializable interface. The Serializable interface acts as a marker, telling the object serialization tools that your class is serializable.

Question: . How many methods in the Externalizable interface?
Answer: There are two methods in the Externalizable interface. You have to implement these two methods in order to make your class externalizable. These two methods are readExternal() and writeExternal().

Question: What is the difference between Serializalble and Externalizable interface?
Answer: When you use Serializable interface, your class is serialized automatically by default. But you can override writeObject() and readObject() two methods to control more complex object serailization process. When you use Externalizable interface, you have a complete control over your class's serialization process.

Question: What is a transient variable?
Answer: A transient variable is a variable that may not be serialized. If you don't want some field to be serialized, you can mark that field transient or static.

Question: Which containers use a border layout as their default layout?
Answer: The Window, Frame and Dialog classes use a border layout as their default layout.

Question: . How are Observer and Observable used?
Answer: Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.

Question: What is synchronization and why is it important?
Answer: With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often causes dirty data and leads to significant errors.

Question: What are synchronized methods and synchronized statements?
Answer: Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.

Question: How are Observer and Observable used?
Answer: Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.

Question: What is synchronization and why is it important?
Answer: With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often causes dirty data and leads to significant errors.

Question: What are synchronized methods and synchronized statements?
Answer: Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.

Question: What are three ways in which a thread can enter the waiting state?
Answer: A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O, by unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method.

Sunday, August 3, 2008

Java Keywords & Literals

Java Keywords

Keywords are reserved identifiers that are predefined in the language and cannot be used to denote other entities. All the keywords are in lowercase, and incorrect usage results in compilation errors.

Keywords currently defined in the language are listed in Table 2.1. In addition, three identifiers are reserved as predefined literals in the language: the null reference and the Boolean literals true and false. Keywords currently reserved, but not in use, are listed in Table 2.3. All these reserved words cannot be used as identifiers. The index contains references to relevant sections where currently defined keywords are explained.

Table 2.1. Keywords in Java

abstract

default

implements

protected

throw

assert

do

import

public

throws

boolean

double

instanceof

return

transient

break

else

int

short

try

byte

extends

interface

static

void

case

final

long

strictfp

volatile

catch

finally

native

super

while

char

float

new

switch

class

for

package

synchronized

continue

if

private

this

Table 2.2. Reserved Literals in Java

null

true

false

Table 2.3. Reserved Keywords not Currently in Use

const

goto

Literals

A literal denotes a constant value, that is, the value a literal represents remains unchanged in the program. Literals represent numerical (integer or floating-point), character, boolean or string values. In addition, there is the literal null that represents the null reference.

Table 2.4. Examples of Literals

Integer

2000    0      -7

Floating-point

3.14    -3.14  .5     0.5

Character

'a'     'A'    '0'    ':'    '-'    ')'

Boolean

true    false

String

"abba"  "3.14"  "for"  "a piece of the action"

Integer Literals

Integer data types are comprised of the following primitive data types: int, long, byte, and short

The default data type of an integer literal is always int, but it can be specified as long by appending the suffix L (or l) to the integer value. Without the suffix, the long literals 2000L and 0l will be interpreted as int literals. There is no direct way to specify a short or a byte literal.

In addition to the decimal number system, integer literals can also be specified in octal (base 8) and hexadecimal (base 16) number systems. Octal and hexadecimal numbers are specified with 0 and 0x (or 0X) prefix respectively. Examples of decimal, octal and hexadecimal literals are shown in Table2.5. Note that the leading 0 (zero) digit is not the uppercase letter O. The hexadecimal digits from a to f can also be specified with the corresponding uppercase forms (A to F). Negative integers (e.g. -90) can be specified by prefixing the minus sign (-) to the magnitude of the integer regardless of number system (e.g., -0132 or -0X5A). Java does not support literals in binary notation.

Table 2.5. Examples of Decimal, Octal, and Hexadecimal Literals

Decimal

Octal

Hexadecimal

8

010

0x8

10L

012L

0XaL

16

020

0x10

27

033

0x1B

90L

0132L

0x5aL

-90

-0132

-0X5A

2147483647 (i.e., 231-1)

017777777777

0x7fffffff

-2147483648 (i.e., -231)

-020000000000

-0x80000000

1125899906842624L (i.e., 250)

040000000000000000L

0x4000000000000L

Floating-point Literals

Floating-point data types come in two flavors: float or double.

The default data type of a floating-point literal is double, but it can be explicitly designated by appending the suffix D (or d) to the value. A floating-point literal can also be specified to be a float by appending the suffix F (or f).

Floating-point literals can also be specified in scientific notation, where E (or e) stands for Exponent. For example, the double literal 194.9E-2 in scientific notation is interpreted as 194.9*10-2 (i.e., 1.949).

Examples of double Literals
0.0       0.0d       0D
0.49 .49 .49D
49.0 49. 49D
4.9E+1 4.9E+1D 4.9e1d 4900e-2 .49E2
Examples of float Literals
0.0F      0f
0.49F .49F
49.0F 49.F 49F
4.9E+1F 4900e-2f .49E2F

Note that the decimal point and the exponent are optional and that at least one digit must be specified.

Boolean Literals

The primitive data type boolean represents the truth-values true or false that are denoted by the reserved literals true or false, respectively.

Character Literals

A character literal is quoted in single-quotes ('). All character literals have the primitive data type char.

Characters in Java are represented by the 16-bit Unicode character set, which subsumes the 8-bit ISO-Latin-1 and the 7-bit ASCII characters. In Table 2.6, note that digits (0 to 9), upper-case letters (A to Z), and lower-case letters (a to z) have contiguous Unicode values. Any Unicode character can be specified as a four-digit hexadecimal number (i.e., 16 bits) with the prefix \u.

Table 2.6. Examples of Unicode Values

Character Literal

Character Literal using Unicode value

Character

' '

'\u0020'

Space

'0'

'\u0030'

0

'1'

'\u0031'

1

'9'

'\u0039'

9

'A'

'\u0041'

A

'B'

'\u0042'

B

'Z'

'\u005a'

Z

'a'

'\u0061'

a

'b'

'\u0062'

b

'z'

'\u007a'

z

'Ñ'

'\u0084'

Ñ

'å'

'\u008c'

å

'ß'

'\u00a7'

ß

Escape Sequences

Certain escape sequences define special character values as shown in Table 2.7. These escape sequences can be single-quoted to define character literals. For example, the character literals '\t' and '\u0009' are equivalent. However, the character literals '\u000a' and '\u000d' should not be used to represent newline and carriage return in the source code. These values are interpreted as line-terminator characters by the compiler, and will cause compile time errors. One should use the escape sequences '\n' and '\r', respectively, for correct interpretation of these characters in the source code.

Table 2.7. Escape Sequences

Escape Sequence

Unicode Value

Character

\b

\u0008

Backspace (BS)

\t

\u0009

Horizontal tab (HT or TAB)

\n

\u000a

Linefeed (LF) a.k.a., Newline (NL)

\f

\u000c

Form feed (FF)

\r

\u000d

Carriage return (CR)

\'

\u0027

Apostrophe-quote

\"

\u0022

Quotation mark

\\

\u005c

Backslash

We can also use the escape sequence \ddd to specify a character literal by octal value, where each digit d can be any octal digit (07), as shown in Table 2.8. The number of digits must be three or fewer, and the octal value cannot exceed \377, that is, only the first 256 characters can be specified with this notation.

Table 2.8. Examples of Escape Sequence \ddd

Escape Sequence \ddd

Character Literal

'\141'

'a'

'\46'

'&'

'\60'

'0'

String Literals

A string literal is a sequence of characters, which must be quoted in quotation marks and which must occur on a single line. All string literal are objects of the class String.

Escape sequences as well as Unicode values can appear in string literals:

"Here comes a tab.\t And here comes another one\u0009!                    (1)
"What's on the menu?" (2)
"\"String literals are double-quoted.\"" (3)
"Left!\nRight!" (4)

In (1), the tab character is specified using the escape sequence and the Unicode value respectively. In (2), the single apostrophe need not be escaped in strings, but it would be if specified as a character literal('\''). In (3), the double apostrophes in the string must be escaped. In (4), we use the escape sequence \n to insert a newline. Printing these strings would give the following result:

Here comes a tab.    And here comes another one    !
What's on the menu?
"String literals are double-quoted."
Left!
Right!

One should also use the string literals "\n" and "\r", respectively, for correct interpretation of the characters "\u000a" and "\u000d" in the source code.

Saturday, August 2, 2008

Clear your concept on shift operators

Shift Operators

Shift left

a <<>

Shift all bits in a left n times, filling with 0 from the right.

Shift right with sign bit

a >> n

Shift all bits in a right n times, filling with the sign bit from the left.

Shift right with zero fill

a >>> n

Shift all bits in a right n times, filling with 0 from the left.

Friday, August 1, 2008

Know wrapper class more

A primitive wrapper class in the java programing language is one of eight classes provided in the java.lang package to provide object method to the eight primitive types. All of the primitive wrapper classes in Java are immutable. J2SE 5.0 introduced autoboxing of primitive types into their wrapper object, and automatic unboxing of the wrapper objects into their primitive value—the implicit conversion between the wrapper objects and primitive values.

Wrapper class is used to represent primitive values when an object is required. The wrapper classes are used extensively with collection classes in the java.utill package and with the classes in the reflection package

The primitive wrapper classes and their corresponding primitive types are:

Primitive type Wrapper class Constructor Arguments
byte
byte or String
short
short or String
int
int or String
long
long or String
float
float, double or String
double
double or String
char
char
boolean
boolean or String

The Byte, Short, Integer, Long, Float, and Double wrapper classes are all subclass of the Number class