|
Java[tm] Programming FAQsWe want to hear from you! Please send us your FEEDBACK. The following responses to Frequently Asked Questions (FAQs) may contain actual software programs in source code form. This source code is made available for developers to use as needed, pursuant to the terms and conditions of this license.
1. How can you sort an array of elements according to a specific ordering criteria? For example the set of elements {123AA, AB123, A3123, 32JDS} should be sorted where elements beginning with letters are placed before those beginning with numbers.
The method Arrays.sort(Object
o) from java.util library will sort
any set of objects according to the object's natural ordering. For
the example given in the question, the objects to be sorted are strings.
The natural ordering of strings is lexicographical. The comparison of two
strings is achieved by comparing the corresponding characters at each character
index. The unicode value of each character is used for comparison to determine
if one character is 'less' than, 'equal' to or 'greater' than the other.
For example the string, lad would come before
let because the unicode value of 'a' (0x61)
is less than the unicode value of 'e' (0x61). Literals representing numbers
have a lower unicode value than those representing alphabetical letters.
Hence Arrays.sort(Object o) will place elements
with leading numbers before letters. For the example given the elements
will be sorted in the order: 123AA, 32JDS, A3123, AB123.
If you want to 'override' the natural order
and define a total order then you need to create a class that implements
the Comparator interface, and pass this class as an argument to the method,
Arrays.sort(Object o, Comparator c). A class
that implements the Comparator interface must define one method, public
int compare(Object o1, Object o2). Compare will return 1, if the
first object o1 precedes o2,
otherwise -1. If the two objects are equal then 0 is returned. Testing
for equality should not contradict the semantics of the equals() method.
2. How do you convert a string representation of a date to an instance of java.sql.Date? Also how do you convert an instance from java.util.Date to java.sql.Date? The following is a program that will take a string representation of a date and convert it to java.util.Date using SimpleDateformat.parse(String s). Java.util.Date is then converted into the time in milliseconds from Jan 1 1970 00:00GMT, using Date.getTime(). This time is passed to the constructor of java.sql.Date to produce a corresponding java.sql.Date object.
//Given a date convert
this to sql.Date
public java.sql.Date convertDate2Sql(java.util.Date d){ long time = d.getTime(); return(new java.sql.Date(time)); } //The parameter string must be compatiable with the format of df i.e. //"yyyy/MM/dd" otherwise a java.text.ParseException thrown. public java.sql.Date convertString2Date(String s) throws ParseException{ SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd"); java.util.Date d = df.parse(s); return(convertDate2Sql(d)); }
Dates can also be represented in databases
by java.sql.Timestamp objects. The
Java.sql.Timestamp
class provides a wrapper around a java.util.Date
object. Java.sql.Timestamp is the Java
representation of the SQL TIMESTAMP type.
Public java.sql.Timestamp convertTimeStamp(String s) throws ParseException { SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd"); java.util.Date d = df.parse(s); long time = d.getTime(); return(new TimeStamp(time)); }
3. What are the most common reasons for a java.util.MissingResourceException being thrown when using java.util.ResourceBundle.getBundle(String s, Locale locale)? Reason 1: You need to create a ResourceBundle class for each locale that you wish to support. You also need to provide a default ResourceBundle, which will be used if no appropriate ResourceBundle class for a locale can be found. For example, you have created the ResourceBundle classes: Meals_fr_FR, Meals_db and Meals_en with a default ResourceBundle class, Meals. A java.util.MissingResourceException is thrown if for a given locale, you cannot find the nearest matching resource bundle for that locale, and you have failed to define a default ResourceBundle class. If a ResourceBundle does not exist for a specific locale, then getBundles will find the nearest match. For instance, if you want to find Meals_fr_FR_UNIX and the default locale is en_GB, then getBundle will look for ResourceBundles in the following order: Meals_fr_FR_UNIX Meals_fr_FR Meals_fr Meals_en_GB Meals_en Meals GetBundle will look and use ResourceBundles in the default locale before using the default ResourceBundle class. Reason 2: An exception will be thrown if
you are working solely with property resource bundles (all bundles are
represented by underlying text files) and you do not append .properties
extension to the file names.
Reason 3: If you pass in the name of the bundle with the .properties extension in the string argument of java.util.ResourceBundle getBundle(String s, Locale l) method. That is, ResourceBundle.getBundle("Meals.properties", Locale.ENGLISH) a java.util.MissingResourceException will be thrown.
4. How can an unsigned applet retrieve a file from the same web server that it was downloaded from? An unsigned applet can open a connection only to the server from which it was downloaded, otherwise security exceptions will occur. The following code creates an applet with
a text area that sends an HTTP request to the web server to establish a
connection with the file resource.
Java.io.BufferedReader
reads the file one line at a time, and each line is displayed on the applet's
text area.
import java.io.*; import java.net.*; import java.awt.*; import java.applet.*;
public class
CommApplet extends Applet{
TextArea ta; public void init() { ta = new TextArea(200, 600); add(ta, BorderLayout.CENTER); uploadFile(); }
public void uploadFile() { try{
//The url is the location of the file URL urlbase
= new URL("http://servername/file");
URLConnection uconn = urlbase.openConnection(); InputStream uc = uconn.getInputStream(); BufferedReader buffIn = new BufferedReader(new InputStreamReader(uc));
String s;
while((s = buffIn.readLine())!= null){ ta.append(s); }
}catch(Exception e){ e.printStackTrace();
} }//End of uploadFile
}
The html file:
<applet code="CommApplet.class" width=400 height=50> </applet>
5. How do you transfer a file between a server and client over TCP/IP using sockets? The file is broken down into bytes in order to be transferred. The server reads the file into a byte array, and it is this byte array that is transferred. In this instance, java.io.RandomAccessFile is used to manipulate the file, but java.io.FileInputStream could also be used. The filename and size are transferred initially so that the client can set up its input buffer before the file content is sent.
6. mySQL will not accept strings with single quotes. How can I place a string with a single quote into a mySQL field? You need to replace the "'" with the escape
sequence, "\\'". Two backslashes are needed as the first escapes the second.
The following will parse a string looking for any problem characters. These
problem characters are replaced in the string by some corresponding characters.
All problem characters and their replacement characters are stored in the
hashMap, replacePhrases.
/** SetUp. */ import java.util.*; ....
Map replacePhrases=new HashMap(); replacePhrases.put("'",
"\\'");
public String parse(String input){ Iterator entryIt = replacePhrases.entrySet().iterator();
//Each problem character is used as a delimiter //If the problem character is present in input string> //then the string will be tokenized.
String output;
while(entryIt.hasNext()){ Map.Entry entry
= (Map.Entry) entryIt.next();
StringTokenizer s = > new StringTokenizer(input, (String)entry.getKey());
//If string tokenized, take the token before the problem //character, concat with the replacement character and then //concat the next token.
if(s.countTokens() > 1){ output = s.nextToken();
while(s.hasMoreTokens()){ output += (String)entry.getValue() + s.nextToken(); } } } return output; }
7. How do you transfer an image from a server to an unsigned applet client over socket connection? The code should be compatable with JDK[tm] version 1.1. Here you will find code that is split into three main sections. The server, the applet client and the utility class, MyCanvas, to display the transferred image in the applet. The server class, Server.java is as in Q5. The applet client, CommApplet.java has the same code as Client.java in Q5, for retrieving the transferred image, but it also has additional code. CommApplet.java will retrieve the image as an array of bytes, and translate this into the object java.awt.Image. CommApplet.java creates a canvas of type MyCanvas.java which will hold the image and which adds the canvas to its display area. MyCanvas.java will use java.awt.MediaTracker to load the image correctly, and then draws the image onto the canvas. The MediaTracker tool is recommended for image loading. While the image is downloading, MediaTracker monitors the image's status, which indicates the presence of any errors. MediaTracker will only complete when the image has downloaded successfully.
8. A container has several sub components. How can a subcomponent get the focus when the top-level container is first opened?
JPanel is the enclosing container. In this example you will find code where a Jbutton called but2, will have the focus whenever the container is first opened. In order to request the focus, the heavyweight container is retrieved using a call to getTopLevelAncestor(). A window listener is then attached to the top-level container and windowOpened is defined to request the focus for button, but2. This code must be placed in addNotify() which overrides the corresponding method in JComponent. AddNotify() is called by the AWT event thread only when a component's parent is created. Hence, it is safe for a subcomponent to reference its parent component at this point. The first line of addNotify()must call the overridden addNotify() for the code to work.
9. How do you make images appear on buttons? Unfortunately AWT Buttons do not support images nor mnemonics. Only javax.swing.Button supports these features. To create an image on a button, type: ImageIcon imageIcon = new ImageIcon("filename.gif"); JButton button = new JButton("ButtonName", imageIcon);
10. How do you load an image into an unsigned applet from the same location as that from which the applet was downloaded? Use
java.applet.Applet.getCodeBase()
to give the directory location of the image, and then java.applet.Applet.getImage(String
dir, String filename) to retrieve the image. Use java.awt.MediaTracker
to load in the image correctly, and override the applet's repaint method
in order to display the image onto the applet. This solution has been proven
to work on IE browsers.
/** ImageApplet.java **/ import java.awt.*; import java.applet.*;
public class
ImageApplet extends Applet{
private Image
image;
public void
init() {
//Retrieve Image image = getImage(getCodeBase(),
"javalogo52x88.gif");
//Load Image MediaTracker tracker = new MediaTracker(this); tracker.addImage(image,
0);
try{> tracker.waitForAll(); }catch(InterruptedException
e){}
}
public void repaint(Graphics g){ g.drawImage(image, 0, 0, this); }
}
11. I have a problem when casting arrays.
The following piece of code compiles fine but at run-time a
java.lang.ClassCastException
is thrown at line 4:
1: Object [] op = new Object[2]; 2: op[0] = new String("hello"); 3: op[1] = new String("goodbye"); 4: String []
strArray = (String [])op;
I know that all elements in op
are of type String, so why can I not cast op
to an array of strings using the cast operator
No compile time error results when the type of source variable, strArray is compatible with the cast operator, (String []). A runtime error results because the runtime type of the op's element is java.lang.Object, as stated in line 1. The JVM[tm] software only allows the assignment between compatible types, so assignment from an object to string would violate the type system. If this assignment was permissible, the array would no longer hold homogeneous type elements; both object and string types could be stored, and upon deferencing the array, the true type of each element could not be determined. Note that the following will both compile
and run without errors:
1: Object [] op2 = new String[2]; 2: op2[0] = new String("hello"); 3: op2[1] = new String("goodbye"); 4: String [] strArray = (String [])op2; Here are two ways around this:
1. Use a java.util.Collection type to store the values, for example, ArrayList, Set, etc, and then use Object [] toArray(Object []) method where the parameter is the runtime type of the array. The JVM software is informed to treat the underlying array as having a runtime type as given by the parameter, even if the actual type is an incompatible type. List list = new ArrayList(); list.add(new String ("hello")); list.add(new String ("Goodbye")); String [] strArray
= (String [])list.toArray(new String[toArray.size()]);
2. Alternatively, use
java.lang.System.arraycopy():
String [] strArray = new String[list.size]; System.arraycopy(list.toArray(), 0, strArray, 0, list.size());
12. How do you explicitly load classes when you do not have the fully qualified name for those classes? ClassLoader.defineClass(String name, byte[], int start, int end) will convert a byte array into an instance of java.lang.Class. The name of the class is not needed so the string parameter can be null. In order to use defineClass you need to subclass java.lang.ClassLoader. This program will take a Java [tm] class file, read it into a byte array, and create an instance of the class. You can then use all methods in java.lang.Class to retrieve information about the newly constructed class.
13. How do you use COM components in Java programs? You can use bridging software to use other vendors' COM classes in your programs written for the Java Platform and to interface with third-party software. The bridging software you choose will need to suit the JVM software version you are using, as well as the application that you want to interface with. Following is a listing of bridging software: JavaBeans
Bridge for ActiveX
J-Integra,
belonging to Intrinsyc Software, Inc.
14. How does the server know when a client disconnects from the server socket? If a client closes its connection to the server correctly by using java.net.Socket.close(), then any subsequent sending of data over the input stream will result in a java.io.IOException on the server side. However, should the client not close down correctly because of network, hardware or OS failure, then the client socket is still open, and from the server perspective the client can still receive information. A good way to handle this scenario is to set a timeout limit on the socket connection, and poll the client with test messages. If the client does not acknowledge these messages within the timeout period, then the server can assume that the client is down, and then disconnect. Your client will need to be programmed to automatically return acknowledgments for all data transfers from the server. Here you will find what the server should include.
15. How do you convert a string to a byte array and visa versa? Java.lang.String has certain utilities to convert a string into a byte array and visa versa. A string can be converted correctly and fully into a byte array by using a character encoding such as UTF-8, US-ASCII. All the overloaded String.getBytes() methods will convert a string into a byte array. Some of these methods take an encoding identifier as an argument, while others take no arguments and will use the platform's default encoding to convert the string. A byte array can be converted into a string using the string constructor methods. Some take an encoding identifier, while others take none and use the platform's default encoding. A listing of appropriate encoding identifiers is found at Character Encodings. The following program does string to byte array conversion using the default platform encoding, and the UTF-8 character encoding. public void converting(){
String str = new String("A" +"\u00fe"+"\u00f3"+"e"); System.out.println("String is "+ str); try{ //Encode using US-ASCII format //Create a byte array of str using the encoding UTF-8 byte [] usAsciiBytes
= str.getBytes("UTF-8");
//To convert the byte array back into its String representation, create a new String passing in the //character encoding and the byte array. String conversion = new Str(usAsciiBytes, "UTF-8"); System.out.println("Byte [] -> String with UTF-8" + conversion); System.out.println();
//Encode using platform's default encoding. byte [] defaultEncodingBytes = str.getBytes(); String defaultBytes = new String(defaultEncodingBytes); System.out.println("Byte [] -> String with DefaultEncoding"+defaultBytes); }catch(UnsupportedEncodingException e){ e.printStackTrace(); } } Every Java JVM software implementation
has a default character encoding which is dependent upon its locale and
the underlying operating system. A list of supported encodings should be
given in the release documentation of the JVM software implementation. All JVM software
implementations should support certain encodings including UTF-8, US-ASCII.
In the above program, if the US-ASCII encoding was used then the unicode
literals would be represented as question marks in the byte array. Question
marks are used to represent characters that are not supported by a given
character encoding.
16. How do you remove all white space in a string? Java.lang.String.trim()
will remove all preceding and following whitespace around a string. In
order to remove any intermediate whitespace you can use the following code.
It will tokenize the string with a space, ' ' as the delimiter, and then
construct the result with the tokens.
public void removeWhiteSpace(String s){ System.out.println(s); String newStr
= s.trim();
// '\u0020' is the unicode value for space, ' ' StringTokenizer st = new StringTokenizer(s, "\u0020"); String result = ""; while(st.hasMoreElements()){ String token = st.nextToken(); System.out.println("token:"+ token); result+= token; }
System.out.println("Result is"+ result); }
17. What is the cause of the following error: "Failed to load Main-Class manifest attribute from my.jar" when using JDK version 1.2? When using JDK version 1.2 or higher, you need to include a manifest file with a Main-Class header correctly set in any JAR files. The 'Main-class' header should point to a java class with a main method. In your manifest file include the line: Main-Class: MainFileName The .class extension is omitted from the MainFileName. You then want to merge the manifest file and the Java class file which has a main method, into a JAR file. For example for a manifest file called, mymanifest and a Java class file called MainFileName.class, you create a JAR file called my.jar by executing the following: jar cmf mymanifest my.jar MainFileName.class
18. How do you print using AWT JDK version 1.1
and JDK version 1.2?
AWT JDK version 1.1 AWT components are drawn onto a special graphics object which refers to a printer. All components have a print(Graphics) and printAll(Graphics) method. These should be implemented to render an image of the component into the graphics object. In order to print, you need to implement the print/printAll method of a component, and construct a graphics object to represent the output on a page to be printed. STEPS:
Follwing is an example: import java.awt.*; import javax.swing.*; import java.awt.event.*;
public class
AWTPrint{
public static
void main(String args[]){
final JFrame frame = new JFrame("AWTPrint"); final JTextField text = new JTextField("hello", 45); Button b = new Button("Print"); frame.getContentPane().add(b, BorderLayout.NORTH); frame.getContentPane().add(text,
BorderLayout.CENTER);
b.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent e){ Toolkit kit = ((Component) (e.getSource())).getToolkit(); PrintJob job = kit.getPrintJob(frame,"Printing", null); if(job != null){ Graphics g = job.getGraphics(); g.setClip(new Rectangle(6,6,80*3, 80*3)); text.print(g); g.setFont(new Font("Serif", Font.BOLD , 18)); g.dispose(); } job.end(); } });
frame.setVisible(true); } }
AWT JDK version 1.2 Printing in AWT JDK version 1.1 is relatively simple. In AWT JDK version 1.2, more printing functionality is provided. STEPS:
Here you will find code that uses the printing mechanisms of AWT JDK version 1.2 to produce the same result as preceding code for AWT JDK version 1.1. For more information on printing in AWT JDK version 1.2 see:
19. I am creating a query string to be executed by the underlying mySQL database. The string is made up of string literals concatenated with string references, for example: String word = "Jumper"; String retrieveGreetings = "SELECT Price FROM Stockroom WHERE Clothing = "+word; However, this statement fails to be executed. Why? When using a mySQL database, strings are represented by the type VARCHAR. A VARCHAR literal is represented as a sequence of characters in single quotes, such as 'Hello'. You need to enclose the string reference with single quotes: String retrieveGreetings = "SELECT Price FROM Stockroom WHERE Clothing = '"+word+"'";
If you do not do this, the string is dereferenced as a column name which could be invalid.
20. When printed, the following arithmetic equation only prints one decimal place after the point. How can it print out more? float fl = 54/7; System.out.println(fl);
//Prints 7.0
7.0 is printed because of binary numeric promotion and no explicit formatting. The loss of precision is because the result of the division is narrowed to an int. The numeric promotion rule states that the result type of an arithmetic expression is the same as the broadest type of its operands which in this case is int. When the integer result is assigned to the float reference it is then promoted to a float type, and hence the single decimal point is printed out. To maintain precision, you must inform the JVM software to do float/double division by attaching either the 'f' or 'd' flag to the expression. For example, float fl = 54/7f or double do = 45/6d. The DecimalFormat class allows the developer to determine what level of precision should be printed. The DecimalFormat constructor takes a pattern which determines how numbers should be formatted. For example, if you want three decimal places after the point, you could do the following: DecimalFormat df = new DecimalFormat("###.##"); System.out.println(df.format(fl)); //Prints 7.71
21. I am using Process.waitFor() to force my application written for the Java platform to wait until the native process has finished. However this does not happen. Why? In order to wait for a subprocess to finish
before your application proceeds, you should place waitFor()
in a try/catch block and test that the process has terminated. A terminated
process will return an exit code of 0. For example:
try {
if(process.waitFor() == 0) { //By placing this in a condition, the java program is forced to wait } else throw new Exception("Process failed to terminated correctly"); }catch(InterruptedException e){ System.out.println(e.getMessage()); }
However, this code may fail to work for some processes. The following is an excerpt from the API documentation on class Process: "The Runtime.exec methods may not work well for special processes on certain native platforms, such as native windowing processes, daemonprocesses, Win16/DOS processes on Win32, or shell scripts. The created subprocess does not have its own terminal or console. All its standard io (i.e.stdin, stdout, stderr) operations will be redirected to the parent process through three streams (Process.getOutputStream(), Process.getInputStream(),Process.getErrorStream()). The parent process uses these streams to feed input to and get output from the subprocess. Because some native platformsonly provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock. "
22. In a program developed in the Java[tm] programming language, how do you redirect any error messages to a file instead of standard output? The method, java.lang.System.setErr(PrintStream newErrorStream) reassigns the underlying "standard" error output stream to the PrintStream, newErrorStream. The PrintStream wraps a FileOutputStream to an output file. import java.io.*; public class
SendingError {
public static void main(String args[]){ File out = new File("output.log");
try{ FileOutputStream fileOut = new FileOutputStream(out); PrintStream outPrintStream = new PrintStream(fileOut); System.setErr(outPrintStream);
//A test throw new Exception("Problem"); }catch(Exception e){ e.printStackTrace(); } } }
23. How do you pass form information between an HTML page and an applet using the JavaScript[tm] programming language? The following steps are a quick guide to using the JavaScript[tm] programming language with applets:
Here you will find an example of an applet that is embedded in an HTML page. This page has a form component with subcomponents. The applet has three methods: setFormName, and setFormNumber which takes the input from the form and sets the corresponding variables of the applet, and getFormNumber which returns an integer to be displayed in HTML. In the HTML page, there is a corresponding JavaScript programming language function for each of the applet's accessor methods. The HTML page has one drop down list which when selected will call the setFormNumber method; a textfield which when given input will call setFormName; and a button which when clicked upon will call getAppletNumber(); getAppletNumber() will then display its result in the textarea of the form. The applet will also display two redundant buttons. You may notice in the method, setFormNumber takes a float object as its argument. The reason is that all JavaScript programming language numbers, regardless of type are converted to float objects when passed to any code developed in the Java programming language. JavaScript programming language string and booleans map straight to Java programming language string and boolean objects. JavaScript technology is a Netscape created language. LiveConnect is a netscape technology which enables JavaScript technology and applets to communicate. Liveconnect is fully supported by them for all Navigator versions since version 3. There is limited support on Internet Explorer. For details on setting up Liveconnect, refer to Web Reference. There are some problems using JavaScript technology with the Java Plugin for some browsers. For more information please see Java Plugin Overview PLEASE NOTE that JavaScript is not a Sun supported product.
24. Where are the sun.net.ftp.* classes and when should I use them? The sun.net.ftp.* are JVM software specific classes to aid the development of applications using the ftp protocol. Sun's JRE [tm] includes several standard URLStreamHandler classes for ftp. The implementation classes are in the JDK software's rt.jar file found under $JAVA_HOME/jre/lib. You can import these classes into your Java applications in the usual manner. However you should not directly use/reference these files as they are not a standard part of the Java 2 Platform. The sun.* packages are implemented differently on different platforms, and can change between releases without notification. All JVM technology vendors independently implement the sun.* packages. Thus, applications that use packages that are not portable, which goes against one of the core principles of the Java programming language. PLEASE NOTE: There is no javadoc documentation for sun.*. However, you can find documentation comments under The community resource code licensing .
25. How can I get Technical support? The Java [tm] Forums are a great place to start for technical help. The forums form a large community with a vast level of expertise in all areas of the Java [tm] Platforms . If you have an issue with a specific J2EE [tm] product and you are unable to get help from the forums, the best recourse is to visit the website of the vendor from who you pruchased your product. Sun [tm] itself offers excellent in-depth developer support programs at many different levels. For more information about these offerings or to purchase one, please visit the Sun Developer Connection web site. | |||||||||||||||||||||||||||||||||||||||