|
Advertisement |
Useful JAVA Tips
Posted On May 15, 2012 by Sneha Philipose filed under Enterprise
Q: What're the differences between classpath and import in the java application? Do I need to have the package in the classpath first before importing in a java application or need not?
Answer: Classpath is an environment variable of your OS, you have to set it (or better: Java sets it) to tell Java where to search for classes.
You use import in a program to let Java search for the specified classes within the classpath. This implies that the package must be in the classpath.
Q: I was just wondering about the usefulness of Interfaces. I was under the impression that interfaces could be used to perform multiple inheritance. But an interface only declares a method - in a very abstract way.
A class that implements an interface needs to define its own implementation of a certain method.
What is the use of having an interface when nothing is being gained...?
Answer: If two classes implements the same interface, you can get a reference to the interface instead of the effective class without bother what class are you managing. This is very useful in RMI (for example) or in any condition when you have to take an object without knowing exactly his class, but only the interface that it implement.
For example:
public void recurseList( List l )
the generic List ensure that you can use every List for this method (ArrayList, AbstractList,
Vector...), so your calling method can be:
ArrayList l = new ArrayList(); or
Vector l = new Vector();
recurseList( l );
Without any problem.
------- ---------------------
Q: Is it possible to stop an object from being created during construction? For example if an error occurs inside the constructor (e.g. the parameters pass in were invalid) and I wanted to stop an object being created would it be possible to return null rather than a reference to a new object. (I know the term return is technically correct in this case but you know what I mean). Basically, is it possible to cancel object creation?
Answer: Yes, have the constructor throw an exception. Formally, an object _will_ be created (since the constructor is a method invoked after the actual method creation), but nothing useful will be returned to the program, and the dead object will be later reclaimed by Garbage Collector. But the clean way is as another reply suggests, that you leave calls to the constructor to a static
factory method which can check the parameters and return null when needed. Note that a constructor - or any method in general - throwing an exception will not "return null", but will leave the "assign target" as it was.
------- ---------------------------- ---------------------------- ---------------------
Q: Why developers should not write programs that call 'sun' packages?
Answer: Java Software supports into the future only classes in java.* packages, not sun.* packages.
In general, API in sun.* is subject to change at any time without notice.
A Java program that directly calls into sun.* packages is not guaranteed to work on all Java- compatible platforms. In fact, such a program is not guaranteed to work even in future versions on the same platform.
For these reasons, there is no documentation available for the sun.* classes. Platform- independence is one of the great advantages of developing in the Java programming language. Furthermore, Sun and our licensees of Java technology are committed to maintaining backward compatibility of the APIs for future versions of the Java platform. (Except for code that relies on serious bugs that we later fix.) This means that once your program is written, the class files will work in future releases.
For more details, see the article Why Developers Should Not Write Programs That Call 'sun' Packages.
http://java.sun.com/products/jdk/faq/faq-sun-packages.html
------- ---------------------------- ---------------------------- ---------------------
Q: I need some Java APIs wherein I can implement various compression algorithms. I have already the GZIP compression technique shipped with JDK's java.util.zip package. I am looking for more efficient compression APIs esp. for *.doc and *.html files.
Answer: You often get better compression results for a large number of smaller files by concatenating the uncompressed files and then compressing the result. That's why tar.gz is often superior to zip for large numbers of html files (like API docs).
You will not get much better general-purpose compression than Zip, at least not until you have a specific class of data and know very much about its structure. Even then you'll need some experience and time working on a better compression method.
You might want to take a look at this Java implementation of bzip2:
http://www.aftexsw.com/aftex/products/java/bzip/
It uses more CPU cycles and memory but typically compresses better than zip.
------- ---------------------------- ---------------------------- ---------------------
Q: About the order of my elements in hastable...
I save some data into hashtable. For example,
hashtable.put ( "1", "one" );
hashtable.put ( "2", "two" );
hashtable.put ("3" , "three" );
when I get back the element from hashtable using Enumeration class ,
Enumeraton e = hashtable.keys();
while ( e.hasMoreElements() ){
Object k = e.nextElement();
Object v = hashtable.get (k );
}
the default result is
"3","three"
"2", "two"
"1", "one"
here I want to get the data sorted as ascending. ( the order as I insert ) such as
"1", "one"
"2", "two"
"3", "three"
or is it possible to get the data from end of hashtable?
Answer: When you insert elements into a Hashtable, they will not be stored in the order you insert them. They are stored in a way that makes it easy to find them by the key you specify.
So, you must either use another data structure (e.g. Vector) or sort them after you retrieve them from the Hashtable (e.g. by using java.util.Collections, java.util.Arrays).
------- ---------------------------- ---------------------------- ---------------------
Q: Is there a way to reduce the amount of time that it takes to download an applet?
Answer: There is a way to reduce the amount of time an applet takes to download. What ever classes the Java applet is refering, you cluster them in a JAR file with the help of JAR utility that comes with the JDK version. Check out the help for the options of that utility and make a ".jar" file out of the applets refered classes and images and other relevent data which you want to
load.
Use the archive option of the applet tag and assign the .jar file:
<applet code="xyz.class" archieve="pqr.jar" width=100 height=100>
</applet>
------- ---------------------------- ---------------------------- ---------------------
Q: I am writing an applet that will use images. I would like to ship out the images using a jar file that contains all the images that the applet is going to use. I have seen a piece of code that does that in the past, but I don't remember where.
Answer:
http://developer.netscape.com/docs/technote/java/getresource/getresource.html
import java.applet.*;
import java.awt.*;
import java.io.*;
public class ResourceDemoApplet extends Applet {
Image m_image;
public void init() {
try {
InputStream in = getClass().getResourceAsStream("my.gif");
if (in == null) {
System.err.println("Image not found.");
return;
}
byte[] buffer = new byte[in.available()];
in.read(buffer);
m_image = Toolkit.getDefaultToolkit().createImage(buffer);
} catch (java.io.IOException e) {
System.err.println("Unable to read image.");
e.printStackTrace();
}
}
public void paint(Graphics g) {
if (m_image == null)
return;
Dimension d = getSize();
g.drawImage(m_image, 0, 0, d.width, d.height, Color.white, this);
}
}
------- ---------------------------- ---------------------------- ---------------------
Q: Does anyone know how to or where I can find information about determining if cookies are disabled on a client browser making a request to a servlet or JSP (or any server side request handler, for that matter)? Also, is there a way to determine whether or not a client's browser has style sheets enabled?
Answer: To test if the client has cookies enabled, create a cookie, send it, and read it back. If you can't read it back, then the client does not accept them. It's not a clean way of doing it, but it's the only way (that I know if).
As for CSS, there is no way to know if they allow CSS. Different versions of the browsers support varying levels of CSS. You can get the browser type from the request object and then make decisions based on that.
------- ---------------------------- ---------------------------- ---------------------
Q: How can two applets communicate with each other? Have you some examples?
You will occasionally need to allow two or more applets on a Web page to communicate with each other. Because the applets all run within the same Java context-that is, they are all in the same virtual machine together-applets can invoke each other's methods. The AppletContext class has methods for locating another applet by name, or retrieving all the applets in the current
runtime environment
import java.applet.*;
import java.awt.*;
import java.util.*;
// This applet demonstrates the use of the getApplets method to
// get an enumeration of the current applets.
public class ListApplets extends Applet {
public void init() {
// Get an enumeration all the applets in the runtime environment
Enumeration e = getAppletContext().getApplets();
// Create a scrolling list for the applet names
List appList = new List();
while (e.hasMoreElements()) {
// Get the next applet
Applet app = (Applet) e.nextElement();
// Store the name of the applet's class in the scrolling list
appList.addItem(app.getClass().getName());
}
add(appList);
}
}
-----------------------------------------------------------------
Q: How do I delete a file in Java? I have programmed a Java application that needs to delete a file, but I couldn't find anything on the topic.
Answer: in java.io.File there is delete
public boolean delete()
Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the directory must be empty in order to be deleted. Create a new File object representing the file, and then use the delete () method. If you use the Microsoft JVM, make sure the file is not shared before you delete it, otherwise that will not work (the delete () method returns
"false").
-----------------------------------------------------------------
Q: I heard that JSP will eventually compile into servlet class file. One thing can be done by servlet, can it be done by JSP too? In terms of http.
Answer: Everything a servlet does can be done in JSP and vice versa. Good programming practice (you will see some articles over the last year in JavaPro) dictates to combine servlets and JSP in any significant web application.
JSP should be mainly HTML (or XML, or WML or whateverML) with little Java inside. Servlets should be Java with few or not at all lines like this:
out.println( "<html>" );
out.printlb( "<body>" );
This creates a more or less clean separation between presentation (JSP) and business logic (servlet).
Java beans also have a role in this. I strongly recommend the JavaPro articles or whatever text on the MVC model you can find.
-----------------------------------------------------------------
Q: I was just wondering about the usefulness of Interfaces. I was under the impression that interfaces could be used to perform multiple inheritance. But an interface only declares a method - in a very abstract way.
A class that implements an interface needs to define its own implementation of a certain method. What is the use of having an interface when nothing is being gained...?
Answer: If two classes implements the same interface, you can get a reference to the interface instead of the effective class without bother what class are you managing. This is very useful in RMI (for example) or in any condition when you have to take an object without knowing exactly his class, but only the interface that it implement.
For example:
public void recurseList( List l )
the generic List ensure that you can use every List for this method (ArrayList, AbstractList,
Vector...), so your calling method can be:
ArrayList l = new ArrayList(); or
Vector l = new Vector();
recurseList( l );
Without any problem.
-----------------------------------------------------------------
Q: Is it possible to stop an object from being created during construction? For example if an error occurs inside the constructor (e.g. the parameters pass in were invalid) and I wanted to stop an object being created would it be possible to return null rather than a reference to a new object. (I know the term return is technically correct in this case but you know what I mean). Basically, is it possible to cancel object creation?
Answer: Yes, have the constructor throw an exception. Formally, an object _will_ be created (since the constructor is a method invoked after the actual method creation), but nothing useful will be returned to the program, and the dead object will be later reclaimed by Garbage Collector. But the clean way is as another reply suggests, that you leave calls to the constructor to a static
factory method which can check the parameters and return null when needed. Note that a constructor - or any method in general - throwing an exception will not "return null", but will leave the "assign target" as it was.
-----------------------------------------------------------------
Q: Difference between loading and instantiating a class?
Well, the subject says it all. What is the difference between loading and instantiating a class in a JVM.
Second question: What would happen if at runtime I update a class file? Will the JVM know to use that instead?
Answer: The difference is that when a class is loaded by a ClassLoader it is read in as a stream of bytes, presumably from a file, but it could just as easily be from over the network, and then
processed or "cooked" into a representation that the VM can use to make instances of Objects of that classes type. This last part is the instantiation. You can load a class at runtime with:
Class.forName( "MyClass" );
and instantiate one with:
MyClass mc = Class.forName( "MyClass" ).newInstance();
You don't have to know the name of a class at compile time.
>Second question: What would happen if at runtime I update a class file?
>Will the JVM know to use that instead?
Loaded classes are cached because it's quite costly to do the "cooking" I mentioned above. So it will not be loaded. You may create a separate ClassLoader with new SecureClassLoader but that will cause all classes _it_ loads to be loaded from this new ClassLoader but that's not what you want.
I don't know if you can specify that a class should be loaded from disk again using the normal ClassLoader. You could very easily make your own ClassLoader in which case you would have
explicit control over such things. Look at java.lang.ClassLoader and java.lang.Class.
----------------------------------------------------------------
Q: What is difference capacity() and size() methods for vector?
What is difference between
public final int capacity()
Returns the current capacity of this vector.
and
public final int size()
Returns the number of components in this vector.
Answer: please read this method: ensureCapacity public final synchronized void ensureCapacity(int minCapacity)
Increases the capacity of this vector, if necessary, to ensure that it can hold at least the number of components specified by the minimum capacity argument.
Parameters:
minCapacity - the desired minimum capacity.
----------------------------------------------------------------
Q: Can garbage collector remove my singleton?
A usually singleton.
public class Single{
private static Single single;
private Single {}
public static Single getInstance(){
if(single==null){
single = new Single();
}
return single;
}
}
Well,, seems good ?
But classes are objects too...so do Java 2 v1.3 class garbagecollecting? Meaning my singleton could dissapear if i dont keep a refrence to it (or the class itself) somewhere ?
If classes is not garbagecollected, that's pretty stupid, I dont want classes taking up memory when i perhaps never will use it again....
Answer: No. Classes can define objects. That is, only the dynamic part of the class defines objects. The static part exists only in one place in memory and can not be duplicated. You can call the getInstance() method from anywhere in your program.
Java requires however that you tell where to find the method, in this case in the Single class. Therefore, you should use
Single.getInstance()
to get the instance. This is (though it looks much like it) not an execution of a method on an object, but just a method call without object. Single is only used to find out which getInstance() method should be used, and where it is.
You could add a delete() method if you don't need the instance anymore:
public class Single{
private static Single single;
private Single {}
public static Single getInstance(){
if(single==null)
single = new Single();
return single;
}
public static delete(){
single = null;
}
}
The garbage collector can now remove the single object after delete() is called if memory is needed.
-------------------------------------------------------- ------------------------------------------
Q: How do I copy one array to another? Given that I have an byte array defined like this:
byte byteSmall = new byte[23];
and another larger byte array defined like this:
byte byteBig = new byte[30];
How do I copy byteSmall into byteBig starting at index 7 without a for loop like this:
for(int i = 0; i < 23; i++){
byteBig[i + 7] = byteSmall;
}
Answer:
"Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array. A subsequence of array components are copied from the source array referenced by src to the destination array referenced by dst. The number of components copied is equal to the length argument. The components at positions srcOffset through srcOffset+length-1 in the source array are copied into positions dstOffset through dstOffset+length-1, respectively, of the destination array.
If the src and dst arguments refer to the same array object, then the copying is performed as if the components at positions srcOffset through srcOffset+length-1 were first copied to a temporary array with length components and then the contents of the temporary array were copied into positions dstOffset through dstOffset+length-1 of the argument array."
-------------------------------------------------------- ------------------------------------------
Q: I want to use some java variables, across multiple java files. Is there some thing like a "extern in C" in java ?
Answer: If you want to share constants, the usual way is to create a class like this:
public class My_Constants {
public static final int ID_OK = 1;
public static final int ID_CANCEL = 2;
public static final String MSG_OK = "Okay.";
public static final String MSG_ERROR = "An error occurred.";
}
If you want to share a single object instance across your application, use the Singleton pattern. Actually, the more common way is to create an interface, like this:
public interface MyConstants{ // Note naming conventions
int ID_OK=1; // public static final is implicit in interfaces
// etc
}
Then anyone who wishes to use the constants without putting MyConstants before each reference can simply implement the interface.
-------------------------------------------------------- ------------------------------------------
Q: Can someone tell me the difference between the JRE that comes with the J2SDK and the stand-
alone JRE?
Can someone tell me the difference between the JRE that comes with the J2SDK and the stand-alone JRE? When should I use which? I read the sun's web page and they said the the JRE stand-alone package is for shipping your application, it doesn't come with a compiler nor debugger, butwhat does it really mean?
Answer: Exactly that. The Java 2 SDK (aka JDK) is the JRE plus the compiler (javac) and debugger (jdb). The JRE is entirely sufficient to run a Java application (with a couple exceptions in situations where you call into the compiler or some such). It's entirely redistributable with your Java application if you've written an app in Java intended for an audience that may not have the JRE
installed.
-------------------------------------------------------- ------------------------------------------
Q: Heap size limit!! I am running JVM from JDK 1.2 on Solaris 2.7 and I couldn't allocate the max heapsize over 2G when I invoke the JVM.
I have repetive tasks that take 500m memory each to run, so I naturally want to run as many threads as possible. I figured out this 2G (-mx2047m) limit by trial and error but is there any way out of this? My workstation happen to have 2G physical memory, and the file size limit is 2G as well (from ulimit), are there any co-relation among those numbers?
Answer: Yes, there is a relation: both result from limiting addressing space to what you can get with signed 32-bit ints for addresses:
2^31 - 1 = 2 * 2^30 -1 = 2 * 1 GB -1 = 2 GB
One of the interesting features of Java, is you could run the code with 64 bit addresses, and nothing would need to change in either the source code or the class files. The only difference would be you could hold a lot more objects and stack frames before you blew virtual RAM. Obviously you would need a different JVM or Hotspot.
Java never lets you discover how big references really are inside or how they are implemented, e.g.
as pointers or as handles, or even the granularity of the addressibility of your machine. On a 32-bit OS it is a liitle hard to get 32+ bit memory space. How about you try a 64-bit Solaris 8?
answered by Michiel, Roedy Green, JAVA GLOSSARY see http://www.mindprod.com/jgloss.html and Johnny Bravo





ramkey commented, on May 18, 2012 at 10:17 a.m.:
Dear DIQ
Provide more tip and tricks of Java.