Skip to main content

Posts

Showing posts from September, 2010

What is the difference between an enum type and java.lang.Enum?

-- An enum type, also called enumeration type, is a type whose fields consist of a fixed set of constants. The purpose of using enum type is to enforce type safety. While java.lang.Enum is an abstract class, it is the common base class of all Java language enumeration types. The definition of Enum is: public abstract class Enum> extends Object implements Comparable, Serializable All enum types implicitly extend java.lang.Enum. The enum is a special reference type, it is not a class by itself, but more like a category of classes that extends from the same base class Enum. Any type declared by the key word "enum" is a different class. They easiest way to declare a enum type is like: public enum Season {     SPRING, SUMMER, AUTUM, WINTER }

"Enums" Concepts in Java

-- In prior releases, Java does not support the concept of user-defined enumerated types. What is an enumerated type? An enumerated type is a type whose legal values consist of a fixed set of constants. The standard way to represent an enumerated type was the int Enum pattern, for example, to define the four seasons in a year: public class SEASON { public static final int WINTER = 0; public static final int SPRING = 1; public static final int SUMMER = 2; public static final int FALL = 3; } This pattern has many problems, such as, not typesafe, no namespace, printed values are uninformative, and not convenient, etc. In 5.0, Java adds support for enumerated types. The new enum has a lot of advantages including:

Which replace function works with regex?

-- More than often we need to manipulate a string, substitute characters inside a string. In Java, the String class, there are a couple of methods that we can use to complete this task. 1. public String replace(char oldChar, char newChar)    This method "returns a new string resulting from replacing all occurrences of oldChar in this string with newChar."    Both oldChar and newChar are single char.    For example, String a = "This is a cat.";    String b = a.replace('c', 'r');    b has the value of "This is a rat.". 2. public String replace(CharSequence target, CharSequence replacement)

How to List Files and Subdirectories in a Directory?

-- Here an example uses File class to retrive all files and subdirectories under the root. public static void main(String[] argv){ File dir = new File("c:\\"); String[] children = dir.list(); if (children != null) { for (String filename: children) { out.println(filename); } } else { out.println("No File Found."); } } Here is an example showing how to return subdirectories only. From java.io.File Java API doc, a list of files can also be retrieved as array of File objects. class DirectoryFileFilter implements FileFilter { public boolean accept(File file) { return file.isDirectory(); } }

How to Use Filename Filters?

-- public interface FilenameFilter is an interface that declares single method. Instances of classes that implement this interface are used to filter filenames. These instances are used to filter directory listings in the list method of class File , and by the Abstract Window Toolkit's file dialog component. There is one and only one method in the interface, public boolean accept(File directory, String filename) . The method returns true if and only if the filename should be included in the file list; false otherwise. The FilenameFilter is an interface and you must implement this interface in your class. Here is a sample implemeting the method which returns all java files in given directory, the file filter only accepts files ending with ".java". public static String[] getFileNames(String dirName) throws IOException{ File dir = new File(dirName); FilenameFilter filter = new FilenameFilter() { public boolean

How to Access System Properties in Java?

-- This code example shows how to list all system properties, get/set the value of a system property: import java.util.Enumeration; import java.util.Properties; public class ListingAllSystemProperties { public static void main(String[] args) { //List All System Properties Properties props = System.getProperties(); Enumeration enumeration = props.keys(); while (enumeration.hasMoreElements()) { String propName = (String) enumeration.nextElement(); String propValue = (String)props.get(propName); System.out.println(propName + " = " + propValue); }

WebSphere MQ Script Commands

-- SCRIPT COMMANDS:- After entering in to queue manager we can find script commands. Script commands are same for every queue manager. (These Commands should be used in CAPITAL LETTERS) · DEFINE :-To define/create MQ manager objects like queue, Channels, process, and listener. · ALTER :-to update or modify the existing objects · DISPLAY :-to view all the properties of a particular object or to Display all objects · DELETE :-to delete created objects · CLEAR :-to clear the message from the queue · END :-to come out of the queue manager · PING :-to check whether other side channel / queue manager is ready to accept our request. · START :- to start the particular channel or listener · STOP :-to stop particular channel or listener · REFRESH :-used to refresh the security every time after giving or executing, set mgr or command for queue manager or object · RESET :-used to reset channel,cluster,queue manager · RESOLVE :-to resolve the channel w

WebSphere MQ Series Interview Questions - 1

-- How does MQ support the Integration? Ans. Because the MQ is independent of the Operating System you use i.e. it may be Windows, Solaris,AIX.It is independent of the protocol (i.e. TCP/IP, LU6.2, SNA, NetBIOS, UDP).It is not required that both the sender and receiver should be running on the same platform What is Asynchrony? Ans. With message queuing, the exchange of messages between the sending and receiving programs is independent of time. This means that the sending and receiving application programs are decoupled; the sender can continue processing without having to wait for the receiver to acknowledge receipt of the message. The target application does not even have to be running when the message is sent. It can retrieve the message after it is has been started. What is a Message and what does it contain? Ans: A message is a string of bytes that is meaningful to the applications that use it. Messages are used to transfer information from one application program to

How to Convert an ArrayList to a HashSet?

-- This code example shows how to convert ArrayList to HashSet: import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class ArrayListToHashSet { public static void main(String[] args) { List list = new ArrayList (); list.add(null); list.add("A"); list.add("B"); Set hashset = new HashSet (list); list = new ArrayList (hashset); System.out.println(list.toString()); } }

How to Convert a HashSet to an ArrayList?

-- This code example shows how to convert HashSet to ArrayList: import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class HashSetToArrayList { public static void main(String[] args) { Set hashset = new HashSet (); hashset.add("A"); hashset.add("B"); hashset.add("C"); List list = new ArrayList (hashset); System.out.println(list.toString()); } }

What is the effect of using Persistant messages?

-- Ans: Persistent messages are usually logged. Logging messages reduces the performance of your application, so use persistent messages for essential data only. If the data in a message can be discarded if the queue manager stops or fails, use a nonpersistent message. WebSphere MQ messages: Messages are made up of Two parts: Message descriptor, Application data Types of messages Datagram : A Message sent with no response expected. Request : A Message sent for which a response is expected. Reply : A Response Message for a requested message. Report : A Message that describes the occurrence or event Ex COA/COD Sizes ? Qmanagerà10000 Msgs Maxmsglengthà4 Mb Queueà5000 Msgs Maxmsglengthà4 Mb  

What is Message driven process?

-- Ans . When messages arrive on a queue, they can automatically start an application using triggering. If necessary, the applications can be stopped when the message (or messages) have been processed. What are advantages of the MQ? Ans. 1. Integration. 2. Asynchrony 3. Assured Delivery 4. Scalability.

What are the hardware and Software requirements for MQ Installation in AIX?

-- Ans. WebSphere MQ for AIX, V5.3 runs on any machine that supports the AIX V4.3.3 PowerPC® 32.bit, or AIX® V5.1 Power 32 bit only operating system. Disk Storage: Typical storage requirements are as follows: 1 Server installation: 50 MB 2. Client installation: 15 MB 3 Data storage (server): 50 MB 4. Data storage (client): 5 MB. Software Requirements: Operating system: The operating systems supported by WebSphere MQ for AIX, V5.3 are: 1. AIX V4.3.3, with PTF U472177, running in a 32 bit environment, on 32 or 64 bit hardware. 2. AIX V5.1, with PTFs U476879, U477366, U477367 and U477368, and APAR fix IY29345 running 32 bit kernel running on 32 or 64 bit hardware. 3. AIX V5.1, with PTF U476879, U477366, U477367 and U477368, and APAR fix IY29345 running 64 bit kernel running on 64 bit hardware. Connectivity The network protocols supported by WebSphere MQ for AIX, V5.3 are: 1. TCP/IP 2. SNA LU 6.2. Databases: DB2 7.1, 7.2 Oracle 8i and 9i Sybase v12 or v 12

How to Use Updatable ResultSet in JDBC?

-- A default ResultSet object is not updatable and has a cursor that moves forward only. Thus, you can iterate through it only once and only from the first row to the last row. It is possible to produce ResultSet objects that are scrollable and/or updatable. An updatable result set allows modification to data in a table through the result set. The following code makes a result set that is scrollable and insensitive to updates by others: try { // Create a statement that will return updatable result sets Statement stmt = connection.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); //Primary key EmployeeID must be specified //so that the result set is updatable ResultSet resultSet = stmt.executeQuery( "SELECT EmployeeID, Name, Office FROM employees"); } catch (SQLException e) { } The updatable result se

How to Use ParameterMetaData to Learn Parameter Information?

-- In the following example, it shows various methods of the ParameterMetaData object are used to display information about the type and mode of the parameters that are contained within a stored procedure. import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ParameterMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.sql.Types; public class JDBCPrepareMetaData { private static final String DBURL = "jdbc:mysql://localhost:3306/mydb?user=usr&password=sql" +"&useUnicode=true&characterEncoding=UTF-8"; private static final String DBDRIVER = "org.gjt.mm.mysql.Driver"; static { try { Class.forName(DBDRIVER).newInstance(); } catch (Exception e){ e.p

How to Use ResultSetMetaData to Learn ResultSet Information?

-- To query an unknown result set for information about the columns that it contains, you need to use ResultSetMetaData methods to determine the characteristics of the ResultSets before you can retrieve data from them. ResultSetMetaData methods provide the following types of information: getColumnCount() method returns the number of columns in the ResultSet getTableName() method returns the qualifier for the underlying table of the ResultSet getSchemaName() method returns the the designated column's table's schema name Information about a column, getColumnName() returns column name, getColumnTypeName() method returns the data type, getColumnDisplaySize() method returns column display length, getPrecision() method returns the column precision, and getScale() method returns scale. Whether a column is read-only, nullability, automatically numbered, and so on.

How to Use DatabaseMetaData to Learn Database Information?

Whorush: 2 sites by this AdSense ID   -- In the following example, getMetaData method of the Connection class is used to return a DatabaseMetadata object, and then various methods of the DatabaseMetaData object are used to display information about the driver, driver version, database name, and database version: import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Types; public class JDBCDatabaseMetaData { private static final String DBURL = "jdbc:mysql://localhost:3306/mydb?user=usr&password=sql" + "&useUnicode=true&characterEncoding=UTF-8"; private static final String DBDRIVER = "org.gjt.mm.mysql.Driver";

How to Use Methods getResultSet or getUpdateCount to Retrieve the Results?

Whorush: 2 sites by this AdSense ID   -- When you use execute method of Statement to execute a given SQL statement, it might return multiple result sets and output parameters. In some (uncommon) situations, a single SQL statement may return multiple result sets and/or update counts. Normally you can ignore this unless you are executing a stored procedure that you know may return multiple results. dynamically executing an unknown SQL string. The execute method excutes an SQL statement and returns a boolean value. When the value is true, the first result returned from the statements is a result set. When the value is false, the first result returned was an update count. You must then use the methods getResultSet or getUpdateCount to retrieve the result, and getMoreResults to move to any subsequent result(s). When the result of a SQL statement is not a result set, the method getResultSet will return null . This can mean th

How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?

-- A stored procedure can process related data and return multiple result sets, this way may save fewer calls to database server. You need to include code to retrieve the result sets, Java JDBC Statement provide the getResultSet method to retrieve each result set. You can access the first result set by calling the getResultSet method on your Statement object. In a loop, position the cursor using the next method, and retrieve data from each column of the current row of the ResultSet object using getXXX methods. To determine if more result sets are available, you can call the getMoreResults method in Statement , which returns a boolean value of true if more result sets are available. If more result sets are available, you can call the getResultSet method again to access them, continuing the process until all result sets have been processed. If the getMoreResults method returns false , there are no more result sets to

How to Use JDBC Java to Dynamically Create a Stored Procedure?

-- This example demonstrates how to create a stored procedure in JDBC in MySQL database. Assume that we have a table created by the following schema script: CREATE TABLE `mydb`.`employees` ( `EmployeeID` int(10) unsigned NOT NULL default '0', `Name` varchar(45) collate utf8_unicode_ci NOT NULL default '', `Office` varchar(10) collate utf8_unicode_ci NOT NULL default '', `CreateTime` timestamp NOT NULL default CURRENT_TIMESTAMP, PRIMARY KEY (`EmployeeID`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; We are going to dynamically add one stored procedure to mydb database import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class JDBCCreateTable { private static final String DBURL = "jdbc:mysql://localhost:3306/mydb?user=usr&password=sql&" + "useUnicode=true&characterEncoding=UTF-8";

How to Use JDBC Java to Create Table?

-- This example demonstrates how to create a table in JDBC in MySQL database. import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class JDBCCreateTable { private static final String DBURL = "jdbc:mysql://localhost:3306/mydb?user=usr&password=sql&" + "useUnicode=true&characterEncoding=UTF-8"; private static final String DBDRIVER = "org.gjt.mm.mysql.Driver"; static { try { Class.forName(DBDRIVER).newInstance(); } catch (Exception e){ e.printStackTrace(); } } private static Connection getConnection() { Connection connection = null; try { connection = DriverManager.getConnection(DBURL); } catch (Exception e) { e.printStackTrace(); } return connection; }

How to Call a Stored Procedure by JDBC Java Class?

-- A Stored procedure can return result sets, you can use getResultSet method in the CallableStatement class to retrieve return result sets. When a procedure has return value for an OUT parameter, you must tell the JDBC driver what SQL type the value will be, with the registerOutParameter method. To call stored procedures, you invoke methods in the CallableStatement class. The basic steps are: Creating a CallableStatement object by calling the Connection.prepareCall method. Using the CallableStatement.setXXX methods to pass values to the input (IN) parameters. Using the CallableStatement.registerOutParameter method to indicate which parameters are output-only (OUT) parameters, or input and output (INOUT) parameters. Invoke one of the following methods to call the stored procedure: CallableStatement.executeUpdate method, if the stored procedure does not return result sets.

How To Use JDBC Statement Objecct?

-- Once a connection to a particular database is established, that Connection object can be used to send SQL statements. The Java JDBC's Statement objects are JDBC's way of executing SQL statements to the database.A Statement object is used to send SQL statements to a database. There are three main types of Statement objects: the base class Statement , the PreparedStatement , and the CallableStatement . These objects are instantiated from your JDBC Connection object. Statement: Execute simple sql statement without parameters. For example, to creates an SQL Statement object with DBConnection object which is a database Connection object. .... Statement s = DBConnection.createStatement(); //Creates an SQL Statement object .... PreparedStatement: Execute a pre-compiled SQL statement with or without IN parameters. It is useful because it avoids manual conversion of Java types to SQL types. PreparedStatement objects

How To Enable JDBC Tracing?

-- A good way to find out what JDBC calls are doing is to enable JDBC tracing. The JDBC trace contains a detailed listing of the activity occurring in the system that is related to JDBC operations. If you use the DriverManager facility to establish your database connection, you use the DriverManager.setLogWriter method to enable tracing of JDBC operations. import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class Program { public static void main(String... args) { Connection con = null; try { Class.forName("org.gjt.mm.mysql.Driver").newInstance(); DriverManager.setLogWriter(new PrintWriter(System.out)); } catch(Exception e) { System.out.println("Exception: " + e.getMessage()); return ; }

How to Connect to a Database Using JDBC?

-- You must build a connection before accessing a database. In order to connect to a database, your specified JDBC driver class must be loaded by the JVM classloader.Your JDBC driver documentation provides the class name to use. You will have to use java.sql.DriverManager 's getConnection() method to create a database connection. This method takes an argument which identifies your database you wishing to connect to through a JDBC URL. A JDBC URL starts with "jdbc:" indicating the protocol (JDBC).The JDBC URL you use will vary with the database you use (such as MySQL, Oracle, Sybase, and so on). The following code is an example opening a MySQL database connection, import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class Program { public static void main(String... args) { Connection con = null; try { Class.forName("org.gjt.mm.mysql.Driver").newInstance(); }

How to Append Data to the End of Existing File in Java?

-- It's often useful to be able to append data to an existing file rather than overwriting it. The BufferedWriter writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.The FileWriter is a convenience class used for writing character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. Also, the FileWriter supports to append data to existing file. For example, class FileAppending { public static void main(String args[]) { try{ FileWriter fstream = new FileWriter("x.txt",true); BufferedWriter fbw = new BufferedWriter(fstream); fbw.write("append txt..."); fbw.newLine(); fbw.close(); }catch (Exception e) { System.out.println("Error: " + e.getMessage())

How to Use Reflection to Get Information about a Class in Java?

-- Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. The class java.lang.Class and the package java.lang.reflect (classes Array, Constructor, Field, Method, Modifier) implement Java's reflection. The methods of java.lang.Class are used to get information about a class. The methods of the classes in java.lang.reflect provide further information about a class and allow methods to be invoked. The following example shows how to get information about java.lang.String a class: public class Program { public static void main(String[] args) { try { Class clz = Class.forName("java.lang.String"); Field[] flds = clz.getDeclaredFields(); System.out.println("\nVariables..."); for ( int k = 0; k < flds.length; k++ ) { String name = flds[k].getName();

How to Use Reflection to Call Methods in Java?

-- You can invoke methods on objects dynamically. First, you must get their definition through one of the methods Class.getMethod(String,Class[]) or Class.getDeclaredMethod(String,Class[]) . The first parameter is the method??s name and the second is an array of Class objects representing the types of its parameters. The getMethod can handle inheritance but only picks up public methods. It returns the public method that matches the parameters provided, whether it is declared by the class or inherited. class Parent { public long l; public void setLong(long l) { this.l = l; } } public class Program extends Parent { public static void main(String[] args) { // Get the Class object associated with this class. Program program = new Program(); Class progClass = program.getClass(); try { // Get the method named sayHello. Method helloMethod = progClass.getMethod(

What is Difference between int.class and Integer.TYPE?

Class literals have been around since Java 1.1. Everyone knows you can use Integer.class to get the Class object for java.lang.Integer . Under the covers the compiler caches a results of Class.forName("java.lang.Integer") in your class. The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int . There is no different between int.class and Integer.TYPE . The Integer.TYPE and int.class point to the same class object. The Integer.TYPE is the Class instance representing the primitive type int . public class Program { public static void main(String[] args) { System.out.println(int.class == Integer.TYPE); } } The output is "true". Class literals are a way to access the instances of the class Class. A class literal is an expression consisting of the name of a class, interface, array, or primitive type followed by a `.' and the

How to Load Java Properties from the XML File?

-- The java.util.Properties class represents a persistent set of properties. The Properties can be saved to a stream or loaded from a stream. Each key and its corresponding value in the property list is a string. In Java 5.0, the java.util.Properties class allows you not only to use it to specify key-value pairs on a single line separated by an equal sign, but also to use XML files to load and save those key-value pairs. The loadFromXML(InputStream) and storeToXML(OutputStream, String, String) methods load and store properties in a simple XML format. By default the UTF-8 character encoding is used, however a specific encoding may be specified if required. An XML properties document has the following DOCTYPE declaration: Note that the system URI (http://java.sun.com/dtd/properties.dtd) is not accessed when exporting or importing properties; it merely serves as a string to uniquely identify the DTD, which is:

How Can I Catch All Possible Exceptions in Java?

-- All exceptions come from the "mother class" called java.lang.Throwable and one of two subclasses called java.lang.Error and java.lang.Exception . A block of code that is executed when an exception occurs is called an Exception handler . By catching java.lang.Throwable , it is possible to handle all unexpected conditions. ... try { } catch(Throwable e) { ... } ... There are some special exceptions that used by the JVM, those are the sub-classes of java.lang.Error . We are not suppose the catch them in our real code and we usually catch java.lang.Exception for all application and runtime exceptions. ... try { } catch(Exception e) { ... } ...

How to Read and Write UTF-8 File in Java?

-- The InputStreamReader and the OutputStreamWriter support UTF-8 character encoding. Here is example code: public class Program { public static void main(String... args) { if (args.length != 2) { return ; } try { Reader reader = new InputStreamReader( new FileInputStream(args[0]),"UTF-8"); BufferedReader fin = new BufferedReader(reader); Writer writer = new OutputStreamWriter( new FileOutputStream(args[1]), "UTF-8"); BufferedWriter fout = new BufferedWriter(writer); String s; while ((s=fin.readLine())!=null) { fout.write(s); fout.newLine(); }

Why final variable in Enhanced for Loop does not act final?

--   public class EnhancedForTest { public static void main(String... args) { String[] strArr = {"A", "B", "C", "D"}; for (final String s : strArr) { System.out.println(s); } } } Since the String s is delcared as final, this code should not compile. However, this is working fine. Why? The enhanced for-loop as shown above is actually just as the following code: public class EnhancedForTest { public static void main(String... args) { String[] strArr = {"A", "B", "C", "D"}; for (int index = 0; index < strArr.length; index++) { final String s = strArr[index]; System.out.println(s); } } }

What Are Restrictions for Enchanced For Loop?

-- You can not use "Enhanced For Loop" to remove elements from a collect or an array. Also, you can not modify the current slot in a collect or an array. It is not usable for loops where you need to replace elements in a list or array as you traverse it. For example, class Program { public static void main(String[] args) { Collection c = new ArrayList (); c.add("A"); c.add("B"); c.add("C"); for(String name : c) { name = "CHANGED"; } for(String name : c){ System.out.print(name); } } } You will see that the ouput still "ABC". All you have done is modified the local reference variable name.

How to use Enhanced for Loop?

-- Using the following link to learn what the Enhanced for Loop is( The For-Each Loop ). The following code is an interesting example of using Enhanced for Loop. The enhanced for loop will go through the array arr and set i to each member of the "int" array. class Program { public static void main(String[] args) { int []arr = {1,2,3,4}; for ( int i : arr ) { arr[i] = 0; } for ( int i : arr ){ System.out.println(i); } } }

How to implement callback functions in Java?

-- The callback function is excutable code that is called through a function pointer. You pass a callback function pointer as an argument to other code, or register callback function pointer in somewhere. When something happens, the callback function is invoked. C/C++ allow function pointers as arguments to other functions but there are no pointers in Java. In Java, only objects and primitive data types can be passed to methods of a class. Java's support of interfaces provides a mechanism by which we can get the equivalent of callbacks. You should declare an interface which declares the function you want to pass. The collections.sort(List list, Comparator c) is an example of implementing callback function in Java. The c is an instance of a class which implements compare(e1, e2) method in the Comparator interface. It sorts the specified list according to the order induced by the specified comparator. All elements in the list must be mutually comparable using

How to Use Reflection to Access Fields with Enum Types of a Class in Java?

-- Java Reflection provides three enum-specific APIs: Class.isEnum() : Indicates whether this class represents an enum type Class.getEnumConstants() : Retrieves the list of enum constants defined by the enum in the order they're declared. java.lang.reflect.Field.isEnumConstant() : Indicates whether this field represents an element of an enumerated type The following example shows how to get and set fields with Java Enum Types: package com.abcd; import java.lang.reflect.Field; import java.util.Arrays; import static java.lang.System.out;

How to Use Collator and CollationKey to Do a Locale-Specific Sorting?

-- Collator Class contains methods used to sort and arrange strings of Unicode characters based on their decomposition and strength. CollationKey represents the collation order of a particular String for a specific Collator. CollationKeys can be compared to determine the relative ordering of their source Strings. This is useful when the Strings must be compared multiple times, as in sorting. The here is an example: public class Program { public static void show( String tag, Collator collator ) { TreeSet set = new TreeSet(); System.out.println( tag ); CollationKey key1 = collator.getCollationKey( "tom" ); CollationKey key2 = collator.getCollationKey( "Dick" ); CollationKey key3 = collator.getCollationKey( "Tony" ); set.add( key1 ); set.add( key2 ); set.add( key3 ); Iterator iterator =set.iterator();

How to Use StringTokenizer in Java?

-- The string tokenizer class allows an application to break a string into tokens. A token is returned by taking a substring of the string that was used to create the StringTokenizer object. There are three ways to construct a StringTokenizer. public class Program { public static void main(String[] args) { System.out.println("Case 1."); StringTokenizer st = new StringTokenizer("this is a test"); while (st.hasMoreTokens()) { System.out.println(st.nextToken()); } System.out.println("Case 2."); st = new StringTokenizer("this,is a=test", " ,="); while (st.hasMoreTokens()) { System.out.println(st.nextToken()); } System.out.println("Case 3."); st = new StringTokenizer("this,is a=test", " ,=", true); while (st.hasMoreTokens()) { System.out.println(st.nextToken()

Is SimpleDateFormat Thread-Safe Class?

-- SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. From time to time, you will use SimpleDateFormat class in your project. But Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally. Yes, it is not thread-safe object as long as your read the whole documentation of the SimpleDateFormat class Java API. The following code will throw out java.lang.NumberFormatException exception: import java.text.SimpleDateFormat; import java.util.Date; public class SimpleDateFormatExample extends Thread { private static SimpleDateFormat sdfmt = new SimpleDateFormat( "EEE MMM dd HH:mm:ss zzz yyyy"); public void run() { Date now = new Date(); String strDate = now.toString(); int m = 3; while (m--!=0) { t

How to Use SimpleDateFormat Class Formating/Parsing Date and Time?

-- SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting. DateFormat also provides many class methods for obtaining default date/time formatters based on the default or a given locale and a number of formatting styles. The SimpleDateFormat provides more flexiable custom formats for date time,  you can set your own date patterns. The following document is from Java API Document. Date and Time Patterns Date and time formats are specified by date and time pattern strings. Within date and time pattern strings, unquoted letters from 'A' to 'Z' and from 'a' to 'z' are interpreted as pattern letters representing the components of a date or time string. Text can be quoted using single quotes ( ' ) to avoid interpretation. "''"

How to Use DateFormat Class in Java?

-- DateFormat helps you to format and parse dates for any locale. DateFormat provides many class methods for obtaining default date/time formatters based on the default or a given locale and a number of formatting styles. The formatting styles include FULL, LONG, MEDIUM, and SHORT. You can pass in different formatting style to these factory methods to control the length of the result but the exact result also depends on the locale, but generally: SHORT is completely numeric, such as 12.13.52 or 3:30pm MEDIUM is longer, such as Jan 12, 1952 LONG is longer, such as January 12, 1952 or 3:30:32pm FULL is pretty completely specified, such as Tuesday, April 12, 1952 AD or 3:30:42pm PST. Use getDateInstance to get the normal date format for that country. For example, import java.text.DateFormat; import java.util.Date; public class DateFormatExample { public static void main(String[] args) { Date now = new Date();

Does the implicit narrowing conversion work with the method return statement?

-- Yes, the implicit narrowing conversion work with the method return statement. For example, class Program { byte method_1() { return 126; } byte method_2() { final int m = 127; return m; } byte method_3() { final int m=128; return m; //compile time error because m is not in the range value (-128 to 127) of byte } } 14.17 The return Statement in JLS 3.0:  A return statement with an Expression must be contained in a method declaration that is declared to return a value (8.4) or a compile-time error occurs. The Expression must denote a variable or value of some type T , or a compile-time error occurs. The type T must be assignable (5.2) to the declared result type of the method, or a compile-time error occurs. "The type T must be assignable (5.2) to the declared result type of the method, or a compile-time error occurs" indicates that the implicit narrowing of integer constan

Collection of SCJP Resources

-- SCJP Tutorial by IBM Developer Works Taming Tiger, Part 1 - An introduction to Java 1.5 Taming Tiger, Part 2 - Understanding generics Chapter 3: Enumerated Types (PDF Format) in Java 5.0 Tiger: A Developer's Notebook Chapter 5: Creating Varargs in Java 5.0 Tiger: A Developer's Notebook Chapter 8: Generics in Learning Java Chapter 6: Objects and Classes in The Complete Java 2 Certification Study Guide Cohesion in WikiPedia Coupling in WikiPedia Information hiding in WikiPedia Lesson: Object-Oriented Programming Concepts in The Java Tutorial Abstraction, Encapsulation, and Information Hiding by Edward V. Berard Encapsulation is not information hiding in JavaWorld Programming With Assertions from Sun. Using Foreach Loops in J2SE 1.5 Reference Objects and Garbage Collection The Truth About Garbage Collection Garbage Collection (Chapter 9 of Inside the Java Virtual Machine) Garbage Collection and setting to null Object finalization and cleanup Using Finall

What does Class.forname method do?

-- A call to Class.forName("X") causes the class named X to be dynamically loaded (at runtime). A call to forName("X") causes the class named X to be initialized (i.e., JVM executes all its static block after class loading). Class.forName("X") returns the Class object associated with the "X" class. The returned Class object is not an instance of the "x" class itself. Class.forName("X") loads the class if it not already loaded. The JVM keeps track of all the classes that have been previously loaded. This method uses the classloader of the class that invokes it. The "X" is the fully qualified name of the desired class. For example, package com.abcd; class AClass { static { System.out.println("static block in AClass"); } }

How to add BASIC Authentication into HttpURLConnection?

-- Here is one sample. ... try { //Create connection url = new URL(targetURL); connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("POST"); ... BASE64Encoder enc = new sun.misc.BASE64Encoder(); String userpassword = username + ":" + password; String encodedAuthorization = enc.encode( userpassword.getBytes() ); connection.setRequestProperty("Authorization", "Basic "+  encodedAuthorization); ... //Send post data ... } catch (Exception e) { ... } finally { if(connection != null) { connection.disconnect(); } } }

How differently does Java handle checked and unchecked exceptions?

-- If a method may throw checked exceptions, the calling code must handle the exception by either catching it or by declaring in the signature of the method (as throws). Unchecked exceptions do not have to be handled by the calling code. If a method might throw a checked exception, it must be declared in the signature of the method. Unchecked exceptions do not have to be listed in the method signature. When to use checked exceptions and unchecked exceptions? Please visit Best Practices for Exception Handling .

Why a protected member of a superclass can't be accessed from a subclass by using a superclass' reference?

-- Keywords "public", "protected" and "private" are exclusively relevant for access control. They enable the compiler to decide wether a statement referencing a class member is allowed or not. The protected modifier specifies that the member can only be accessed within its own package and, in addition, by a subclass of its class in another package. But, look the following codes (has two packages) from JLS: package points; public class Point { protected int x, y; } package threePoint; import points.Point; public class Point3d extends Point { protected int z; public void delta(Point p) { p.x += this.x; // compile-time error: cannot access p.x p.y += this.y; // compile-time error: cannot access p.y } public void delta3d(Point3d q) { q.x += this.x; q.y += this.y; q.z += this.z; } }

When should I use volatile modifier?

-- A variable that might be concurrently modified by multiple threads (without locks or a similar form of mutual exclusion) should be declared volatile. The volatile modifier can be used to inform the compiler that it should not attempt to perform optimizations on the field, which could cause unpredictable results when the field is accessed by multiple threads. For example, A multiprocessor system(>2 CPUs) with 2 threads sharing a single variable in memory. Thread 1 reads the variable and caches it in one of the registers for efficient access. Thread 2 reads the memory and changes its value. Now if Thread 1 wants to access the value, it may get it from its cache and thus end up with a wrong value. To avoid these scenarios a variable can be declared as volatile , thus informing the JVM that the value can change asynchronously and has to be fetched always from memory or in other words it is like saying to JVM "Please do not optimize this variable for any

Why it is not required to declare the exceptions declared in the superclass' method when overriding it?

-- An implementation of a overriding method in a subclass may be totally different with its overridden method in the superclass. It may not have any exceptions needed to throw at all. The only restriction in Java compiler ( 8.4.6 Method Throws )is that the overriding method in subclass cannot be declared to throw border or new checked exceptions than the overridden method in the superclass (otherwise, you may break other codes because the runtime polymorphism).

Does JVM throw Exceptions for Floating-point arithmetic operations?

-- According to 3.8 Floating-Point Arithmetic . The JVM throws no Exception as a result of any floating-point operations. Special values, such as positive and negative infinity or NaN, are returned as the result of suspicious operations such as positive value, negative value and zero division by zero. For example, class Program { public static void main(String[] args) { double d1 = 1.0; double d2 = 0.0; byte b =1; d1 = d1/d2; b = (byte)d1; System.out.print(b); } } The output is -1 and no exception throw. The process involved is: 1.0/0.0 results in Double.POSITIVE_INFINITY; Double.POSITIVE_INFINITY is converted to Integer.MAX_VALUE ('0' followed by 31 '1's) Integer.MAX_VALUE is then cast to byte value, which simply takes the last 8 bits(11111111) and is -1.

Why it doesn't compile when an inner class has a method of the same name (but different signature) as that of its enclosing class?

-- The compiling the following code will generate an compilation error: public class Program { class Inner { void method(int i) {}; void doSomething() { method(); //compiler error } } void method() {} } Determining the method that will be invoked by a method invocation expression involves several steps: 15.12.1 Compile-Time Step 1: Determine Class or Interface to Search 15.12.2 Compile-Time Step 2: Determine Method Signature 15.12.3 Compile-Time Step 3: Is the Chosen Method Appropriate? According to the rules in 15.12.1 Compile-Time Step 1: Determine Class or Interface to Search , the first step is to figure out the name of the method to be invoked and which class or interface to check for definitions of methods of that name. No method parameters consider in this step:

What are the differences between synchronized method and synchronized block (statement)?

-- The 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 resource while another thread is in the process of using or updating that resource. There two synchronization syntax in Java Language. The practical differences are in controlling scope and the monitor. With a synchronized method, the lock is obtained for the duration of the entire method. With synchronized blocks you can specify exactly when the lock is needed. Basically, synchronized blocks are more general, and synchronized methods can be rewritten to use synchronized blocks: class Program { public synchronized void f() { ......... } } is equivalent to class Program { public void f() { synchronized(this){ ... } } }

What does 'strictfp' mean?

-- The keyword strictfp allows you to have more (predictable) control over floating-point arithmetic. Different arithmetic/logic units may enable additional features which allow a machine dependent answer to a floating point problem. The Java Virtual Machine has been modified to allow Java implementations to use these features where developers are not concerned with a routine, possibly providing a different, ie: more *or* less accurate solution to a problem on differing architectures. Because many developers want the exact same solution to occur regardless of the underlying hardware, the strictfp keyword was implemented. strictfp insures that the VMS will always use a standardized implementation of floating point numbers, wherever the application/applet is run. Thus continuity across platforms is achieved. When this modifier is specified, the JVM adheres to the Java specifications ( IEEE-754 floating-point speci

Why compiler doesn't generate 'unreachable statement' for 'if (false)' statement?

-- The Java compiler won't complain about unreachable code due to an if statement with a constant expression, such as if (false) . The if statement is a special case, because Java's designers wanted to allow us to use compile-time constant booleans to enable conditional compilation. Basically, if (false) {...} is allowed, but while (false) {...} is not. The if statement, whether or not it has an else part, is handled in an unusual manner. It is discussed separately at the end of JLS3 14.21 section: if (false) { x=3; } does not result in a compile-time error. An optimizing compiler may realize that the statement x=3; will never be executed and may choose to omit the code for that statement from the generated class file, but the statement x=3; is not regarded as "unreachable" in the technical sense specified here.

What is the difference between this and super keyword?

-- Using this Keyword Within member methods or constructors of an instance Java object, this is a reference to the currently executing object on which the method or constructor was invoked. It can not appear within static methods. You can refer to any member of the current object from within an instance method or a constructor by using this : Using this keyword as a prefix for member variables, When member variables are shadowed by method or constructor parameters. From within a constructor, you can also use the this keyword to call another constructor in the same class. Doing so is called an explicit constructor invocation , the invocation of another constructor must be the first line in the constructor. For example, .... public Date(long time) { this.time = time; } public Date(int year, int month, int day) { this(year, month, day, 0, 0, 0); } ... Within the scope of a non-static inner class, this refers to the instance o

When to use "private" constructor?

-- The private constructors are used in the following situation: When you implement singletons or factory design pattern. Do not want people to instantiate your class directly. e.g., new MyObject();. For example, all of your method and fields are static, you may need to add a private default constructor (if you do not have it, compiler will add one for you that is not what you want). Such way can enforce that people can not accidently use "new".