Monday, November 15, 2010

Conversions and Java Print Streams:-

(1) Date and time conversions.....

Date and time conversions can be applied to java.util.Calendar and java.util.Date objects. They can also be applied to long andLongvalues, in which case the value is assumed to be the number of milliseconds since midnight, January 1, 1970. All date and time conversions begin with atfor lowercase or aTfor uppercase. These conversions are:

%tH/ %TH
Two-digit hour using a 24-hour clock, ranging from 00
to 23

%tI/%TI
Two-digit hour using a 12-hour clock, ranging from 01
to 12

%tk/ %Tk
One- or two-digit hour using a 24-hour clock, ranging
from 0 to 23

%tl/ %Tl
One- or two-digit hour using a 12-hour clock, ranging
from 1 to 12

%tM/ %TM
Two-digit minutes, ranging from 00 to 59

%tS/ %TS
Two-digit seconds, ranging from 00 to 60 (60 is used
for leap seconds)

%tL/ %TL
Three-digit milliseconds, ranging from 000 to 999

%tN/ %TN
Nine-digit nanoseconds, ranging from 000000000 to
999999999

%tp/ %Tp
Locale-specific morning/afternoon indicator, such as
am or PM

%tz/ %Tz
RFC 822 numeric time zone indicator as an offset
from UMT (for instance, Eastern Standard Time is–
0500)

%tZ/ %TZ
An abbreviation for the time zone, such as edt or EST

%ts/ %Ts
Seconds elapsed since midnight, January 1, 1970,
Greenwich Mean Time

%TQ
Milliseconds elapsed since midnight, January 1, 1970,
Greenwich Mean Time

%tB/ %TB
Localized month, such as “January” or “JANVIER”

%tb/ %Tb
Localized, abbreviated month, such as “Jan” or “JAN”

%th/ %Th
Localized, abbreviated month, such as “Jan” or
“JAN” (yes,%tband%thare synonyms; I have no
idea why)

%tA/ %TA
Localized day name, such as “Tuesday” or “MARDI”

%ta/ %Ta
Localized, abbreviated day, such as “Tue” or “TUE”

%tC/ %TC
Two-digit century, ranging from 00 to 99

%tY/ %TY
Year with at least four digits, ranging from 0001 to
the indefinite future

%ty/ %Ty
Two-digit year, ranging from 00 to 99

%tj/ %Tj
Three-digit day of the year, ranging from 001 to 366

%tm/ %Tm
Two-digit month, ranging from 01 to 13 (13 is used in
some non-Gregorian lunar calendars)

%td/ %Td
Two-digit day of the month, ranging from 01 to 31

%te/ %Te
One- or two-digit day of the month, ranging from 1 to
31

%tR/ %TR
Hours and minutes on a 24-hour clock, such as 03:23
or 14:07

%tT/ %TT
Hours, minutes, and seconds on a 24-hour clock,
such as 03:23:17 or 14:07:00

%tr/ %Tr
Hours, minutes, and seconds on a 12-hour clock,
such as 03:23:17 am or 02:07:00 PM

%tD/ %TD
Date in the form month/day/year, such as 05/12/06

%tF/ %TF
ISO 8601 standard date in the form year-month-day,
such as 2006-05-12

%tc/ %Tc
Date and time formatted like so: “Fri May 12
12:27:30 EDT 2006”

Example :- prints the current date and time in all of these formats.

Example :- Date format specifiers

import java.util.Date;

public class DateFormatExample {

public static void main(String[] args) {
Date now = new Date();
System.out.printf("two-digit hour on a 24-hour clock: %tH/%TH\n", now, now);
System.out.printf("two-digit hour on a 12-hour clock: %tI/%TI\n", now, now);
System.out.printf("one- or two-digit hour on a 24-hour clock: %tk/%Tk\n",
now, now);
System.out.printf("one- or two-digit hour on a 12-hour clock: %tl/%Tl\n", now,
now);
System.out.printf("two-digit minutes ranging from 00 to 59: %tH/%TH\n",
now, now);
System.out.printf("two-digit seconds ranging from 00 to 60 : %tS/%TS\n",
now, now);
System.out.printf("milliseconds: %tL/%TL\n", now, now);
System.out.printf("nanoseconds: %tN/%TN\n", now, now);
System.out.printf("locale-specific morning/afternoon indicator: %tp/%Tp\n",
now, now);
System.out.printf("RFC 822 numeric time zone indicator: %tz/%Tz\n", now, now);
System.out.printf("time zone abbreviation: %tZ/%TZ\n", now, now);
System.out.printf("seconds since the epoch: %ts/%Ts\n", now, now);
System.out.printf("milliseconds since the epoch: %TQ\n", now);
System.out.printf("localized month name: %tB/%TB\n", now, now);
System.out.printf("localized, abbreviated month: %tb/%Tb\n", now, now);
System.out.printf("localized, abbreviated month: %th/%Th\n", now, now);
System.out.printf("localized day name: %tA/%TA\n", now, now);
System.out.printf("localized, abbreviated day: %ta/%Ta\n", now, now);
System.out.printf("two-digit century:
%tC/%TC\n", now, now);
System.out.printf("four-digit year:
%tY/%TY\n", now, now);
System.out.printf("two-digit year:
%ty/%Ty\n", now, now);
System.out.printf("three-digit day of the year: %tj/%Tj\n", now, now);
System.out.printf("two-digit month:
%tm/%Tm\n", now, now);
System.out.printf("two-digit day of the month: %td/%Td\n", now, now);
System.out.printf("one- or two-digit day of the month: %te/%Te\n", now, now);
System.out.printf("hours and minutes on a 24-hour clock: %tR/%TR\n", now, now);
System.out.printf("hours, minutes, and seconds on a 24-hour clock: %tT/%TT\n",
now, now);
System.out.printf("hours, minutes, and seconds on a 12-hour clock: %tr/%Tr\n",
now, now);
System.out.printf("month/day/year:
%tD/%TD\n", now, now);
System.out.printf("ISO 8601 standard date: %tF/%TF\n", now, now);
System.out.printf("Unix date format:
%tc/%Tc\n", now, now);
}
}

Here’s the output when this was run on Friday, June 24, 2005 at 6:43 PM EDT:

two-digit hour on a 24-hour clock: 18/18
two-digit hour on a 12-hour clock: 06/06
one- or two-digit hour on a 24-hour clock: 18/18
one- or two-digit hour on a 12-hour clock: 6/6
two-digit minutes ranging from 00 to 59: 18/18
two-digit seconds ranging from 00 to 60 : 50/50
milliseconds: 859/859
nanoseconds: 859000000/859000000
locale-specific morning/afternoon indicator: pm/PM
RFC 822 numeric time zone indicator:
-0500/-0500
time zone abbreviation: EDT/EDT
seconds since the epoch: 1119653030/1119653030
milliseconds since the epoch: 1119653030859
localized month name: June/JUNE
localized, abbreviated month: Jun/JUN
localized, abbreviated month: Jun/JUN
localized day name: Friday/FRIDAY
localized, abbreviated day: Fri/FRI
two-digit century: 20/20
four-digit year: 2005/2005
two-digit year: 05/05
three-digit day of the year: 175/175
two-digit month: 06/06
two-digit day of the month: 24/24
one- or two-digit day of the month: 24/24
hours and minutes on a 24-hour clock: 18:43/18:43
hours, minutes, and seconds on a 24-hour clock: 18:43:50/18:43:50
hours, minutes, and seconds on a 12-hour clock: 06:43:50 PM/06:43:50 PM
month/day/year: 06/24/05/06/24/05
ISO 8601 standard date: 2005-06-24/2005-06-24
Unix date format: Fri Jun 24 18:43:50 EDT 2005/FRI JUN 24 18:43:50 EDT 2005


(2) Conversions and Java Print Streams - Character conversions


Character conversions can be applied to char and java.lang.Character objects. They can also be applied to byte, short,int, and the equivalent type-wrapper objects if the integer falls into the range of Unicode code points (0 to 0x10FFFF). These
conversions are:

%c
A lowercase Unicode character

%C
An uppercase Unicode character

Boolean conversions

Boolean conversions can be applied to boolean primitive values and java.lang.Boolean objects. They can also be applied to all object types, in which case they’re considered to be true if the object is nonnull and false if it is null. All other primitive types are considered to be true, regardless of value. These conversions are:

%b
“true” or “false”

%B
“TRUE” or “FALSE”

These conversions are not localized. Even in France, you’ll see “true” and “false” instead of “vrai” and “faux.”

General conversions

There are two more conversions that can be applied to any object and also to primitive types after autoboxing. These are:

%h/%H
The lowercase/uppercase hexadecimal form of the
object’shashCode, or “null” or “NULL” if the object is
null.

%s/%S
The result of invoking the object’sformatTo()
method if it implements Formattable; otherwise,
the result of invoking its toString()method, or
“null” if the object is null. With%S, this value is then
converted to uppercase.

Example :- General format specifiers

import java.net.*;

public class GeneralFormatExample {

public static void main(String[] args) throws MalformedURLException{
URL u = new URL(http://www.example.com/Article.html);
System.out.printf("boolean: %b\n", u);
System.out.printf("BOOLEAN: %B\n", u);
System.out.printf("hashcode: %h\n", u);
System.out.printf("HASHCODE: %H\n", u);
System.out.printf("string: %s\n", u);
System.out.printf("STRING: %S\n", u);
}
}

Here’s the output from running this on a U.S.-localized system:

boolean: true
BOOLEAN: TRUE
hashcode: 79d2cef0
HASHCODE: 79D2CEF0
string: http://www.example.com/ Article.html
STRING: HTTP://WWW.EXAMPLE.COM/ ARTICLE.HTML

(3). Conversions and Java Print Streams - Format Modifiers

In addition to a conversion code, the format string can also specify a width, a precision, the argument it’s replaced with, and any of several special-purpose flags. The most general format follows this pattern:

%[argument_index$][flags][width][.precision]conversion

Here is a quick definition of those parameters. More detail on each will follow:

argument_index

The number of the argument with which to replace this tag

flags

Indicators of various formatting options

width

The minimum number of characters with which to format the replacement value

precision

The number of characters after the decimal point; alternately, the maximum number of characters in the formatted string

These four options control exactly how a string is formatted as tags are replaced by values.

Argument index

The argument index is specified when the order of the arguments does not match the order of the tags. For example:

out.printf("There are %2$f centimeters in %1$f feet.", feet, 2.54 * feet * 12);

In this case, indexes start with 1 rather than 0, which is unusual for Java. (The format string counts as argument 0.) If you reference a nonexistent argument,printf()throws aMissingFormatArgumentException.

The argument index is particularly useful when you want to repeat the same value more than once in a string, perhaps formatted differently each time. For example:

System.out.printf("Hexadecimal: %1$H Decimal: %1$f", Math.PI);

You can also repeat the previous argument by specifying a less than sigh (<) rather than an integer and a dollar sign ($). For instance, this statement is equivalent to the previous statement:

System.out.printf("Hexadecimal: %1$H Decimal: %

(4). Conversions and Java Print Streams - Flags

Flags indicate a variety of formatting options. Not all flags apply to all types. Using a flag to format a type that does not apply throws a FormatFlagsConversionMismatchException, a subclass of IllegalFormatException. However, you can combine multiple flags that do apply.

Flag Signifies Applies to
- Left-justify. All
# Alternate form. General, integer, floating point
+ Include a sign even if positive.
(Normally, only negative numbers have signs.) Integer, floating point
space Add a leading space to positive numbers. Integer, floating point
(This is where the sign would be and helps line up
positive and negative numbers.)
0 Pad with zeros instead of spaces. Integer, floating point
, Use the locale-specific grouping separator instead Integer, floating point
of a period.
( Use instead of a minus sign to indicate negative Integer, floating point
numbers.


For example, this statement prints adoubleformatted as a 20-character decimal padded with zeros, using a locale-specific grouping separator and parentheses for negative numbers:

System.out.printf("%(+0,20f", -Math.PI);

The result is(00000000003.141593).

The relative order of the flags does not matter. This statement prints the same thing:

System.out.printf("%,0+(20f", -Math.PI);

Width

Each of the various conversions may be preceded by an optional width. This sets the minimum number of characters to print. For example, if you format an integer using the code %5d, it will always be printed at least five characters wide. If the integer has fewer than five digits, extra spaces are added on the left-hand side to make up five characters. If it has five or more digits, no extra spaces are added.
The entire number is always printed. If the argument is larger than can fit in five places, all of it will be printed anyway, and subsequent columns may no longer line up properly.
For example, this statement prints five mathematical constants, each 12 places wide:

System.out.printf("%12f %12f %12f %12f
%12f",
Math.PI, Math.E, 1.0, 0.0, Math.sqrt(2));

By default, extra places are filled with space characters to right-justify the numbers. However, flags can be used to fill extra places with zeros or to left-justify the numbers instead.
This is the output:
3.141593 2.718282 1.000000 0.000000 1.414214

Width is not limited to numeric types. You can specify a width for any format tag: date, time, boolean, and so on.

(5). Conversions and Java Print Streams - Precision

Floating-point types (%e, %E, %f, %g, and%G) may also specify a precision in the form.3or.5. The precision comes after the width but before the conversion code. This indicates how many places are used after the decimal point. For example, this statement formats the same five constants 15 places wide, with 3 places after the decimal point:

System.out.printf("%15.3f %15.3f %15.3f
%15.3f %15.3f",
Math.PI, Math.E, 1.0, 0.0, Math.sqrt(2));
This is the output:
3.142 2.718 1.000 0.000 1.414
A precision can also be applied to strings and other nonnumeric, nondate types. In these cases, it specifies the maximum number of characters to write to the output.
Precision cannot be set for integral types, however. Attempting to do so throws anIllegalFormatPrecisionException. As usual, this is a subclass ofIllegalFormatExceptionand a runtime exception.

Formattable:-

You can format your own custom classes by implementing the Formattable interface. In format strings, you use %s and %S to indicate where you want your custom class instances placed. The default formatting for objects matched to %s and %S is simply whatever is returned by toString(). However, more often than not, this is just a debugging string not really meant for display to end users. If your class implements the java.util.Formattable interface, Java will use the return value of the object’s formatTo() method instead. That method has this signature:
public void formatTo(Formatter formatter, int flags, int width, int precision)

The four arguments are:

formatter
TheFormatterthat calledformatTo. More importantly, this is the object onto which the output will be written. Your method will invoke this object’sformat() methods to write to the underlying stream.
flags
A bitmasked constant providing the values of various flags set for this operation: ^,-,#, etc. You interpret these with theFormattableFlagsclass.
width
The minimum number of characters your method must return. If the returned value has fewer characters than the specified minimum, it will be padded with spaces.
precision
The maximum number of characters your method should return. Earlier, I complained that the uppercasing in the URL class was too naïve because, when formatted, it changed the case of case-sensitive parts such as the path and the query string as well as case-insensitive parts such as the scheme and the hostname. There’s another problem with the naïve uppercasing: the scheme and host names are defined in ASCII, but uppercasing isn’t always. In particular, uppercasing the letter i in Turkey produces the capital dotted I rather than the usual undotted capital I. For instance, WWW.microsoft.com uppercases as WWW.MICROSOFT.COM, which will not resolve.
Example:- demonstrates aFormattableURLclass that uppercases only those parts of a URL that can be uppercased without changing its meaning. Ideally this would be a subclass of java.net.URL, but sinceURL is final, delegation is used instead. In essence,FormattableURLis a wrapper around a URL object that just provides theformatTo()method.

Example . Implementing Formattable

import java.util.*;
import java.net.*;
public class FormattableURL implements Formattable {

private URL delegate;

public FormattableURL(URL url){
this.delegate = url;
}

public void formatTo(Formatter formatter, int flags, int width,
int precision) {

if (precision < -1) {
throw new IllegalFormatPrecisionException(precision);
}
if (width < -1) {
throw new IllegalFormatWidthException(width);
}
if (precision > width) {
throw new IllegalFormatPrecisionException(precision);
}

// Check to see if we've been asked to use any flags we don't interpret
int recognizedFlags
= FormattableFlags.UPPERCASE | FormattableFlags.LEFT_JUSTIFY;
boolean unsupportedFlags = ((~recognizedFlags) & flags) != 0;
if (unsupportedFlags) {
// We should really pass the flags to this constructor.
// However, Java doesn't offer any reasonable way to get these.
throw new IllegalFormatFlagsException("#");
}

boolean upperCase = (flags & FormattableFlags.UPPERCASE) != 0;

StringBuffer sb = new StringBuffer();

String scheme = delegate.getProtocol();
if (upperCase && scheme != null) {
scheme = scheme.toUpperCase(Locale.ENGLISH);
}

String hostname = delegate.getHost();
if (upperCase && hostname != null) {
hostname = hostname.toUpperCase(Locale.ENGLISH);
}

String userInfo = delegate.getUserInfo();

int port = delegate.getPort();
String path = delegate.getPath();
String query = delegate.getQuery(); String fragment = delegate.getRef();
if (scheme != null) {
sb.append(scheme);
sb.append("://");
}

if (userInfo != null) {
sb.append(userInfo);
sb.append("@");
}

if (hostname != null) {
sb.append(hostname);
}

if (port != -1) {
sb.append(':');
sb.append(port);
}

if (path != null) {
sb.append(path);
}

if (query != null) {
sb.append('?');
sb.append(query);
}

if (fragment != null) {
sb.append('#');
sb.append(fragment);
}

boolean leftJustify = (flags & FormattableFlags.LEFT_JUSTIFY) != 0;

// Truncate on the right if necessary
if (precision <>
sb.setLength(precision);
}
else {// Pad with spaces if necessary
while (sb.length() <>
if (leftJustify) sb.append(' ');
else sb.insert(0, ' ');
}
}

formatter.format(sb.toString());
}
}

The formatTo()method first checks to see if the values passed make sense—that is, that the width is greater than or equal to the precision, and both are greater than or equal to –1. (–1 simply indicates that these values weren’t set.) Assuming these checks pass, it splits the delegate URL into its component parts and uppercases the two case-insensitive parts (the scheme and the hostname) if the uppercase flag is set. It then appends all the other parts without changing their cases at all. Finally, if the precision is less than the string’s length, the formatted string is truncated on the right. If the string’s length is less than the specified width, the string is padded with spaces: on the right by default but on the left if the left-justified flag is set. If any other flags are present, anIllegalFormatFlagsExceptionis thrown. Thus, it becomes possible to format a URL like this:

URL url = new URL(http://www.example.org/index.html?name=value#Fred);
System.out.printf("%60.40S\n", new FormattableURL(url));

Monday, November 1, 2010

Formatters and Java Print Streams

Constructors

Exactly where the output from a Formatter ends up depends on what argument you pass to the constructor. You’ve already seen the constructor that takes a filename:

public Formatter(String fileName) throws FileNotFoundException

If the named file does not exist in the current working directory, this constructor attempts to create it. If that fails for any reason other than a security violation, the constructor throws aFileNotFoundException. Security problems are reported with aSecurityExceptioninstead. If the file does exist, its contents are overwritten.

Instead of a filename, you can pass in aFileobject:

public Formatter(File file) throws FileNotFoundException

You can also use aFormatterto write onto aPrintStreamor another kind ofOutputStream:

public Formatter(PrintStream out)
public Formatter(OutputStream out)

or onto anyAppendableobject:

public Formatter(Appendable out)

TheAppendableinterface is a new Java 5 interface for anything onto whichchars can be appended. This includesStringBuffers andStringBuilders. It also includes a number of classes we’ll talk about later, such asCharBuffer andWriter.

Finally, the no-args constructor creates aFormatterwith no specified destination for output:

public Formatter()

In this case, theFormatterwrites everything onto a newStringBuilderobject. You can retrieve this object using theout()method at any time before theFormatteris closed:

public Appendable out() throws FormatterClosedException

You might need to use this method if you want to write unformatted output onto the sameStringBuilder, but more commonly you’ll just use thetoString()method to get the final result. For example:

Formatter formatter = new Formatter();
for (double degrees = 0.0; degrees <>
double radians = Math.PI * degrees / 180.0;
double grads = 400 * degrees / 360;
formatter.format("%5.1f %5.1f %5.1f\n", degrees , radians, grads);
}
String table = formatter.toString();


Formatters and Java Print Streams - Character Sets

stick to the ASCII character set, a single computer, and System.out, character sets aren’t likely to be a problem. However, as data begins to move between different systems, it becomes important to consider what happens when the other systems use different character sets. For example, suppose I use a Formatteror aPrintStream on a typical U.S. or Western European PC to write the sentence “Au cours des dernières années, XML a été adapte dans des domaines aussi diverse que l’aéronautique, le multimédia, la gestion de hôpitaux, les télécommunications, la théologie, la vente au détail, et la littérature médiévale” in a file. Say I then send this file to a Macintosh user, who opens it up and sees “Au cours des derniËres annÈes, XML a ÈtÈ adapte dans des domaines aussi diverse que l’aÈronautique, le multimÈdia, la gestion de hÙpitaux, les tÈlÈcommunications, la thÈologie, la vente au dÈtail, et la littÈrature mÈdiÈvale.” This is not the same thing at all! The confusion is even worse if you go in the other direction.

If you’re writing to the console (i.e.,System.out), you don’t really need to worry about character set issues. The default character set Java writes in is usually the same one the console uses.

Actually, you may need to worry a little. On Windows, the console encoding is usually not the same as the system encoding found in thefile.encodingsystem property. In particular, the console uses a DOS character set such as Cp850 that includes box drawing characters such as L and +, while the rest of the system uses an encoding such as Cp1252 that maps these same code points to alphabetic characters like È and Î. To be honest, the console is reliable enough for ASCII, but anything beyond that requires a GUI.

However, there’s more than one character set, and when transmitting files between systems and programs, it pays to be specific. In the previous example, if we knew the file was going to be read on a Macintosh, we might have specified that it be written with the MacRoman encoding:

Formatter formatter = new Formatter("data.txt", "MacRoman");

More likely, we’d just agree on both the sending and receiving ends to use some neutral format such as ISO-8859-1 or UTF-8. In some cases, encoding details can be embedded in the file you write (HTML, XML) or sent as out-of-band metadata (HTTP, SMTP). However, you do need some way of specifying and communicating the character set in which any given document is written. When you’re writing to anything other than the console or a string, you should almost always specify an encoding explicitly. Three of theFormatterconstructors take character set names as their second argument:

public Formatter(String fileName, String characterSet)
throws FileNotFoundException
public Formatter(File file , String characterSet)
throws FileNotFoundException
public Formatter(OutputStream out, String characterSet)


Formatters and Java Print Streams - Locales

Character sets are not the only localization issue in the Formatter class. For instance, in France, a decimal comma is used instead of a decimal point. Thus, a French user running the earlier degree table example would want to see this:

0,0 0,0 0,0
1,0 0,0 1,1
2,0 0,0 2,2
3,0 0,1 3,3
4,0 0,1 4,4
...

Sometimes Java adapts the format to the local conventions automatically, and sometimes it doesn’t. For instance, if you want decimal commas, you have to write%,5.1finstead of%5.1f. The comma after the percent sign is a flag that tells the formatter to use the local conventions. (It does not actually say to use commas.) Java will now use commas only if the local conventions say to use commas. On a typical U.S. English system, the local convention is a decimal point, and that’s what you’ll get even if you format numbers as%,5.1f.

Of course, sometimes you don’t want a program to adapt to the local conventions. For instance, many companies use PCs adapted to local languages and customs but still need to produce English documents that use American formats. Thus, as an optional third argument to the constructor, you can pass ajava.util.Localeobject:

public Formatter(String fileName, String characterSet, Locale locale)
throws FileNotFoundException
public Formatter(File file, String characterSet, Locale locale)
throws FileNotFoundException
public Formatter(OutputStream out, String characterSet, Locale locale)

For example, to force the use of American conventions regardless of where a program is run, you’d construct aFormatterlike this:

Formatter formatter = new Formatter("data.txt", "ISO-8859-1", Locale.US);

You can also specify a locale when writing to anAppendableobject or aStringBuilder:

public Formatter(Appendable out, Locale locale)
public Formatter(Locale locale)

Character encodings don’t matter for these two cases because bothAppendableandStringBuilderare defined in terms of characters rather than bytes—there’s no conversion to be done. However, locales can change formatting even when the character set stays the same.

On occasion, you might wish to change the locale for one string you write but not for other strings (in a mixed English/French document, perhaps). In that case, you can pass a locale as the first argument to theformat()method before the format string:

public Formatter format(Locale locale, String format, Object... args)

You can do the same thing with theprintf()andformat()methods in thePrintStreamclass:

public PrintStream printf(Locale locale, String format, Object... args)

Finally, I’ll note that there’s a getter method that returns theFormatter’s current locale:

public Locale locale()

Error Handling

The Formatter class handles errors in much the same way PrintStream does. That is, it sweeps them under the rug and pretends they didn’t happen. Notice how none of the methods mentioned so far threwIOException?

To find out if theFormatterhas encountered an error, invoke itsioException()method:

public IOException ioException()

This returns the las tIOExceptionthrown by the underlying output stream. If there was more than one, only the last one is available.

This is marginally better than PrintStream’s booleancheckError()method. At leastFormatter will tell you what the problem was. However, it still won’t tell you unless you ask. For simple cases in which you don’t have to write a lot of data before closing theFormatterand checking for any errors, this may be adequate. However, programs that need to write for an extended period of time should probably create strings using a Formatter but write them using a regularOutputStream. That way, if an I/O error does happen, you’ll find out soon enough to do something about it.

Formatters and Java Print Streams - Format Specifiers


The Formatter class and the printf() method inPrintStreamthat depends on it support several dozen format specifiers. In addition to integer and floating-point numbers,Formatter offers a wide range of date and time formats. It also has a few general formatters that can display absolutely any object or primitive data type.

All format specifiers begin with percent signs. The minimum format specifier is a percent sign followed by an alphabetic conversion code. This code identifies what the corresponding argument is to be formatted as. For instance,%fformats a number with a decimal point,%dformats it as a decimal (base-10) integer,%oformats it as an octal integer, and%xformats it as a hexadecimal integer. None of these specifiers changes what the number actually is; they’re just different ways of creating a string that represents the number.

To use a literal percent character in a format string, just double escape it. That is,%%is formatted as%in the output.

To get the platform default line separator, use%n.(\nis always a linefeed regardless of platform.%nmay be a carriage return, a linefeed, or a carriage return linefeed pair, depending on the platform.)

Integer conversions

Integer conversions can be applied to all integral types (specifically, byte, short,int, andlong, as well as the type-wrapper classesByte,Short,Integer,Long, and also thejava.math.BigIntegerclass). These conversions are:

%d
A regular base-10 integer, such as 987

%o
A base-8 octal integer, such as 1733

%x
A base-16 lowercase hexadecimal integer, such as
3db

%X
A base-16 uppercase hexadecimal integer, such as
3DB

Example 7-1 prints the number 1023 in all four formats.

Example 7-1. Integer format specifiers

public class IntegerFormatExample {

public static void main(String[] args) {
int n = 1023;
System.out.printf("Decimal: %d\n", n);
System.out.printf("Octal: %o\n", n);
System.out.printf("Lowercase hexadecimal: %x\n", n);
System.out.printf("Uppercase hexadecimal: %X\n", n);
}
}

Here’s the output:

Decimal: 1023
Octal: 1777
Lowercase hexadecimal: 3ff
Uppercase hexadecimal: 3FF

Formatters and Java Print Streams - Floating-point conversions :-\

Floating-point conversions can be applied to all floating-point types: float and double, the type-wrapper classesFloatandDouble, andjava.math.BigDecimal. These conversions are:

%f
A regular base-10 decimal number, such as 3.141593

%e
A decimal number in scientific notation with a
lowercase e, such as 3.141593e+00

%E
A decimal number in scientific notation with an
uppercase E, such as 3.141593E+00

%g
A decimal number formatted in either regular or
scientific notation, depending on its size and
precision, with a lowercase e if scientific notation is
used

%G
A decimal number formatted in either regular or
scientific notation, depending on its size and
precision, with an uppercase E if scientific notation is
used

%a
A lowercase hexadecimal floating-point number, such
as 0x1.921fb54442d18p1

%A
An uppercase hexadecimal floating-point number,
such as 0X1.921FB54442D18P1

Surprisingly, you cannot use these conversions on integer types such asintorBigDecimal. Java will not automatically promote the integer type to a floating-point type when formatting. If you try to use them, it throws anIllegalFormatConversionException.

Example 7-2 prints π in all of these formats.

Example 7-2. Floating-point format specifiers

public class FloatingPointFormatExample {

public static void main(String[] args){
System.out.printf("Decimal: %f\n", Math.PI);
System.out.printf("Scientific notation: %e\n", Math.PI);
System.out.printf("Scientific notation: %E\n", Math.PI);
System.out.printf("Decimal/Scientific: %g\n", Math.PI);
System.out.printf("Decimal/Scientific: %G\n", Math.PI);
System.out.printf("Lowercase Hexadecimal: %a\n", Math.PI);
System.out.printf("Uppercase Hexadecimal: %A\n", Math.PI);
}
}

Here’s the output:

Decimal: 3.141593
Scientific notation: 3.141593e+00
Scientific notation: 3.141593E+00
Decimal/Scientific: 3.14159
Decimal/Scientific: 3.14159
Lowercase Hexadecimal: 0x1.921fb54442d18p1
Uppercase Hexadecimal: 0X1.921FB54442D18P1

Monday, October 11, 2010

Java Print Streams

Java Print Streams


The first two output streams that Java programmers encounter are usually instances of the java.io.Printstream class. If you want to learn more about print streams, keep reading; this is the first part of a three-part series on the topic. It is excerpted from chapter seven of Java I/O, Second Edition, written by Elliotte Rusty Harold (O'Reilly, 2006; ISBN: 0596527500). Copyright © 2006 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

System.out is the first output stream most Java programmers encounter. System.err is probably the second. Both are instances of thejava.io.PrintStreamclass.PrintStreamis a subclass ofFilterOutputStreamthat converts numbers and objects to text.System.outis primarily used for simple, character-mode applications and for debugging. Its raison d’étre is convenience, not robustness; print streams ignore many issues involved in internationalization and error checking. This makesSystem.outeasy to use in quick-and-dirty hacks and simple examples, while simultaneously making it unsuitable for production code, which should use thejava.io.PrintWriterclass
PrintStreamis not limited to the console.PrintStreamis a filter stream and thus can be connected to any other output stream: aFileOutputStream, aByteArrayOutputStream, aTelnetOutputStream, or anything else you write to. Three constructors can be used to chain aPrintStreamto an underlying stream:

public PrintStream(OutputStream out)
public PrintStream(OutputStream out, boolean autoFlush)
public PrintStream(OutputStream out, boolean autoFlush, String encoding)
throws UnsupportedEncodingException

Java Print Streams - Print Versus Write

:

The reason you might choose a PrintStream instead of a raw OutputStream is for its print()andprintln()methods. These methods each convert their argument to aStringand then convert theStringto bytes in a specific encoding before writing it to the underlying output stream. For example, consider thisPrintStreamconnected to a file named numbers.dat:

PrintStream out = new PrintStream(new FileOutputStream("numbers.dat"));

Suppose we use a simple for loop to write the numbers from 0 to 127 in that file:

for (int i = 0; i <= 127; i++) out.write(i);

When we’re done, the file contains 128 bytes: the first byte is 0, the second is 1, the third is 2, and so on. It’s pure binary data. If you try to open it up in a texteditor. you’ll see goop, as shown in Figure 7-1. Some of those binary numbers happen to be interpretable as ASCII text, but that’s an accident. They’re really just bytes. Many of them aren’t printable.


Figure 7-1. A binary file in a text editor

Now suppose instead of using thewrite()method we use theprint()method:

for (int i = 0; i <= 127; i++) out.print(i);

This time thePrintStreamdoes not write raw binary data in the file. Instead, it converts each number into its ASCII string equivalent and writes that string. For instance, instead of writing the byte 20, it writes the character 2 followed by the character 0. If you open the file in a text editor now, you’ll see something like the screenshot shown in Figure 7-2.


Figure 7-2. A text file in a text editor

It’s not absolutely guaranteed that the string will be written in ASCII. On a few IBM mainframes, EBCDIC might be used instead. However, given the range of characters used here, it’s pretty likely that the resulting file will make sense when interpreted as ASCII. More on this point shortly.

Theprintln()method prints a platform-specific line terminator after printing its argument. Suppose instead of using theprint()method we use theprintln()method:

for (int i = 0; i <= 127; i++) out.println(i);

Then the output is even neater, as shown in Figure 7-3.

These examples used ints, but thePrintStream class hasprint()andprintln( )methods for every Java data type. The method signatures are:

public void print(boolean b)
public void print(char c)
public void print(int i)
public void print(long l)
public void print(float f)
public void print(double d)
public void print(char[] s)
public void print(String s)
public void print(Object o)
public void println(boolean b)
public void println(char c)
public void println(int i)
public void println(long l)
public void println(float f)
public void println(double d)
public void println(char[] s)
public void println(String s)
public void println(Object o)

You can pass anything at all to aprint()method. Whatever argument you supply is guaranteed to match at least one of these methods. Object types are converted to


Figure 7-3. A text file with line breaks

strings by invoking theirtoString()methods. Primitive types are converted with the appropriateString.valueOf()methods.

One aspect of makingSystem.outsimple for quick jobs is not in thePrintStream class at all, but in the compiler. Because Java overloads the+operator to signify concatenation of strings, primitive data types, and objects, you can pass multiple variables to theprint()andprintln()methods, which are then converted to strings and concatenated. For example, consider the line:

System.out.println("As of " + (new Date()) + " there have been over "
+ hits + " hits on the web site." );

The compiler rewrites this complicated expression as:

StringBuffer sb = new StringBuffer();
sb.append("As of ");
Date d = new Date();
sb.append(d);
sb.append(" there have been over ");
sb.append(hits);
sb.append(" hits on the web site.")
String s = sb.toString();
System.out.println(s);

TheStringBuffer append()method is overloaded in much the same way that theprint()andprintln()methods are; as a result, it can handle any Java data type.

Java Print Streams - Line Breaks

:

As previously mentioned, the println() method always adds a line break at the end of each line it prints. You can even call println() with no arguments to print just a line break:

public void println()

The line break character varies from platform to platform. In particular:

On Unix (including Mac OS X), it’s a linefeed,\n, ASCII 10.
On Mac OS 9, it’s a carriage return,\r, ASCII 13.
On Windows, it’s a carriage return linefeed pair,\r\n, ASCII 13 followed by ASCII 10.
This is almost never what you actually want!

Most file formats and most network protocols care a great deal about which line break character is written.* For instance, if you’re writing a web client or server, the HTTP specification requires that header lines end with carriage return linefeed pairs. It doesn’t matter whether the client or server is a Mac, a PC, a Unix workstation, or a Palm Pilot. It must use\r\nas the line break. You can specify this by explicitly passing the line break you want to theprint()method rather than callingprintln(). For example:

for (int i = 0; i <= 127; i++) {
out.print(i);
out.print("\r\n");
}

In practice, most HTTP servers and clients accept requests that use the wrong line breaks. However, some aren’t so forgiving, and you really shouldn’t count on this behavior.

If for some reason you want to know which line break character will be used, theline.separatorsystem property will tell you:

String lineBreak = System.getProperty("line.separator");

Not all line breaks are created equal. If thePrintStream is set toautoFlush—that is, if the second argument to the constructor istrue—after every call toprintln()and after every linefeed that’s printed, the underlying stream will be flushed. Thus,out.println()andout.print("\n")both flush the stream. So doesout.print("\r\n"), because it contains a linefeed. However,out.print("\r")does not cause an automatic flush.


Java Print Streams - Error Handling

:

You may have noticed something a little funny with the code fragments in this chapter: I haven’t put any try-catch blocks around them. That’s not an oversight. PrintStream methods never throw IOExceptions. Each method in the class catchesIOException. When an exception occurs, an internal flag is set totrue. You can test this flag using thecheckError()method:

public boolean checkError()

This method returnstrueif this print stream has ever encountered an error during its lifetime. Most of the time, you just ignore this, since print streams are only used in situations where exhaustive error checking is unnecessary.

There’s also a protectedsetError()method you can use to signal an error from a subclass:

protected void setError()

Once an error has been set, there’s no way to unset it. Generally, once aPrintStreamhas encountered an error, all further writes to it silently fail. It’s not the failure but the silence that makesPrintStream unsuitable for most applications.

printf()
I was inspired to write the first edition of this book by the numerous questions I received about why there was no printf() function in Java. Part of the goal of that edition was to explain to readers why they didn’t actually need it. Thus, I was a little perturbed when Java 5 added printf(). Personally, I still don’t think Java needs printf(), but it’s here now, so let’s talk about it.

Theprintf()method makes heavy use of Java 5’s new varargs feature. That is, a single method definition can support any number of arguments. In this case, the signature is:

public PrintStream printf(String format, Object... args)

A typical invocation looks like this:

System.out.printf("There are %f centimeters in %f inches.", 2.54*inches, inches);

If you’re an old C hack, this is like coming home. The first argument is a format string containing both literal text and tags beginning with percent signs (%). To form the output, each tag is replaced by the corresponding argument that follows the format string. If the format string is the zeroth argument, the first tag is replaced by the first argument, the second tag by the second argument, and so forth. If there are more tags than arguments,printf()throws ajava.util.MissingFormatArgumentException. This is a subclass ofIllegalFormatException, which is a runtime exception, so you don’t have to catch it. If there are more arguments than tags, the extra arguments are silently ignored.

Printf()

The letter(s) after the percent sign in the format tag specify how the number is interpreted. For instance,%fmeans that the number is formatted as a floating-point number with a decimal sign.%dformats the argument as a decimal integer.%xformats the number as a hexadecimal integer.%Xalso formats the number as a hexadecimal integer but uses the uppercase letters A–F instead of the lowercase letters a–f to represent 10–15.

Most of the time, changing a lowercase conversion specifier to uppercase changes the formatted string from lowercase to uppercase. However, there are a few exceptions to this rule.

There are a couple of dozen tags for different kinds of data. Not all data is compatible. For instance, if you use%xto format adouble as a hexadecimal integer,printf()throws ajava.util.IllegalFormatConversionException. Again, this is a runtime exception and a subclass ofIllegalFormatException.

So far, this isn’t anything that can’t be done easily withprintln()and string concatenation. What makesprintf()more convenient for some uses is that the tags can also contain width and precision specifiers. For example, suppose we wrote the previous statement like this instead:

System.out.printf("There are %.3f centimeters in %.2f feet.", 2.54*feet, feet);

%.3fmeans that the centimeters will be formatted as a decimal number with exactly three digits after the decimal point.%.2fmeans that the number will be rounded to only two decimal places. This gives more legible output, like “There are 21.691 centimeters in 8.54 feet” instead of “There are 21.690925 centimeters in 8.539734 feet.”

A number before the decimal point in the format tag specifies the minimum width of the formatted string. For instance,%7.3fformats a decimal number exactly seven characters wide with exactly three digits after the decimal point. Those seven characters include the decimal point, so there will be exactly three digits to the left of the decimal point. If the number is smaller than 100, it will be padded on the left with spaces to make seven characters. Zeros will be added to the right of the decimal point if necessary to pad it to three decimal places.

Consider this Java 1.4 code fragment that prints a three-column table of the angles between 0 and 360 degrees in degrees, radians, and grads, using onlyprintln():

for (double degrees = 0.0; degrees <>
double radians = Math.PI * degrees / 180.0;
double grads = 400 * degrees / 360;
System.out.println(degrees + " " + radians + " " + grads);
}

Its output looks like this (not very pretty):

0.0 0.0 0.0
1.0 0.017453292519943295 1.1111111111111112
2.0 0.03490658503988659 2.2222222222222223
3.0 0.05235987755982988 3.3333333333333335
...

In Java 5,printf()can easily format each number exactly five characters wide with one digit after the decimal point:

for (double degrees = 0.0; degrees <>
double radians = Math.PI * degrees / 180.0;
double grads = 400 * degrees / 360;
System.out.printf("%5.1f %5.1f %5.1f\n", degrees , radians, grads);
}

Here’s the start of the output:

0.0 0.0 0.0
1.0 0.0 1.1
2.0 0.0 2.2
3.0 0.1 3.3
...

Notice how nicely everything lines up in a monospaced font? This is incredibly useful for the two dozen programmers using Java to generate reports for VT-100 terminals and letter-quality printouts on green-and-white barred computer paper. (Those readers who haven’t written any software like that since 1984, and certainly those readers who weren’t even born in 1984, should now see why I’m less than thrilled with the addition of this 1970s technology to a 21st-century language.)

Of course, programmers printing text in proportional-width fonts, GUI table components, HTML reports, XML documents styled with XSL stylesheets, and any other output format produced since 1992 may be less enamored of this style of programming. Anyway, Java has it now. You don’t have to use it (or read the rest of this chapter) if you don’t need it.


Java Print Streams - Formatter

:
In fact, printf() is a little more general than System.out (though that’s its primary justification). Besides printf(), the PrintStreamclass also has aformat()method:

public PrintStream format(String format, Object... args)

This does exactly the same thing asprintf(). That is, the previous example could be rewritten like this and produce identical output:

for (double degrees = 0.0; degrees <>
double radians = Math.PI * degrees / 180.0;
double grads = 400 * degrees / 360;
System.out.format("%5.1f %5.1f %5.1f\n", degrees , radians, grads);
}

Why two methods, then? Theformat()method is used not just byPrintStreambut also by thejava.util.Formatterclass:

public class Formatter implements Flushable, Closeable

printf()is there solely to make C programmers feel nostalgic.

Formatteris the object-oriented equivalent ofsprintf()andfprintf()in C. Rather than writing its output onto the console, it writes it into a string, a file, or an output stream. Pass the object you want to write into to theFormatterconstructor. For example, this code fragment creates aFormatterthat writes data into a file named angles.txt:

Formatter formatter = new Formatter("angles.txt");

Once you’ve created aFormatterobject, you can write to it using theformat()method just as you would withSystem.out.format(), except that the output goes into the file rather than onto the console:

for (double degrees = 0.0; degrees <>
double radians = Math.PI * degrees / 180.0;
double grads = 400 * degrees / 360;
formatter.format("%5.1f %5.1f %5.1f\n", degrees , radians, grads);
}

Formatters are not output streams, but they can and should be flushed and closed just the same:

formatter.flush();
formatter.close();

Friday, October 8, 2010

Code Examples Code

I want to show you one funny thing!

The code is shown below is simplest that you can imagine and does very unusual thing!
It is slightly bigger than "Hello World!" program but does much more.
It lists all files in the current directory if you run it like this:
java test *
(of course after compilation) in DOS/CMD prompt on Windows or in any shell in UNIX.
The program shows all files both in Unix and Windows.
If you do: java test .*
on UNIX it also shows all hidden files.

class test{
public static void main(String args[]){
for (int i = 0;i <>
System.out.println("File " + i + ":" + args[i]);
}
if (args.length<=0) {
System.out.println("No files!");
}
}
}

What is a Programming Language?

What Does A Programming Language Do?:

A programming language is used to write computer programs such as

Applications
Utilities
Servers
Systems Programs

A program is written as a series of human understandable computer instructions that can be read by a compiler and linker, and translated into machine code so that a computer can understand and run it.


Are There Many Programs In A Computer?:

From the moment you turn on your computer, it is running programs, carrying out instructions, testing your ram, resetting all attached devices and loading the operating system from hard disk or CD-Rom.

Each and every operation that your computer performs has instructions that someone had to write in a programming language. These had to be created, compiled and tested- a long and complex task.

An operating system like Microsoft's Windows Vista took millions of man hours to write and test the software.



Examples Of Programming Languages:

These languages include Assembler, C or C++. A computer motherboard with the CPU, RAM and ROM), the instructions to boot the computer are limited to a small amount of memory in the boot ROM chip and so are usually written in assembler. Operating systems like Linux or Windows are written in C and C++.

Traditional Programming Languages:

In the late 40s and early 50s, computer programs were entered by flicking switches. It was quickly realised how inefficient and slow that was and computer languages soon appeared.

Thousands of programming languages have been invented since then, many as PhD research projects, but only a few have been really successful. Through the 60s and 70s, these languages :

Fortran
Cobol
Basic
all ruled the roost but declined when better languages came into being. Basic hung in there the longest but is now declining.



What Programming Languages Are Now In Use?:

It is mainly Java and C++ with C# starting to gain popularity and C holding its own. There have been many attempts to automate this process, and have computers write computer programs but the complexity is such that for now, humans still write the best computer programs.


The Future Of Programming Languages:

The most popular programming languages are currently :

C
C++
Java
As computers get faster, have more RAM, applications will get more complex, it is likely that more development will shift from C++ to the higher level languages such as Java and C#.
Microsoft have put a lot of faith in C# as their answer to Java and have the financial leverage to continue plugging it for a very long time. I expect both Java and C# to become the two dominant programming languages.

Monday, October 4, 2010

Java Interview Question


1. What is the difference between private, protected, and public?

These keywords are for allowing privileges to components such as java methods and variables.
Public: accessible to all classes
Private: accessible only to the class to which they belong
Protected: accessible to the class to which they belong and any subclasses.
Access specifiers are keywords that determines the type of access to the member of a class. These are:
* Public
* Protected
* Private
* Defaults

2. What's the difference between an interface and an abstract class? Also discuss the similarities. (Very Important)

Abstract class is a class which contain one or more abstract methods, which has to be implemented by sub classes. Interface is a Java Object containing method declaration and doesn't contain implementation. The classes which have implementing the Interfaces must provide the method definition for all the methods
Abstract class is a Class prefix with a abstract keyword followed by Class definition. Interface is a Interface which starts with interface keyword.
Abstract class contains one or more abstract methods. where as Interface contains all abstract methods and final declarations
Abstract classes are useful in a situation that Some general methods should be implemented and specialization behavior should be implemented by child classes. Interfaces are useful in a situation that all properties should be implemented.

Differences are as follows:

* Interfaces provide a form of multiple inheritance. A class can extend only one other class.
* Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc.
* A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class.
* Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast.

Similarities:

* Neither Abstract classes or Interface can be instantiated.

How to define an Abstract class?
A class containing abstract method is called Abstract class. An Abstract class can't be instantiated.
Example of Abstract class:

abstract class testAbstractClass {
protected String myString;
public String getMyString() {
return myString;
}
public abstract string anyAbstractFunction();
}

How to define an Interface?
Answer: In Java Interface defines the methods but does not implement them. Interface can include constants. A class that implements the interfaces is bound to implement all the methods defined in Interface.
Example of Interface:

public interface sampleInterface {
public void functionOne();
public long CONSTANT_ONE = 1000;
}

3. Question: How you can force the garbage collection?

Garbage collection automatic process and can't be forced. You could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.

Garbage collection is one of the most important feature of Java, Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. User program can't directly free the object from memory, instead it is the job of the garbage collector to automatically free the objects that are no longer referenced by a program. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use. I Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected.

4. What's the difference between constructors and normal methods?

Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times and it can return a value or can be void.

5. Can you call one constructor from another if a class has multiple constructors

Yes. Use this() to call a constructor from an other constructor.

6. Explain the usage of Java packages.

This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes.

7. Explain in your own words the "bottom line" benefits of the use of an interface.

The interface makes it possible for a method in one class to invoke methods on objects of other classes, without the requirement to know the true class of those objects, provided that those objects are all instantiated from classes that implement one or more specified interfaces. In other words, objects of classes that implement specified interfaces can be passed into methods of other objects as the generic type Object, and the methods of the other objects can invoke methods on the incoming objects by first casting them as the interface type.

8. What are some advantages and disadvantages of Java Sockets?

Some advantages of Java Sockets:
Sockets are flexible and sufficient. Efficient socket based programming can be easily implemented for general communications. Sockets cause low network traffic. Unlike HTML forms and CGI scripts that generate and transfer whole web pages for each new request, Java applets can send only necessary updated information.

Some disadvantages of Java Sockets:
Security restrictions are sometimes overbearing because a Java applet running in a Web browser is only able to establish connections to the machine where it came from, and to nowhere else on the network Despite all of the useful and helpful Java features, Socket based communications allows only to send packets of raw data between applications. Both the client-side and server-side have to provide mechanisms to make the data useful in any way.

9. Explain the usage of the keyword transient?

Transient keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).

10. What's the difference between the methods sleep() and wait()

The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.

11. What would you use to compare two String variables - the operator == or the method equals()?

I'd use the method equals() to compare the values of the Strings and the == to check if two variables point at the same instance of a String object.

12. Why would you use a synchronized block vs. synchronized method?

Synchronized blocks place locks for shorter periods than synchronized methods.

13. What access level do you need to specify in the class declaration to ensure that only classes from the same directory can access it?

You do not need to specify any access level, and Java will use a default package access level.

14. Can an inner class declared inside of a method access local variables of this method?

It's possible if these variables are final.

15. What can go wrong if you replace && with & in the following code:
String a=null; if (a!=null && a.length()>10) {...}

A single ampersand here would lead to a NullPointerException.

16. What's the main difference between a Vector and an ArrayList?

Java Vector class is internally synchronized and ArrayList is not synchronized.

17. Describe the wrapper classes in Java.

Wrapper class is wrapper around a primitive data type. An instance of a wrapper class contains, or wraps, a primitive value of the corresponding type.

Following table lists the primitive types and the corresponding wrapper classes:
Primitive Wrapper
boolean - java.lang.Boolean
byte - java.lang.Byte
char - java.lang.Character
double - java.lang.Double
float - java.lang.Float
int - java.lang.Integer
long - java.lang.Long
short - java.lang.Short
void - java.lang.Void

18. How could Java classes direct program messages to the system console, but error messages, say to a file?

The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:
Stream st = new Stream(new FileOutputStream("output.txt")); System.setErr(st); System.setOut(st);

19. How do you know if an explicit object casting is needed?

If you assign a superclass object to a variable of a subclass's data type, you need to do explicit casting. For example:
Object a; Customer b; b = (Customer) a;

20. When you assign a subclass to a variable having a supeclass type, the casting is performed automatically. Can you write a Java class that could be used both as an applet as well as an application?

Yes. Add a main() method to the applet.

21. If a class is located in a package, what do you need to change in the OS environment to be able to use it?

You need to add a directory or a jar file that contains the package directories to the CLASSPATH environment variable. Let's say a class Employee belongs to a package com.xyz.hr; and is located in the file c:\dev\com\xyz\hr\Employee.javIn this case, you'd need to add c:\dev to the variable CLASSPATH. If this class contains the method main(), you could test it from a command prompt window as follows:
c:\>java com.xyz.hr.Employee

22. What's the difference between J2SDK 1.5 and J2SDK 5.0?

There's no difference, Sun Microsystems just re-branded this version.

23. Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?

Yes, it does. The FileNoFoundException is inherited from the IOException. Exception's subclasses have to be caught first.

24. Name the containers which uses Border Layout as their default layout?

Containers which uses Border Layout as their default are: window, Frame and Dialog classes.

25. You are planning to do an indexed search in a list of objects. Which of the two Java collections should you use:
ArrayList or LinkedList?

ArrayList

26. When should the method invokeLater()be used?

This method is used to ensure that Swing components are updated through the event-dispatching thread.

27. How can a subclass call a method or a constructor defined in a superclass?

Use the following syntax: super.myMethod(); To call a constructor of the superclass, just write super(); in the first line of the subclass's constructor.

28. What do you understand by Synchronization?

Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption.
E.g. Synchronizing a function:
public synchronized void Method1 () {
// Appropriate method-related code.
}
E.g. Synchronizing a block of code inside a function:
public myFunction (){
synchronized (this) {
// Synchronized code here.
}
}

29. What's the difference between a queue and a stack?

Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule

30. You can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. So can you use abstract classes instead of interfaces?

Sometimes. But your class may be a descendent of another class and in this case the interface is your only option.

31. If you're overriding the method equals() of an object, which other method you might also consider?

hashCode()

32. What is Collection API?

The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.

33. How would you make a copy of an entire Java object with its state?

Have this class implement Cloneable interface and call its method clone().

34. How can you minimize the need of garbage collection and make the memory use more effective?

Use object pooling and weak object references.

35. There are two classes: A and B. The class B need to inform a class A when some important event has happened. What Java technique would you use to implement it?

If these classes are threads I'd consider notify() or notifyAll(). For regular classes you can use the Observer interface.

36. Explain the Encapsulation principle.

Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper.

37. Explain the Inheritance principle.

Inheritance is the process by which one object acquires the properties of another object.

38. Explain the Polymorphism principle.

The meaning of Polymorphism is something like one name many forms. Polymorphism enables one entity to be used as as general category for different types of actions. The specific action is determined by the exact nature of the situation. The concept of polymorphism can be explained as "one interface, multiple methods".
From a practical programming viewpoint, polymorphism exists in three distinct forms in Java:

* Method overloading
* Method overriding through inheritance
* Method overriding through the Java interface

39. Is Iterator a Class or Interface? What is its use?

Iterator is an interface which is used to step through the elements of a Collection.

40. Explain the user defined Exceptions?

User defined Exceptions are the separate Exception classes defined by the user for specific purposed. An user defined can created by simply sub-classing it to the Exception class. This allows custom exceptions to be generated (using throw) and caught in the same way as normal exceptions.
Example:

class myCustomException extends Exception {
/ The class simply has to exist to be an exception
}


41. What is OOPS?

OOP is the common abbreviation for Object-Oriented Programming.
There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation.

39. Read the following program:

public class test {
public static void main(String [] args) {
int x = 3;
int y = 1;
if (x = y)
System.out.println("Not equal");
else
System.out.println("Equal");
}
}

What is the result?
The output is “Equal”
B. The output in “Not Equal”
C. An error at " if (x = y)" causes compilation to fall.
D. The program executes but no output is show on console.
Answer: C
Answer: Transient variable can't be serialize. For example if a variable is declared as transient in a Serializable class and the class is written to an ObjectStream, the value of the variable can't be written to the stream instead when the class is retrieved from the ObjectStream the value of the variable becomes null.

# Question: Name the containers which uses Border Layout as their default layout?
Answer: Containers which uses Border Layout as their default are: window, Frame and Dialog classes.

# Question: What do you understand by Synchronization?
Answer: Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption.
E.g. Synchronizing a function:
public synchronized void Method1 () {
// Appropriate method-related code.
}
E.g. Synchronizing a block of code inside a function:
public myFunction (){
synchronized (this) {
// Synchronized code here.
}
}