FFMPEG Install for CentOS 5

 FFMPEG Install for CentOS 5

A little while back, I posted a basic install of ffmpeg for CentOS 5. After working with that build over the last month, I found I needed to expand it to include many different video codecs. Because of licensing restrictions, binaries of the build cannot be distributed. However, instructions for a similar build can! I spent several days (or more) researching the packages I would need and I must have combed dozens of blogs to find this information. The build I made strips sound from videos [See update at the end of this post for more information on this subject], this decreases the final file size. If you need sound, you will not want to follow these steps exactly. I also stripped ffserver and ffplay from my build.

These packages were executed in the following order. I cannot say for certain this exact order must be followed, it was the order in which ffmpeg threw the errors. This tutorial assumes you have wget, bzip2, tar and subversion installed on your system. If you do not, please find and install the lastest versions of these utilities for CentOS 5. Additionally, I have allowed all packages to install into their default directories, typically this is /usr/local/[bin | lib]. If at any point during the process of a ‘make’ you run into errors, be sure and run ‘make clean’ before running ‘make’ again. You will either need root access of su access to install ffmpeg. The marker ‘codec:$’ is my prompt, it is merely to indicate separate commands.

Getting Started

codec:$ mkdir -p ./tmp/ffmpeg-packages
codec:$ cd ./tmp/ffmpeg-packages

Installing a52

codec:$ wget http://liba52.sourceforge.net/files/a52dec-0.7.4.tar.gz
codec:$ tar -zxf a52dec-0.7.4.tar.gz
codec:$ cd a52dec-0.7.4
codec:$ ./configure –enable-shared=PKGS
codec:$ make && make install
codec:$ cd ..

Installing FAAD2

codec:$ wget http://downloads.sourceforge.net/faac/faad2-2.6.1.tar.gz
codec:$ tar zxf faad2-2.6.1.tar.gz
codec:$ cd faad2
codec:$ autoreconf -vif
codec:$ ./configure –disable-drm –disable-mpeg4ip
codec:$ make && make install
codec:$ cd ..

Installing FAAC

codec:$ wget http://downloads.sourceforge.net/faac/faac-1.26.tar.gz
codec:$ tar zxfv faac-1.26.tar.gz
codec:$ cd faac
codec:$ ./bootstrap
codec:$ ./configure –disable-mp4v2
codec:$ make && make install
codec:$ cd ..

Installing LAME

codec:$ wget \
codec:$ tar zxfv lame-3.98b8.tar.gz
codec:$ cd lame-3.98b8
codec:$ ./configure
codec:$ make && make install
codec:$ cd ..

Installing yasm

YASM is a modular assembler, it is required by the x264 package.

codec:$ wget \
codec:$ tar zfvx yasm-0.7.0.tar.gz
codec:$ cd yasm-0.7.0
codec:$ ./configure
codec:$ make && make install
codec:$ cd ..

Installing x264
The x264 package is under git revision control, which is much like CVS or SVN. Thankfully, they provide daily tarballs. I grabbed this one:

codec:$ wget \

I just did a little exploring via an FTP program to find the snapshot I was after. If you are feeling adventurous, download git and try checking out the latest version from their repository.

codec:$ bzip2 -d x264-snapshot-20080513-2245.tar.bz2
codec:$ tar xfv x264-snapshot-20080513-2245.tar
codec:$ cd x264-snapshot-20080513-2245
codec:$ ./configure –enable-mp4-output –enable-shared –enable-pthread
codec:$ make && make install
codec:$ cd ..

Installing Xvid

codec:$ wget http://downloads.xvid.org/downloads/xvidcore-1.1.3.tar.gz
codec:$ tar zxfv xvidcore-1.1.3.tar.gz
codec:$ cd xvidcore-1.1.3/build/generic
codec:$ ./configure
codec:$ make && make install
codec:$ cd ../../..

Installing libraw1394

codec:$ wget http://www.linux1394.org/dl/libraw1394-1.3.0.tar.gz
codec:$ tar zxfv libraw1394-1.3.0.tar.gz
codec:$ cd libraw1394-1.3.0
codec:$ ./configure
codec:$ make dev
codec:$ make && make install
codec:$ cd ..

Installing libdc1394

This project requires libraw1394, you must build it first. This project is a little confusing there is both a libdc1394 and a libdc1394-2. I have only installed the former. Visit Sourceforge here. I grabbed the tarball here:

codec:$ wget \
codec:$ tar zxfv libdc1394-1.2.2.tar.gz
codec:$ cd libdc1394-1.2.2
codec:$ ./configure
codec:$ make && make install
codec:$ cd ..

Installing ffmpeg

For FFMPEG, you will need to get the latest out of SVN. FFMPEG doesn’t ever make releases. To do so, run:

codec:$ svn checkout svn://svn.mplayerhq.hu/ffmpeg/trunk ffmpeg
codec:$ cd ffmpeg

codec:$ ./configure –enable-gpl –enable-postproc –enable-nonfree –enable-postproc –enable-libfaad –enable-swscale –enable-avfilter –enable-pthreads –enable-libxvid –enable-libx264 –enable-libmp3lame –enable-libdc1394 –enable-liba52 –enable-libfaac –disable-ffserver –disable-ffplay
codec:$ make
codec:$ make install

It usually takes at least 5 mins for ‘make’ to run, be sure you have a good file before attempting to install. You will need to be sure and run the ldconfig setting if you have to re-compile, otherwise ffmpeg will throw an error that it cannot find library files. Here is a good resource for using ffmpeg.

Post-Installation Actions

After the install in complete, you may need to add the /usr/local/lib directory to your ld.so.config file. Do the following:

codec:$ cd /etc/
codec:$ cd ld.so.conf.d
codec:$ vi ffmpeg.conf

You need to add ‘/usr/local/lib’ [sans-quotes] to this file and save it. Press Esc, :, x to do so in vi. Afterwords you need to run the following from the commandline

codec:$ ldconfig

That’s it, you now have a fairly robust build of ffmpeg that can take almost anything you can throw at it. Sadly, licensing restrictions prevent binaries from being made of the above steps. Happy (video) encoding!

Update: This build doesn’t actually strip sound from videos, I am doing that with a flag when I run ffmpeg, however, it should be noted that all the audio codecs you may find in many common video formats may not be supported in this build of ffmpeg, which is why I am choosing to strip audio entirely from videos.

終於搞掂量: rhel5 64 yum update









#cd /etc/yum.repos.d

# cat rhel-debuginfo.repo
name=Red Hat Enterprise Linux $releasever -Base
name=Red Hat Enterprise Linux $releasever -Updates
name=Red Hat Enterprise Linux $releasever -Extras
name=Red Hat Enterprise Linux $releasever -Addons




[root@web1363 yum.repos.d]# cat rpmforge.repo
# Name: RPMforge RPM Repository for Red Hat Enterprise 5 – dag
# URL: http://rpmforge.net/

name = Red Hat Enterprise $releasever – RPMforge.net – dag
mirrorlist = http://apt.sw.be/redhat/el5/en/mirrors-rpmforge
enabled = 1
protect = 0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rpmforge-dag
gpgcheck = 1





OK,馬上yum update吧!








     Mplayer windows版本下载列表:http://www5.mplayerhq.hu/MPlayer/releases/win32/



    现在可以试试用Mplayer播放视频,比如有个视频位于D:\music\APerfectMatch.wmv,那么可以打开一个cmd窗口,输入 mplayer “D:\music\APerfectMatch.wmv”,感受一下来自Linux的播放器吧,可以通过键盘来操纵。



mencoder ””E:\test.m2p”” -o ””E:\output.flv”” -of lavf  -lavfopts i_certify_that_my_video_stream_does_not_use_b_frames -oac mp3lame -lameopts abr:br=56 -ovc lavc -lavcopts vcodec=flv:vbitrate=500:mbd=2:mv0:trell:v4mv:cbp:last_pred=3:dia=4:cmp=6:vb_strategy=1 -vf scale=512:-3 -ofps 12 -srate 22050







-o ””E:\output.flv””:是输出文件路径;

-of lavf:是输出文件格式,这里不是flv而是lavf,是因为flv属于libavformat;

-lavfopts i_certify_that_my_video_stream_does_not_use_b_frames:-lavfopts表示对lavf进行一 些设置,设置的内容就是i_certify_that_my_video_stream_does_not_use_b_frames,翻译成中文就是: 我确定,我的视频不用B frames,对于转换flv格式,最好加上这个参数,否则可能会报错,如图:

-oac mp3lame:oac=output audio codec,输出音频编码器,这里用的mp3lame;

-lameopts abr:br=56:lame options,是专门针对mp3lame的参数设置,abr:br=56,是设置音频比特率为56(比特率:每秒钟输出的音频大小,单位kb/s);

-ovc lavc:ovc=output video codec,输出视频编码器,lavc表示one of libavcodec’s video codec,输出格式为libavformat之一,编码器当然也是libavcodec之一啦,至于libavodec里都有哪些编码器,可以查看 Mplayer的官方文档;

-lavcopts vcodec=flv:vbitrate=500:mbd=2:mv0:v4mv:trell:cbp:last_pred=3:dia=4:cmp=6:vb_strategy=1:对lavc进行一些设置,详细介绍如下:


-vf scale=512:-3:-vf表示视频格式,scale是缩放,512:-3表示强制将宽度设置为512,高度写为-3表示保持高宽比,也可以设置为 -1或-2,具体表示什么,有兴趣的可以尝试一下。如果要强制转化为统一大小,可以直接写-vf scale=640:480,但笔者个人建议用-3来保持高宽比。-vf里还有expand和crop参数,例如:-vf scale=512:384,expand=512:384:::1,crop=512:384:0:0,expand表示膨胀,crop表示裁剪;

-ofps 12:输出视频的帧频,一般,用于flash播放的视频帧频高了没有没有意义,反而会增加视频文件大小,但如果ofps设置的不合适,比如源视频帧频不是 ofps的整数倍,可能会导致转换后的视频、音频不同步,似乎可以将这一参数改为-noskip来解决这一问题;

-srate 22050:音频采样率一般为22050或44100。

     对于转换flv格式,lavsopts的设置比较重要,还有很多参数本文没有涉及到,在笔者参考的文献中会有具体的说明,感兴趣的可以去看一下。我对于 Mencoder的认识主要也是来源于下面2篇文章,实践的比较少,如果有理解和翻译的失误,再次欢迎与我交流。


《Linux Reviews》http://linuxreviews.org/man/mencoder/

开始菜单 -> 运行 -> cmd -> 回车,就打开了命令行窗口
mencoder “D:\music\sk8ter_boi_300.wmv” -o “D:\output.flv” -of lavf -oac mp3lame -lameopts abr:br=56 -ovc lavc -lavcopts vcodec=flv:vbitrate=150:mbd=2:mv0:trell:v4mv:cbp:last_pred=3 -srate 22050
按下回车后,如果你看到显示:“mencoder 不是内部或外部命令,也不是可运行的程序,或批处理文件”,那么说明环境变量没有设置好
Pos: 226.8s 297f (100%) 48fps Trem: 0min 5mb a-v:-0.009 [142:56]
Video stream: 142.564 kbit/s (17820 B/s) size: 4046677 bytes 227.080 secs 2700 frames
Audio stream: 56.938 kbit/s (7117 B/s) size: 1616197 bytes 227.082 secs
这2 行信息我想大家都能明白,其中我一直关注的是那个142.564kbit/s,用过flash8自带转换工具的应该知道高级设置里有个选项是最大数据速 率,当选中中等画质的时候,是400kb/s,而低品质也是150kb/s,也就是说,用那句命令转换的视频,其画质都不如品质的,那么,品质怎么样呢? 看一下,怎么看flv文件?别忘了我们有万能播放器mplayer,哈哈,直接在命令行里输入:
mplayer “d:\output.flv”,看到咱们刚刚转好的视频,我当时一看,画面上马赛克倒是没有,全是瓷砖,我晕倒…
mencoder “D:\music\sk8ter_boi_300.wmv” -o “D:\output.flv” -of lavf -oac mp3lame -lameopts abr:br=56 -ovc lavc -lavcopts vcodec=flv:vbitrate=150:mbd=2:mv0:trell:v4mv:cbp:last_pred=3 -srate 22050。
mencoder 说明你用的是mencoder;
“d:\…..wmv” -> 是指你的输入视频;
-o -> 后面指定输出路径;(前面有“-”的都是option(选项的意思))
-of -> 大概是output format的缩写,输出文件格式,咦!为什么不是flv,而是lavf?lavf表示你使用了libavcodec里的格式,flv正好是libavcodec里的,呵呵;
-oac -> 大概是output audio codec的缩写,指定输出音频编码,这儿选用的是mp3lame;
-lameopts -> 指定lame的options,就是设置音频输出的一些参数啦,我只关心视频,跳过
-ovc -> 大概是output video codec的缩写,制定输出视频编码(我最关心的好像要上场了),选用的lavc,什么意思?说是用了libavcodec的编码器;
-lavcopts -> 是lavc的options,要设置视频编码的参数了!(心跳加速,血压升高,口中开始大量分泌唾液),看看它后面都有什么:
codec=flv 说的是用的flv编码器,这个咱不理;
vbitrate=150 video bit rate!视频数据速率!就是它了!原来我设的是150啊!
mencoder “D:\music\APerfectMatch.wmv” -o “D:\output.flv” -of lavf -oac mp3lame -lameopts abr:br=56 -ovc lavc -lavcopts vcodec=flv:vbitrate=500:mbd=2:mv0:trell:v4mv:cbp:last_pred=3:dia=4:cmp=6:vb_strategy=1 -vf scale=320:240,expand=320:240:::1,crop=320:240:0:0 -ofps 30 -srate 22050
mencoder “D:\music\APerfectMatch.wmv” -o “D:\output.flv” -of lavf -oac mp3lame -lameopts abr:br=56 -ovc lavc -lavcopts vcodec=flv:vbitrate=500:mbd=2:mv0:trell:v4mv:cbp:last_pred=3 -sws 3 -vf scale=320:240,expand=320:240:::1,crop=320:240:0:0 -ofps 30 -srate 22050
只是加一个 -sws 3进去,转换后的效果和前面一种方法大致相同,视频数据速率都是422.5kb/s左右,解释一下


第一步骤: 在线转换

Set Executor = Server.CreateObject(“ASPExec.Execute”)
Executor.Application = “cmd /c mencoder E:\qiancheng\upload\”&request.QueryString(“keys”)&” -o E:\qiancheng\shipin\record\streams\_definst_\record\”&lid&”\”&keys&”.flv -of lavf -oac mp3lame -lameopts abr:br=56 -ovc lavc -lavfopts i_certify_that_my_video_stream_does_not_use_b_frames -lavcopts vcodec=flv:vbitrate=200:mbd=2:mv0:v4mv:last_pred=3:dia=3:cmp=3:vb_strategy=1 -vf scale=330:-3 -ofps 12 -srate 22050″
Executor.Parameters = “”
strResult = Executor.ExecuteDosApp

asp执行 .bat文件

第二步骤: 通过ffmpeg生成所略图+fso 删除源件

imgW =”120″
imgY = “90”
imgQuality = “100”
newName = “../upload/”&flvname&”.jpg”
str=str+” -i “&server.mappath(streamPath)&” -ss 3 -vframes 1 -r 1 -ac 1 -ab 2 -s 120*90 -f image2 “&server.mappath(newName)&””
Set shellffmpeg=server.CreateObject(“ffmpeg.shellffmpeg”)
Set shellffmpeg = Nothing
set   fso=server.CreateObject(“scripting.filesystemobject”)   
if fso.FileExists(Server.MapPath(tupianid))   then   
end if   
set fso=nothing

flash视频整站程序制作完成, 在线录制视频+音频+ 缩略图+在线转flv +asp + sqlserver

Unique Skill

1           What is transient variable?

Transient variable can’t be serialize. For example if a variable is declared as transient in a Serializable class and the class is written to an ObjectStream, the value of the variable can’t be written to the stream instead when the class is retrieved from the ObjectStream the value of the variable becomes null.


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

Containers which use Border Layout as their default ones are, window, Frame and Dialog classes.


3           What do you understand by Synchronization?

Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object’s value. Synchronization prevents such type of data corruption.


E.g. Synchronizing a function:

public synchronized void Method1 () {

     // Appropriate method-related code.



E.g. Synchronizing a block of code inside a function:

public myFunction (){

    synchronized (this) {

            // Synchronized code here.




4           What is Collection API?

The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces.














5           Is Iterator a Class or Interface? What is its use?

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


6           What is similarities/difference between an Abstract class and Interface?

6.1          Similarities

6.1.1     They can be used to implement the polymorphism.

6.1.2     Both of them can not be instantiated.

6.2          Differences

6.2.1     Interface can be used to implement the multiple inheritances while the abstract can not. Because the Java only provides the single inheritance.

6.2.2     There is no implementation in the interfaces. But in abstract class, you can implement some common logic.

6.2.3     In interface, there can be only public methods and public static fields.

6.2.4     The efficiency with interface is lower than abstract class. (If it refer to the  overrode function)


7           How to define an Interface?

7In Java Interface defines the methods but does not implement them. Interface can include constants. A class that implements the interfaces is bound to implement all the methods defined in Interface.

Emaple of Interface:


public interface sampleInterface {

    public void functionOne();


    public static long CONSTANT_ONE = 1000;



8           Explain the user defined Exceptions?

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



class myCustomException extends Exception {

     // The class simply has to exist to be an exception



9           Explain the new Features of JDBC 2.0 Core API?

The JDBC 2.0 API includes the complete JDBC API, which includes both core and Optional Package API, and provides inductrial-strength database computing capabilities.


New Features in JDBC 2.0 Core API:

9.1          Scrollable result sets – using new methods in the ResultSet interface allows programmatically move the to particular row or to a position relative to its current position. The methods is ResultSet.relative(…).

9.2          JDBC 2.0 Core API provides the Batch Updates functionality to the java applications.

9.3          Java applications can now use the ResultSet.updateXXX methods.

9.4          New data types – interfaces mapping the SQL3 data types

9.5          Custom  mapping of user-defined types (UTDs)

9.6          Miscellaneous features, including performance hints, the use of character streams, full precision for java.math.BigDecimal values, additional security, and support for time zones in date, time, and timestamp values. 


10       Explain garbage collection?

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


11       How you can force the garbage collection?

Garbage collection automatic process and can’t be forced. 


12       What is OOPS?

OOP is the common abbreviation for Object-Oriented Programming.  


13       Describe the principles of OOPS.

There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation. 


14       Explain the Encapsulation principle.

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


15       Explain the Inheritance principle.

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


16       Explain the Polymorphism principle.

16.1       One name many forms.

16.2       One interface multiple implementations.


The meaning of Polymorphism is something like one name many forms. Polymorphism enables one entity to be used as as general category for different types of actions. The specific action is determined by the exact nature of the situation. The concept of polymorphism can be explained as “one interface, multiple methods”. 


17       Explain the different forms of Polymorphism.

From a practical programming viewpoint, polymorphism exists in three distinct forms in



Method overloading

Method overriding through inheritance

Method overriding through the Java interface


18       Access specifiers are keywords that determine the type of access to the member of a class.






19       Describe the wrapper classes in Java.

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

Following table lists the primitive types and the corresponding wrapper classes:























20       Read the following program:

public class test {

public static void main(String [] args) {

    int x = 3;

    int y = 1;

   if (x = y)

     System.out.println(“Not equal”);






What is the result?

   A. The output is “Equal”

   B. The output in “Not Equal”

   C. An error at ” if (x = y)” causes compilation to fall.

   D. The program executes but no output is show on console.


Answer: C


21       what is the class variables ?

When we create a number of objects of the same class, then each object will share a common copy of variables. That means that there is only one copy per class, no matter how many objects are created from it. Class variables or static variables are declared with the static keyword in a class, but mind it that it should be declared outside outside a class. These variables are stored in static memory. Class variables are mostly used for constants, variable that never change its initial value. Static variables are always called by the class name. This variable is created when the program starts i.e. it is created before the instance is created of class by using new operator and gets destroyed when the programs stops. The scope of the class variable is same a instance variable. The class variable can be defined anywhere at class level with the keyword static. It initial value is same as instance variable. When the class variable is defined as int then it’s initial value is by default zero, when declared boolean its default value is false and null for object references. Class variables are associated with the class, rather than with any object. 


22       What is the difference between the instanceof and getclass, these two are same or not ?

Instanceof is a operator, not a function while getClass is a method of java.lang.Object class. Consider a condition where we use


if(o.getClass().getName().equals(“java.lang.Math”)){ }


This method only checks if the classname we have passed is equal to java.lang.Math. The class java.lang.Math is loaded by the bootstrap ClassLoader. This class is an abstract class.This class loader is responsible for loading classes. Every Class object contains a reference to the ClassLoader that defines. getClass() method returns the runtime class of an object. It fetches the java instance of the given fully qualified type name. The code we have written is not necessary, because we should not compare getClass.getName(). The reason behind it is that if the two different class loaders load the same class but for the JVM, it will consider both classes as different classes so, we can’t compare their names. It can only gives the implementing class but can’t compare a interface, but instanceof operator can.


The instanceof operator compares an object to a specified type. We can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface. We should try to use instanceof operator in place of getClass() method. Remember instanceof opeator and getClass are not same. Try this example, it will help you to better understand the difference between the two.


Interface one{


Class Two implements one {


Class Three implements one {



public class Test {

public static void main(String args[]) {

One test1 = new Two();

One test2 = new Three();

System.out.println(test1 instanceof one); //true

System.out.println(test2 instanceof one); //true

System.out.println(Test.getClass().equals(test2.getClass())); //false




23       Is “abc” a primitive value?

The String literal “abc” is not a primitive value. It is a String object.


24       What restrictions are placed on the values of each case of a switch statement?

During compilation, the values of each case of a switch statement must evaluate to a value     that can be promoted to an int value.


25       What modifiers may be used with an interface declaration? –

An interface may be declared as public or abstract.


26       What is the difference between a while statement and a do statement?

A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once.


27       What modifiers can be used with a local inner class?

A local inner class may be final or abstract.


28       What is the purpose of the File class?

The File class is used to create objects that provide access to the files and directories of a local file system.


29       Can an exception be rethrown?

Yes, an exception can be rethrown.


30       When does the compiler supply a default constructor for a class?

The compiler supplies a default constructor for a class if no other constructors are provided.


31       If a method is declared as protected, where may the method be accessed?

A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared.


32       Which non-Unicode letter characters may be used as the first character of an identifier?

The non-Unicode letter characters $ and _ may appear as the first character of an identifier


33       What restrictions are placed on method overloading?

Two methods may not have the same name and argument list but different return types.


34       What is casting?

There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.


35       What is the return type of a program’s main() method?

A program’s main() method has a void return type.


36       What class of exceptions are generated by the Java run-time system?

The Java runtime system generates RuntimeException and Error exceptions.


37       What class allows you to read objects directly from a stream?

The ObjectInputStream class supports the reading of objects from input streams.


38       What is the difference between a field variable and a local variable?

A field variable is a variable that is declared as a member of a class. A local variable is a variable that is declared local to a method.


39       How are this() and super() used with constructors?

this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.


40       What is the relationship between a method’s throws clause and the exceptions that can be thrown during the method’s execution?

A method’s throws clause must declare any checked exceptions that are not caught within the body of the method.


41       Why are the methods of the Math class static?

So they can be invoked as if they are a mathematical code library.


42       What are the legal operands of the instanceof operator?

The left operand is an object reference or null value and the right operand is a class, interface, or array type.


43       What are E and PI?

E is the base of the natural logarithm and PI is mathematical value pi. They are defined in the Math class.


44       Are true and false keywords?

The values true and false are not keywords. Both are the constant values like 0, 1, 2.


45       What is the difference between the File and RandomAccessFile classes?

The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.


46       What happens when you add a double value to a String?

The result is a String object.


47       What is your platform’s default character encoding?

If you are running Java on English Windows platforms, it is probably Cp1252. If you are running Java on English Solaris platforms, it is most likely 8859_1.


48       Which package is always imported by default?

The java.lang package is always imported by default.


49       What interface must an object implement before it can be written to a stream as an object?

An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.


50       How can my application get to know when a HttpSession is removed?

Define a Class HttpSessionNotifier which implements HttpSessionBindingListener and implement the functionality what you need in valueUnbound() method. Create an instance of that class and put that instance in HttpSession.


51       What’s the difference between notify() and notifyAll()?

notify() is used to unblock one waiting thread; notifyAll() is used to unblock all of them. Using notify() is preferable (for efficiency) when only one blocked thread can benefit from the change (for example, when freeing a buffer back into a pool). notifyAll() is necessary (for correctness) if multiple threads should resume (for example, when releasing a “writer” lock on a file might permit all “readers” to resume).


52       Why can’t I say just abs() or sin() instead of Math.abs() and Math.sin()?

The import statement does not bring methods into your local name space. It lets you abbreviate class names, but not get rid of them altogether. That’s just the way it works, youll get used to it. It’s really a lot safer this way.


However, there is actually a little trick you can use in some cases that gets you what you want. If your top-level class doesn’t need to inherit from anything else, make it inherit from java.lang.Math. That *does* bring all the methods into your local name space. But you can’t use this trick in an applet, because you have to inherit from java.awt.Applet. And actually, you can’t use it on java.lang.Math at all, because Math is a “final” class which means it can’t be extended.


53       Why are there no global variables in Java?

Global variables are considered bad form for a variety of reasons: Adding state variables breaks referential transparency (you no longer can understand a statement or expression on its own: you need to understand it in the context of the settings of the global variables), State variables lessen the cohesion of a program: you need to know more to understand how something works. A major point of Object-Oriented programming is to break up global state into more easily understood collections of local state, When you add one variable, you limit the use of your program to one instance. What you thought was global, someone else might think of as local: they may want to run two copies of your program at once. For these reasons, Java decided to ban global variables.


54       What does it mean that a class or member is final?

A final class can no longer be subclassed. Mostly this is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. Methods may be declared final as well. This means they may not be overridden in a subclass. Fields can be declared final, too. However, this has a completely different meaning. A final field cannot be changed after it’s initialized, and it must include an initializer statement where it’s declared. For example, public final double c = 2.998; It’s also possible to make a static field final to get the effect of C++’s const statement or some uses of C’s #define, e.g. public static final double c = 2.998;


55       What does it mean that a method or class is abstract?

An abstract class cannot be instantiated. Only its subclasses can be instantiated. You indicate that a class is abstract with the abstract keyword like this:

public abstract class Container extends Component {

Abstract classes may contain abstract methods. A method declared abstract is not actually implemented in the current class. It exists only to be overridden in subclasses. It has no body. For example,

public abstract float price();

Abstract methods may only be included in abstract classes. However, an abstract class is not required to have any abstract methods, though most of them do. Each subclass of an abstract class must override the abstract methods of its superclasses or itself be declared abstract.


56       What is a transient variable?

Transient variable is a variable that may not be serialized.


57       How are Observer and Observable used?

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


58       Can a lock be acquired on a class?

Yes, a lock can be acquired on a class. This lock is acquired on the class’s Class object.


59       What state does a thread enter when it terminates its processing?

When a thread terminates its processing, it enters the dead state.



60       What is the difference between the >> and >>> operators?

The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out.


61       Is sizeof a keyword?

The sizeof operator is not a keyword.


62       Does garbage collection guarantee that a program will not run out of memory?

Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection


63       Can an object’s finalize() method be invoked while it is reachable?

An object’s finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an object’s finalize() method may be invoked by other objects.

64       What value does readLine() return when it has reached the end of a file?

The readLine() method returns null when it has reached the end of a file.


65       Can a for statement loop indefinitely?

Yes, a for statement can loop indefinitely. For example, consider the following: for($$) ;


66       To what value is a variable of the String type automatically initialized?

The default value of an String type is null.


67       What is a task’s priority and how is it used in scheduling?

A task’s priority is an integer value that identifies the relative order in which it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks. Please see the method public final void setPriority(int newPriority) in class Thread.


68       What is the range of the short type?

The range of the short type is -(2^15) to 2^15 – 1.


69       What is the purpose of garbage collection?

The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources may be reclaimed and reused.


70       What do you understand by private, protected and public?

These are accessibility modifiers. Private is the most restrictive, while public is the least restrictive. There is no real difference between protected and the default type (also known as package protected) within the context of the same package, However the protected keyword allows visibility to a derived class in a different package.


71       What is Downcasting?

Downcasting is the casting from a general to a more specific type, i.e. casting down the hierarchy


72       Can a method be overloaded based on different return type but same argument type ?

No, because the methods can be called without using their return type in which case there is ambiquity for the compiler


73       What happens to a static var that is defined within a method of a class ?

Can’t do it. You’ll get a compilation error


74       How many static init can you have ?

As many as you want, but the static initializers and class variable initializers are executed in textual order and may not refer to class variables declared in the class whose declarations appear textually after the use, even though these class variables are in scope.


75       What is the difference amongst JVM Spec, JVM Implementation, JVM Runtime ?

The JVM spec is the blueprint for the JVM generated and owned by Sun. The JVM implementation is the actual implementation of the spec by a vendor and the JVM runtime is the actual running instance of a JVM implementation


76       Describe what happens when an object is created in Java?

Several things happen in a particular order to ensure the object is constructed properly: Memory is allocated from heap to hold all instance variables and implementation-specific data of the object and its superclasses. Implemenation-specific data includes pointers to class and method data. The instance variables of the objects are initialized to their default values. The constructor for the most derived class is invoked. The first thing a constructor does is call the consctructor for its superclasses. This process continues until the constrcutor for java.lang.Object is called, as java.lang.Object is the base class for all objects in java. Before the body of the constructor is executed, all instance variable initializers and initialization blocks are executed. Then the body of the constructor is executed. Thus, the constructor for the base class completes first and constructor for the most derived class completes last.


77       Why does it take so much time to access an Applet having Swing Components the first time?

Because behind every swing component are many Java objects and resources. This takes time to create them in memory. JDK 1.3 from Sun has some improvements which may lead to faster execution of Swing applications.


78       What is Action Class?

78The Action is part of the controller. The purpose of Action Class is to translate the HttpServletRequest to the business logic. To use the Action, we need to  Subclass and overwrite the execute()  method. The ActionServlet (commad) passes the parameterized class to Action Form using the execute() method. There should be no database interactions in the action. The action should receive the request, call business objects (which then handle database, or interface with J2EE, etc) and then determine where to go next. Even better, the business objects could be handed to the action at runtime (IoC style) thus removing any dependencies on the model.   The return type of the execute method is ActionForward which is used by the Struts Framework to forward the request to the file as per the value of the returned ActionForward object.


79       Write code of any Action Class?

79 Here is the code of Action Class that returns the ActionForward object.




package roseindia.net;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class TestAction extends Action
  public ActionForward execute(
    ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response) throws Exception{
      return mapping.findForward(“testAction”);


80       What is ActionForm?

80An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm. ActionForm maintains the session state for web application and the ActionForm object is automatically populated on the server side with data entered from a form on the client side.


81       What is Struts Validator Framework?

81Struts Framework provides the functionality to validate the form data. It can be use to validate the data on the users browser as well as on the server side. Struts Framework emits the java scripts and it can be used validate the form data on the client browser. Server side validation of form can be accomplished by sub classing your From Bean with DynaValidatorForm class. 


The Validator framework was developed by David Winterfeldt as third-party add-on to Struts. Now the Validator framework is a part of Jakarta Commons project and it can be used with or without Struts. The Validator framework comes integrated with the Struts Framework and can be used without doing any extra settings.


82       Give the Details of XML files used in Validator Framework?

The Validator Framework uses two XML configuration files validator-rules.xml and validation.xml. The validator-rules.xml defines the standard validation routines, these are reusable and used in validation.xml. to define the form specific validations. The validation.xml defines the validations applied to a form bean.


83       How you will display validation fail errors on jsp page?

83Following tag displays all the errors:



84       How you will enable front-end validation based on the xml in validation.xml?

84The <html:javascript> tag to allow front-end validation based on the xml in validation.xml. For  example the code: <html:javascript formName=”logonForm” dynamicJavascript=”true” staticJavascript=”true” /> generates the client side java script for the form “logonForm” as defined in the validation.xml file. The <html:javascript> when added in the jsp file generates the client site validation script.


85       What is RequestProcessor and RequestDispatcher?

The controller is responsible for intercepting and translating user input into actions to be performed by the model. The controller is responsible for selecting the next view based on user input and the outcome of model operations. The Controller receives the request from the browser, invoke a business operation and coordinating the view to return to the client.

The controller is implemented by a java servlet, this servlet is centralized point of control for the web application. In struts framework the controller responsibilities are implemented by several different components like

The ActionServlet Class
The RequestProcessor Class
The Action Class

The ActionServlet extends the javax.servlet.http.httpServlet class. The ActionServlet class is not abstract and therefore can be used as a concrete controller by your application.
The controller is implemented by the ActionServlet class. All incoming requests are mapped to the central controller in the deployment descriptor as follows.


All request URIs with the pattern *.do are mapped to this servlet in the deployment descriptor as follows.


A request URI that matches this pattern will have the following form.


The preceding mapping is called extension mapping, however, you can also specify path mapping where a pattern ends with /* as shown below.



A request URI that matches this pattern will have the following form.
The class org.apache.struts.action.requestProcessor process the request from the controller. You can sublass the RequestProcessor with your own version and modify how the request is processed.

Once the controller receives a client request, it delegates the handling of the request to a helper class. This helper knows how to execute the business operation associated with the requested action. In the Struts framework this helper class is descended of org.apache.struts.action.Action class. It acts as a bridge between a client-side user action and business operation. The Action class decouples the client request from the business model. This decoupling allows for more than one-to-one mapping between the user request and an action. The Action class also can perform other functions such as authorization, logging before invoking business operation. the Struts Action class contains several methods, but most important method is the execute() method.

public ActionForward execute(ActionMapping mapping,
            ActionForm form, HttpServletRequest request, HttpServletResponse response)    throws Exception; 

The execute() method is called by the controller when a request is received from a client. The controller creates an instance of the Action class if one doesn
already exist. The strut framework will create only a single instance of each Action class in your application.

Action are mapped in the struts configuration file and this configuration is loaded into memory at startup and made available to the framework at runtime. Each Action element is represented in memory by an instance of the org.apache.struts.action.ActionMapping class . The ActionMapping object contains a path attribute that is matched against a portion of the URI of the incoming request.

        path= “/somerequest”
    <forward name=”Success” path=”/action/xys” redirect=”true”/>
   <forward name=”Failure” path=”/somejsp.jsp” redirect=”true”/>

Once this is done the controller should determine which view to return to the client. The execute method signature in Action class has a return type org.apache.struts.action.ActionForward class. The ActionForward class represents a destination to which the controller may send control once an action has completed. Instead of specifying an actual JSP page in the code, you can declaratively associate as action forward through out the application. The action forward are specified in the configuration file.

        path= “/somerequest”
    <forward name=”Success” path=”/action/xys” redirect=”true”/>
    <forward name=”Failure” path=”/somejsp.jsp” redirect=”true”/>

The action forward mappings also can be specified in a global section, independent of any specific action mapping.

    <forward name=”Success” path=”/action/somejsp.jsp” />
    <forward name=”Failure” path=”/someotherjsp.jsp” />

public interface RequestDispatcher

Defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server. The servlet container creates the RequestDispatcher object, which is used as a wrapper around a server resource located at a particular path or given by a particular name.
This interface is intended to wrap servlets, but a servlet container can create RequestDispatcher objects to wrap any type of resource.


public RequestDispatcher getRequestDispatcher(java.lang.String path)

Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path. A RequestDispatcher object can be used to forward a request to the resource or to include the resource in a response. The resource can be dynamic or static.
The pathname must begin with a “/” and is interpreted as relative to the current context root. Use getContext to obtain a RequestDispatcher for resources in foreign contexts. This method returns null if the ServletContext cannot return a RequestDispatcher.

    path – a String specifying the pathname to the resource 
    a RequestDispatcher object that acts as a wrapper for the resource at the specified path 
See Also:
    RequestDispatcher, getContext(java.lang.String)


public RequestDispatcher getNamedDispatcher(java.lang.String name)

Returns a RequestDispatcher object that acts as a wrapper for the named servlet.
Servlets (and JSP pages also) may be given names via server administration or via a web application deployment descriptor. A servlet instance can determine its name using ServletConfig.getServletName().
This method returns null if the ServletContext cannot return a RequestDispatcher for any reason.

    name – a String specifying the name of a servlet to wrap 
    a RequestDispatcher object that acts as a wrapper for the named servlet 
See Also:


86       Is struts threadsafe?Give an example?

86Struts is not only thread-safe but thread-dependant. The response to a request is handled by a light-weight Action object, rather than an individual servlet. Struts instantiates each Action class once, and allows other requests to be threaded through the original object. This core strategy conserves resources and provides the best possible throughput. A properly-designed application will exploit this further by routing related operations through a single Action.


87       Can we Serialize static variable?

Serialization is the process of converting a set of object instances that contain references to each other into a linear stream of bytes, which can then be sent through a socket, stored to a file, or simply manipulated as a stream of data. Serialization is the mechanism used by RMI to pass objects between JVMs, either as arguments in a method invocation from a client to a server or as return values from a method invocation. In the first section of this book, There are three exceptions in which serialization doesnot necessarily read and write to the stream.


These are,

1. Serialization ignores static fields, because they are not part of any particular object’s state.

2. Base class fields are only handled if the base class itself is serializable.

3. Transient fields. There are four basic things you must do when you are making a class serializable. They are,

Implement the Serializable interface.

Make sure that instance-level, locally defined state is serialized properly.

Make sure that superclass state is serialized properly.

Override equals( )and hashCode( ).


It is possible to have control over serialization process. The class should implement Externalizable interface. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process.


88       What are the uses of tiles-def.xml file, resourcebundle.properties file, validation.xml file?

tiles-def.xml is is an xml file used to configure tiles with the struts application. You can define the layout / header / footer / body content for your View.


The resourcebundle.properties file is used to configure the message (error/ other messages) for the struts applications.


The file validation.xml is used to declare sets of validations that should be applied to Form Beans.


89       What is the difference between perform() and execute() methods?

Perform method is the method which was deprecated in the Struts Version 1.1.  In Struts 1.x, Action.perform() is the method called by the ActionServlet. This is typically where your business logic resides, or at least the flow control to your JavaBeans and EJBs that handle your business logic. As we already mentioned, to support declarative exception handling, the method signature changed in perform. Now execute just throws Exception. Action.perform() is now deprecated; however, the Struts v1.1 ActionServlet is smart enough to know whether or not it should call perform or execute in the Action, depending on which one is available.


90       What are the various Struts tag libraries?

Struts is very rich framework and it provides very good and user friendly way to develop web application forms. Struts provide many tag libraries to ease the development of web applications. These tag libraries are:

1.1          Bean tag library – Tags for accessing JavaBeans and their properties.

1.2          HTML tag library – Tags to output standard HTML, including forms, text boxes, checkboxes, radio buttons etc..

1.3          Logic tag library – Tags for generating conditional output, iteration capabilities and flow management

1.4          Tiles or Template tag library – For the application using tiles

1.5          Nested tag library – For using the nested beans in the application


91       Can I setup Apache Struts to use multiple configuration files?

Yes Struts can use multiple configuration files. Here is the configuration example:















92       What are the disadvantages of Struts?

92Struts is very robust framework and is being used extensively in the industry. But there are some disadvantages of the Struts:

High Learning Curve

Struts requires lot of efforts to learn and master it. For any small project less experience developers could spend more time on learning the Struts.

Harder to learn

       Struts are harder to learn, benchmark and optimize.

The name of class is not proper.

The Action should not be a class.

The ActionForm is redundant.


93       What are the difference between <bean:message> and <bean:write>?

<bean:message>, This tag is used to output locale-specific text (from the properties files) from a MessageResources bundle.


<bean:write>, This tag is used to output property values from a bean. <bean:write> is a commonly used tag which enables the programmers to easily present the data.


94       What is LookupDispatchAction?

94An abstract Action that dispatches to the subclass mapped execute method. This is useful in cases where an HTML form has multiple submit buttons with the same name. The button name is specified by the parameter property of the corresponding ActionMapping.


95       What are the components of Struts?

Struts is based on the MVC design pattern. Struts components can be categoried into Model, View and Controller.

Model: Components like business logic / business processes and data are the part of Model.

View: JSP, HTML etc. are part of View

Controller: Action Servlet of Struts is part of Controller components which works as front controller to handle all the requests.


96       What do you understand by JSP Actions?

JSP actions are XML tags that direct the server to use existing components or control the behavior of the JSP engine. JSP Actions consist of a typical (XML-based) prefix of “jsp” followed by a colon, followed by the action name followed by one or more attribute parameters.


There are six JSP Actions:













97       What is the difference between <jsp:include page = … > and <%@ include file = … >?

Both the tag includes the information from one page in another. The differences are as follows:

<jsp:include page = … >: This is like a function call from one jsp to another jsp. It is executed ( the included page is executed  and the generated html content is included in the content of calling jsp) each time the client page is accessed by the client. This approach is useful to for modularizing the web application. If the included file changed then the new content will be included in the output.

<%@ include file = … >: In this case the content of the included file is textually embedded in the page that have <%@ include file=”..”> directive. In this case in the included file changes, the changed content will not included in the output. This approach is used when the code from one jsp file required to include in multiple jsp files.


98       What is the difference between <jsp:forward page = … > and      response.sendRedirect(url)?

The <jsp:forward> element forwards the request object containing the client request information from one JSP file to another file. The target file can be an HTML file, another JSP file, or a servlet, as long as it is in the same application context as the forwarding JSP file.

sendRedirect sends HTTP temporary redirect response to the browser, and browser creates a new request to go the redirected page. The  response.sendRedirect kills the session variables.


99       Identify the advantages of JSP over Servlet

a) Embedding of Java code in HTML pages

b) Platform independence

c) Creation of database-driven Web applications

d) Server-side programming capabilities


Answer:  a)


100    Write the following code for a JSP page:

<%@ page language = “java” %>







PrintWriter print = request.getWriter();







Suppose you access this JSP file, Find out your answer.

a) A blank page will be displayed.

b) A page with the text Welcome is displayed

c) An exception will be thrown because the implicit out object is not used

d) An exception will be thrown because PrintWriter can be used in servlets only


Answer, b)


101    What are implicit Objects available to the JSP Page?

Implicit objects are the objects available to the JSP page. These objects are created by Web container and contain information related to a particular request, page, or application. The JSP implicit objects are:







The context for the JSP page’s servlet and any Web components contained in the same application.



Initialization information for the JSP page’s servlet.



Accessible only from an error page.



The output stream.



The instance of the JSP page’s servlet processing the current request. Not typically used by JSP page authors.



The context for the JSP page. Provides a single API to manage the various scoped attributes.


Subtype of javax.servlet.ServletRequest

The request triggering the execution of the JSP page.


Subtype of javax.servlet.ServletResponse

The response to be returned to the client. Not typically used by JSP page authors.



The session object for the client.


102    What are all the different scope values for the <jsp:useBean> tag?

<jsp:useBean> tag is used to use any java object in the jsp page. Here are the scope values for <jsp:useBean> tag:

page, request, session and application


103    What is JSP Output Comments?

JSP Output Comments are the comments that can be viewed in the HTML source file.

(Will be outputted into the html source code)
<!– This file displays the user login screen –>
<!– This page was loaded on
<%= (new java.util.Date()).toLocaleString() %> –>


The following comments can not be viewed in html, so the servlet container ignores it.



<jsp:setProperty name=”user” property=”*” />

<jsp:setProperty name=”user” property=”modDate”

  value=”<%= new java.util.Date(  ) %>” />

<% boolean isValid = user.isValid(  ); %>




104    What types of comments are available in the JSP?

104There are two types of comments are allowed in the JSP. These are hidden and output comments. A hidden comments does not appear in the generated output in the html, while output comments appear in the generated output.


Example of hidden comment

<%– This is hidden comment –%>

Example of output comment

<!– This is output comment –>



105    What is expression in JSP?

Expression tag is used to insert Java values directly into the output. Syntax for the Expression tag is:

<%= expression %>

An expression tag contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. The following expression tag displays time on the output:

<%=new java.util.Date()%>


106    What is JSP declaration?

106JSP declarations are the JSP tags used to declare variables. Declaratives are enclosed in the <%! %> tag and ends in semi-colon. You declare variables and functions in the declaration tag and can use anywhere in the JSP. Here is the example of declaratives:



<%@page contentType=”text/html” %>

//JSP directive





int cnt=0;

private int getCount(){

//increment cnt and return the value


return cnt;



//JSP declaration


<p>Values of Cnt are:</p>



//JSP expression





107    What is JSP Scriptlet?

JSP Scriptlet is jsp tag which is used to enclose java code in the JSP pages. Scriptlets begins with <% tag and ends with %> tag. Java code written inside scriptlet executes every time the JSP is invoked.



       //java codes

       String userName = null;

       userName = request.getParameter(“userName”);



108    What are the life-cycle methods of JSP?

Life-cycle methods of the JSP are,

1.1          jspInit(), The container calls the jspInit() to initialize the servlet instance. It is called before any other method, and is called only once for a servlet instance.

1.2          jspService(), The container calls the _jspservice() for each request and it passes the request and the response objects. _jspService() method cann’t be overridden.

1.3          jspDestroy(), The container calls this when its instance is about to destroyed. The jspInit() and jspDestroy() methods can be overridden within a JSP page.


109    What are JSP Custom tags?

JSP Custom tags are user defined JSP language element. JSP custom tags are user defined tags that can encapsulate common functionality. For example you can write your own tag to access the database and performing database operations. You can also write custom tag for encapsulate both simple and complex behaviors in an easy to use syntax and greatly simplify the readability of JSP pages.


110    What is JSP?

110JavaServer Pages (JSP) technology is the Java platform technology for delivering dynamic content to web clients in a portable, secure and well-defined way. The JavaServer Pages specification extends the Java Servlet API to provide web application developers.


111    What is the role of JSP in MVC Model?

111JSP is mostly used to develop the user interface, It plays are role of View in the MVC Model.


112    What do you understand by context initialization parameters?

The context-param element contains the declaration of a web application’s servlet context initialization parameters.







The Context Parameters page lets you manage parameters that are accessed through the ServletContext.getInitParameterNames and ServletContext.getInitParameter methods.


113    Can you extend JSP technology?

113JSP technology lets the programmer to extend the jsp to make the programming more easier. JSP can be extended and custom actions and tag libraries can be developed.


114    What do you understand by JSP translation?

JSP translators generate standard Java code for a JSP page implementation class. This class is essentially a servlet class wrapped with features for JSP functionality.


115    What you can stop the browser to cash your page?

Instead of deleting a cache, you can force the browser not to catch the page.


response.setHeader(“pragma”,”no-cache”);//HTTP 1.1



response.addDateHeader(“Expires”, -1);

response.setDateHeader(“max-age”, 0);

//response.setIntHeader (“Expires”, -1); //prevents caching at the proxy server

response.addHeader(“cache-Control”, “private”);


put the above code in your page.


116    What will you handle the runtime exception in your jsp page?

The errorPage attribute of the page directive can be used to catch run-time exceptions automatically and then forwarded to an error processing page.


For example,

<%@ page errorPage=”customerror.jsp” %>

above code forwards the request to “customerror.jsp” page if an uncaught exception is encountered during request processing. Within “customerror.jsp”, you must indicate that it is an error-processing page, via the directive: <%@ page isErrorPage=”true” %>.


117    What is J2EE?

J2EE Stands for Java 2 Enterprise Edition. J2EE is an environment for developing and deploying enterprise applications. J2EE specification is defined by Sun Microsystems Inc. The J2EE platform is one of the best platform for the development and deployment of enterprise applications. The J2EE platform is consists of a set of services, application programming interfaces (APIs), and protocols, which provides the functionality necessary for developing multi-tiered, web-based applications.


118    What do you understand by a J2EE module?

A J2EE module is a software unit that consists of one or more J2EE components of the same container type along with one deployment descriptor of that type. J2EE specification defines four types of modules:

a) EJB

b) Web

c) Application client and

d) Resource adapter


In the J2EE applications modules can be deployed as stand-alone units. Modules can also be assembled into J2EE applications.


119    Tell me something about J2EE component?

J2EE component is a self-contained functional software unit supported by a container and configurable at deployment time. The J2EE specification defines the following J2EE components,

119.1   Application clients and applets are components that run on the client.

119.2   Java servlet and JavaServer Pages (JSP) technology components are Web components that run on the server.

119.3   Enterprise JavaBeans (EJB) components (enterprise beans) are business components that run on the server. J2EE components are written in the Java programming language and are compiled in the same way as any program in the language. The difference between J2EE components and “standard” Java classes is that J2EE components are assembled into a J2EE application, verified to be well formed and in compliance with the J2EE specification, and deployed to production, where they are run and managed by the J2EE server or client container.


120    What are the contents of web module?

120A web module may contain:

120.1   JSP files

120.2   Java classes

120.3   gif and html files and

120.4   web component deployment descriptors


121    Differentiate between .ear,  .jar and .war files.

These files are simply zipped file using java jar tool. These files are created for different purposes. Here is the description of these files:

.jar files: These files are with the .jar extenstion. The .jar files contains the libraries, resources and accessories files like property files.

.war files: These files are with the .war extension. The war file contains the web application that can be deployed on the any servlet/jsp container. The .war file contains jsp, html, javascript and other files for necessary for the development of web applications.

.ear files: The .ear file contains the EJB modules of the application.


122    What is the difference between Session Bean and Entity Bean?

Session is one of the EJBs and it represents a single client inside the Application Server. Stateless session is easy to develop and its efficient. As compare to entity beans session beans require few server resources.


A session bean is similar to an interactive session and is not shared; it can have only one client, in the same way that an interactive session can have only one user. A session bean is not persistent and it is destroyed once the session terminates.


An entity bean represents persistent global data from the database. Entity beans data are stored into database.


123    Why J2EE is suitable for the development distributed multi-tiered enterprise applications?

The J2EE platform consists of multi-tiered distributed application model. J2EE applications allows the developers to design and implement the business logic into components according to business requirement. J2EE architecture allows the development of multi-tired applications and the developed applications can be installed on different machines depending on the tier in the multi-tiered J2EE environment . The J2EE application parts are:


123.1   Client-tier components run on the client machine.

123.2   Web-tier components run on the J2EE server.

123.3   Business-tier components run on the J2EE server and the

123.4   Enterprise information system (EIS)-tier software runs on the EIS servers


124    Why do understand by a container?

Normally, thin-client multi-tiered applications are hard to write because they involve many lines of intricate code to handle transaction and state management, multithreading, resource pooling, and other complex low-level details. The component-based and platform-independent J2EE architecture makes J2EE applications easy to write because business logic is organized into reusable components. In addition, the J2EE server provides underlying services in the form of a container for every component type. Because you do not have to develop these services yourself, you are free to concentrate on solving the business problem at hand.


In short containers are the interface between a component and the low-level platform specific functionality that supports the component. The application like Web, enterprise bean, or application client component must be assembled and deployed on the J2EE container before executing.


125    What are the services provided by a container?

The services provided by container are as follows:

125.1   Transaction management for the bean

125.2   Security for the bean

125.3   Persistence of the bean

125.4   Remote access to the bean

125.5   Lifecycle management of the bean

125.6   Database-connection pooling

125.7   Instance pooling for the bean


126    What are types of J2EE clients?

J2EE clients are the software that accesses the services components installed on the J2EE container. Following are the J2EE clients:

a) Applets

b) Java-Web Start clients

c) Wireless clients

d) Web applications


127    What is Deployment Descriptor?

A deployment descriptor is simply an XML(Extensible Markup Language) file with the extension of .xml. Deployment descriptor describes the component deployment settings. Application servers reads the deployment descriptor to deploy the components contained in the deployment unit. For example ejb-jar.xml file is used to describe the setting of the EJBs.


128    What do you understand by JTA and JTS?

JTA stands for Java Transaction API and JTS stands for Java Transaction Service. JTA provides a standard interface which allows the developers to demarcate transactions in a manner that is independent of the transaction manager implementation. The J2EE SDK uses the JTA transaction manager to implement the transaction. The code developed by developers does not call the JTS methods directly, but only invokes the JTA methods. Then JTA internally invokes the JTS routines. JTA is a high level transaction interface used by the application code to control the transaction.


129    What is the difference between JTS and JTA?

In any J2EE application transaction management is one of the most crucial requirements of the application. Given the complexity of today’s business requirements, transaction processing occupies one of the most complex segments of enterprise level distributed applications to build, deploy and maintain.  JTS specifies the implementation of a Java transaction manager. JTS specifies the implementation of a Transaction Manager which supports the Java Transaction API (JTA) 1.0 This transaction manager supports the JTA, using which application servers can be built to support transactional Java applications. Internally the JTS implements the Java mapping of the OMG OTS 1.1 specifications. The Java mapping is specified in two packages: org.omg.CosTransactions and org.omg.CosTSPortability. The JTS thus provides a new architecture for transactional application servers and applications, while complying to the OMG OTS 1.1 interfaces internally. This allows the JTA compliant applications to interoperate with other OTS 1.1 complaint applications through the standard IIOP. Java-based applications and Java-based application servers access transaction management functionality via the JTA interfaces. The JTA interacts with a transaction management implementation via JTS. Similarly, the JTS can access resources via the JTA XA interfaces or can access OTS-enabled non-XA resources. JTS implementations can interoperate via CORBA OTS interfaces.


The JTA specifies an architecture for building transactional application servers and defines a set of interfaces for various components of this architecture. The components are: the application, resource managers, and the application server. The JTA specifies standard interfaces for Java-based applications and application servers to interact with transactions, transaction managers, and resource managers JTA transaction management provides a set of interfaces utilized by an application server to manage the beginning and completion of transactions. Transaction synchronization and propagation services are also provided under the domain of transaction management.


In the Java transaction model, the Java application components can conduct transactional operations on JTA compliant resources via the JTS. The JTS acts as a layer over the OTS. The applications can therefore initiate global transactions to include other OTS transaction managers, or participate in global transactions initiated by other OTS compliant transaction managers.


130    What is JAXP?

The Java API for XML Processing (JAXP) enables applications to parse and transform XML documents independent of a particular XML processing implementation. JAXP or Java API for XML Parsing is an optional API provided by Javasoft. It provides basic functionality for reading, manipulating, and generating XML documents through pure Java APIs. It is a thin and lightweight API that provides a standard way to seamlessly integrate any XML-compliant parser with a Java application.


131    What is J2EE Connector architecture?

131J2EE Connector Architecture (JCA) is a Java-based technology solution for connecting application servers and enterprise information systems (EIS) as part of enterprise application integration (EAI) solutions. While JDBC is specifically used to connect Java EE applications to databases, JCA is a more generic architecture for connection to legacy systems (including databases). JCA was developed under the Java Community Process as JSR 16 (JCA 1.0) and JSR 112 (JCA 1.5). As of 2006, the current version of JCA is version 1.5. The J2EE Connector API is used by J2EE tools developers and system integrators to create resource adapters.


132    What is difference between Java Bean and Enterprise Java Bean?

Java Bean as is a plain java class with member variables and getter setter methods. Java Beans are defined under JavaBeans specification as Java-Based software component model which includes the features like introspection, customization, events, properties and  persistence.

Enterprise JavaBeans or EJBs for short are Java-based software components that comply with Java’s EJB specification. EJBs are delpoyed on the EJB container and executes in the EJB container. EJB is not that simple, it is used for building distributed applications. Examples of EJB are Session Bean, Entity Bean and Message Driven Bean. EJB is used for server side programming whereas java bean is a client side. Bean is only development but the EJB is developed and then deploy on EJB Container.


133    Can Entity Beans have no create() methods?

Entity Beans can have no create() methods. Entity Beans have no create() method, when entity bean is not used to store the data in the database. In this case entity bean is used to retrieve the data from database.


134    What are the call back methods in Session bean?

Callback methods are called by the container to notify the important events to the beans in its life cycle. The callback methods are defined in the javax.ejb.EntityBean interface. The callback methods example are ejbCreate(), ejbPassivate() and ejbActivate().


135    What is bean managed transaction?

In EJB transactions can be maintained by the container or developer can write own code to maintain the transaction. If a developer doesn want a Container to manage transactions, developer can write own code to maintain the database transaction.


136    What are transaction isolation levels in EJB?

There are four levels of transaction isolation are:

* Uncommitted Read

* Committed Read

* Repeatable Read

* Serializable


The four transaction isolation levels and the corresponding behaviors are described below,


Isolation Level

Dirty Read

Non-Repeatable Read

Phantom Read

Read Uncommitted




Read Committed

Not possible



Repeatable Read

Not possible

Not possible



Not possible

Not possible

Not possible


137    Can a private method of a superclass be declared within a subclass?

Sure. A private field or method or inner class belongs to its declared class and hides from its subclasses. There is no way for private stuff to have a runtime overloading or overriding (polymorphism) features.


138    Why Java does not support multiple inheritence ?

Java does support multiple inheritance via interface implementation.


139    What is the difference between final, finally and finalize?

139.1   final – declare constant

139.2   finally – handles exception

139.3   finalize – helps in garbage collection


140    Where and how can you use a private constructor.

Private constructor can be used if you do not want any other class to instanstiate the object , the instantiation is done from a static public method, this method is used when dealing with the factory method pattern when the designer wants only one controller (fatory method ) to create the object.


141    In System.out.println(),what is System,out and println,pls explain?

System is a predefined final class,out is a PrintStream object and println is a built-in overloaded method in the out object.


142    What is meant by “Abstract Interface”?

First, an interface is abstract. That means you cannot have any implementation in an interface. All the methods declared in an interface are abstract methods or signatures of the methods.


143    Can you make an instance of an abstract class? For example – java.util.Calender is an abstract class with a method getInstance() which returns an instance of the Calender class.

No! You cannot make an instance of an abstract class. An abstract class has to be sub-classed. If you have an abstract class and you want to use a method which has been implemented, you may need to subclass that abstract class, instantiate your subclass and then call that method.


144    What is the output of x<y? a:b = p*q when x=1,y=2,p=3,q=4?

When this kind of question has been asked, find the problems you think is necessary to ask before you give an answer. Ask if variables a and b have been declared or initialized. If the answer is yes. You can say that the syntax is wrong. If the statement is rewritten as: x<y? a:(b=p*q); the return value would be variable a because the x is 1 and less than y = 2; the x < y statement return true and variable a is returned.


145    What is the difference between Swing and AWT components?

AWT components are heavy-weight, whereas Swing components are lightweight. Heavy weight components depend on the local windowing toolkit. For example, java.awt.Button is a heavy weight component, when it is running on the Java platform for Unix platform, it maps to a real Motif button.


146    Why does Java not support pointers?

Because pointers are unsafe. Java uses reference types to hide pointers and programmers feel easier to deal with reference types without pointers. This is why Java and C# shine.


147    Parsers? DOM vs SAX parser

Parsers are fundamental xml components, a bridge between XML documents and applications that process that XML. The parser is responsible for handling xml syntax, checking the contents of the document against constraints established in a DTD or Schema.


148    What is a platform?

A platform is the hardware or software environment in which a program runs. Most platforms can be described as a combination of the operating system and hardware, like Windows 2000/XP, Linux, Solaris, and MacOS.


149    What is the main difference between Java platform and other platforms?

The Java platform differs from most other platforms in that it’s a software-only platform that runs on top of other hardware-based platforms. The Java platform has two components:


149.1   The Java Virtual Machine (Java VM)

149.2   The Java Application Programming Interface (Java API)


150    What is the Java Virtual Machine?

The Java Virtual Machine is a software that can be ported onto various hardware-based platforms.


It is used to explain the java class codes and run in the OS.


151    What is the Java API?

The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets.


152    What is the package?

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


153    What is native code?

The native code is code that after you compile it, the compiled code runs on a specific hardware platform.


154    Is Java code slower than native code? 

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


155    What is the serialization?

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


156    How to make a class or a bean serializable?

By implementing either the java.io.Serializable interface, or the java.io.Externalizable interface. As long as one class in a class’s inheritance hierarchy implements Serializable or Externalizable, that class is serializable.


157    How many methods in the Serializable interface?

There is no method in the Serializable interface. The Serializable interface acts as a marker, telling the object serialization tools that your class is serializable.


158    How many methods in the Externalizable interface?

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


159    What is the difference between Serializable and Externalizable interface?

When you use Serializable interface, your class is serialized automatically by default. But you can override writeObject() and readObject() two methods to control more complex object serailization process. When you use Externalizable interface, you have a complete control over your class’s serialization process.


160    What is a transient variable?

A transient variable is a variable that may not be serialized. If you don’t want some field to be serialized, you can mark that field transient or static.


161    Which containers use a border layout as their default layout?

The Window, Frame and Dialog classes use a border layout as their default layout.


162    How are Observer and Observable used?

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


163    What is synchronization and why is it important?

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


164    What are synchronized methods and synchronized statements?

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


165    How are Observer and Observable used?

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


166    What are three ways in which a thread can enter the waiting state?

A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O, by unsuccessfully attempting to acquire an object’s lock, or by invoking an object’s wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method.


167    Can a lock be acquired on a class?

Yes, a lock can be acquired on a class. This lock is acquired on the class’s Class object.


168    What’s new with the stop(), suspend() and resume() methods in JDK 1.2?

The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.


169    What is the preferred size of a component?

The preferred size of a component is the minimum component size that will allow the component to display normally.


170    Which containers use a FlowLayout as their default layout?

The Panel and Applet classes use the FlowLayout as their default layout.


171    What is thread?

171A thread is an independent path of execution in a system.


172    What is multithreading?

Multithreading means various threads that run in a system.


173    How does multithreading take place on a computer with a single CPU?

The operating system’s task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially.


174    How to create multithread in a program?

You have two ways to do so. First, making your class “extends” Thread class. Second, making your class “implements” Runnable interface. Put jobs in a run() method and call start() method to start the thread.


175    Can Java object be locked down for exclusive use by a given thread?

Yes. You can lock an object by putting it in a “synchronized” block. The locked object is inaccessible to any thread other than the one that explicitly claimed it.


176    Can each Java object keep track of all the threads that want to exclusively access to it?

Yes, the methods in Object wait and notify are used to access the synchronized objects.


177    What state does a thread enter when it terminates its processing?

When a thread terminates its processing, it enters the dead state.


178    What invokes a thread’s run() method?

After a thread is started, via its start() method of the Thread class, the JVM invokes the thread’s run() method when the thread is initially executed.


179    What is the purpose of the wait(), notify(), and notifyAll() methods?

The wait(), notify(), and notifyAll() methods are used to provide an efficient way for threads to communicate each other.


180    What are the high-level thread states?

The high-level thread states are ready, running, waiting, and dead.


181    What is the Collections API?

The Collections API is a set of classes and interfaces that support operations on collections of objects.


182    What is the List interface?

The List interface provides support for ordered collections of objects.


183    What is the Vector class?

The Vector class provides the capability to implement a growable array of objects


184    What modifiers may be used with an inner class that is a member of an outer class?

A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.


185    If a method is declared as protected, where may the method be accessed?

A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared.


186    What is an Iterator interface?

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


187    How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?

Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.


188    What is the difference between yielding and sleeping?

When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state.


189    Is sizeof a keyword?

The sizeof operator is not a keyword. It is a just operator.


190    What are wrapped classes?

Wrapped classes are classes that allow primitive types to be accessed as objects.


191    Does garbage collection guarantee that a program will not run out of memory?

No, it doesn’t. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection.


192    What is the difference between preemptive scheduling and time slicing?

Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.


193    Name Component subclasses that support painting.

The Canvas, Frame, Panel, and Applet classes support painting.


194    What is a native method?

A native method is a method that is implemented in a language other than Java.


195    How can you write a loop indefinitely?

for($$)–for loop; while(true)–always true, etc.


196    Can an anonymous class be declared as implementing an interface and extending a class?
An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.


197    What is the purpose of finalization?

The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.


198    Which class is the superclass for every class?



199    What is the difference between the Boolean & operator and the && operator?

If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped.

Operator & has no chance to skip both sides evaluation and && operator does. If asked why, give details as above.


200    What is the GregorianCalendar class?

The GregorianCalendar provides support for traditional Western calendars.


201    What is the SimpleTimeZone class?

The SimpleTimeZone class provides support for a Gregorian calendar.


202    Which Container method is used to cause a container to be laid out and redisplayed?



203    What is the Properties class?

The properties class is a subclass of Hashtable that can be read from or written to a stream. It also provides the capability to specify a set of default values to be used.


204    What is the purpose of the Runtime class?

The purpose of the Runtime class is to provide access to the Java runtime system.


205    What is the purpose of the System class?

The purpose of the System class is to provide access to system resources.


206    Which package has light weight components?

javax.Swing package. All components in Swing, except JApplet, JDialog, JFrame and JWindow are lightweight components.


207    What are peerless components?

The peerless components are called light weight components.


208    What is the difference between the Font and FontMetrics classes?

The FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of a Font object.


209    What happens when a thread cannot acquire a lock on an object?

If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object’s lock, it enters the waiting state until the lock becomes available.


210    What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?

The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented.


211    What classes of exceptions may be caught by a catch clause?

A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types


212    What is the difference between throw and throws keywords?

The throw keyword denotes a statement that causes an exception to be initiated. It takes the Exception object to be thrown as argument. The exception will be caught by an immediately encompassing try-catch construction or propagated further up the calling hierarchy. The throws keyword is a modifier of a method that designates that exceptions may come out of the mehtod, either by virtue of the method throwing the exception itself or because it fails to catch such exceptions that a method it calls may throw.

213    If a class is declared without any access modifiers, where may the class be accessed?

A class that is declared without any access modifiers is said to have package or friendly access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package.


214    What is the Map interface?

The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values.


215    Does a class inherit the constructors of its superclass?

A class does not inherit constructors from any of its superclasses.


216    Name primitive Java types.

The primitive types are byte, char, short, int, long, float, double, and boolean.


217    What is the purpose of the finally clause of a try-catch-finally statement?

The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.


218    What is the Locale class?

The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region


219    What must a class do to implement an interface?

It must provide all of the methods in the interface and identify the interface in its implements clause.


220    What is an abstract method?

An abstract method is a method whose implementation is deferred to a subclass. Or, a method that has no implementation (an interface of a method).


221    What is a static method?

A static method is a method that belongs to the class rather than any object of the class and doesn’t apply to an object or even require that any objects of the class have been instantiated.


222    What is a protected method?

A protected method is a method that can be accessed by any method in its package and inherited by any subclass of its class.


223    What is the difference between a static and a non-static inner class?

A non-static inner class may have object instances that are associated with instances of the class’s outer class. A static inner class does not have any object instances.


224    What is an object’s lock and which object’s have locks?

An object’s lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object’s lock. All objects and classes have locks. A class’s lock is acquired on the class’s Class object.


225    When can an object reference be cast to an interface reference?

An object reference be cast to an interface reference when the object implements the referenced interface.


226    What is the difference between a Window and a Frame?

The Frame class extends Window to define a main application window that can have a menu bar.

227    What do heavy weight components mean?

Heavy weight components like Abstract Window Toolkit (AWT), depend on the local windowing toolkit. For example, java.awt.Button is a heavy weight component, when it is running on the Java platform for Unix platform, it maps to a real Motif button. In this relationship, the Motif button is called the peer to the java.awt.Button. If you create two Buttons, two peers and hence two Motif Buttons are also created. The Java platform communicates with the Motif Buttons using the Java Native Interface. For each and every component added to the application, there is an additional overhead tied to the local windowing system, which is why these components are called heavy weight.


228    Which class should you use to obtain design information about an object?

The Class class is used to obtain information about an object’s design.


229    How can a GUI component handle its own events?

A component can handle its own events by implementing the required event-listener interface and adding itself as its own event listener.


230    How are the elements of a GridBagLayout organized?

The elements of a GridBagLayout are organized according to a grid. However, the elements are of different sizes and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes.


231    What advantage do Java’s layout managers provide over traditional windowing systems?

Java uses layout managers to lay out components in a consistent manner across all windowing platforms. Since Java’s layout managers aren’t tied to absolute sizing and positioning, they are able to accommodate platform-specific differences among windowing systems.


232    What are the problems faced by Java programmers who don’t use layout managers?

Without layout managers, Java programmers are faced with determining how their GUI will be displayed across multiple windowing systems and finding a common sizing and positioning that will work within the constraints imposed by each windowing system.


233    What is the difference between static and non-static variables?

A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.


234    What is the difference between the paint() and repaint() methods?

The paint() method supports painting via a Graphics object. The repaint() method is used to cause paint() to be invoked by the AWT painting thread.


235    What is the purpose of the File class?

The File class is used to create objects that provide access to the files and directories of a local file system.


236    What restrictions are placed on method overloading?

Two methods may not have the same name and argument list but different return types.


237    What restrictions are placed on method overriding?

Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides. The overriding method may not throw any exceptions that may not be thrown by the overridden method.


The overridden methods can decrease the visibility of the methods. The overridden methods can increase the thrown exceptions.


238    What is casting?

There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.


239    Name Container classes.

Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane


240    What class allows you to read objects directly from a stream?

The ObjectInputStream class supports the reading of objects from input streams.


241    How are this() and super() used with constructors?

this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.


242    How is it possible for two String objects with identical values not to be equal under the == operator?

The == operator compares two objects to determine if they are the same object in memory. It is possible for two String objects to have the same value, but located indifferent areas of memory.


243    What is the Set interface?

The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements.


244    What is the List interface?

The List interface provides support for ordered collections of objects.


245    What is the purpose of the enableEvents() method?

The enableEvents() method is used to enable an event for a particular object. Normally, an event is enabled when a listener is added to an object for a particular event. The enableEvents() method is used by objects that handle events by overriding their event-dispatch methods.


The method enableEvents() is in the Component class in AWT.


246    What is the difference between the File and RandomAccessFile classes?

The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.


247    What interface must an object implement before it can be written to a stream as an object?

An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.


248    What is the ResourceBundle class?

The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program’s appearance to the particular locale in which it is being run.


249    What is the difference between a Scrollbar and a ScrollPane?

A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling.


250    What is a Java package and how is it used?

A Java package is a naming context for classes and interfaces. A package is used to create a separate name space for groups of classes and interfaces. Packages are also used to organize related classes and interfaces into a single API unit and to control accessibility to these classes and interfaces.


251    What are the Object and Class classes used for?

The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program.


252    What is Serialization and deserialization?

Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects.


253    Does the code in finally block get executed if there is an exception and a return statement in a catch block?

If an exception occurs and there is a return statement in catch block, the finally block is still executed. The finally block will not be executed when the System.exit(1) statement is executed earlier or the system shut down earlier or the memory is used up earlier before the thread goes to finally block.


254    How you restrict a user to cut and paste from the html page?

Using javaScript to lock keyboard keys. It is one of solutions.


255    Is Java a super set of JavaScript?

No. They are completely different. Some syntax may be similar.


256    What is a Container in a GUI?

A Container contains and arranges other components (including other containers) through the use of layout managers, which use specific layout policies to determine where components should go as a function of the size of the container.


257    How the object oriented approach helps us keep complexity of software development under control?

We can discuss such issue from the following aspects (Encapsulation, Inheritance and Porlymorphysm),


257.1   Objects allow procedures to be encapsulated with their data to reduce potential interference.


257.2   Inheritance allows well-tested procedures to be reused and enables changes to make once and have effect in all relevant places.


257.3   The well-defined separations of interface and implementation allows constraints to be imposed on inheriting classes while still allowing the flexibility of overriding and overloading.


258    What is polymorphism?

Polymorphism allows methods to be written that needn’t be concerned about the specifics of the objects they will be applied to. That is, the method can be specified at a higher level of abstraction and can be counted on to work even on objects of yet unconceived classes.


259    What is design by contract?

The design by contract specifies the obligations of a method to any other methods that may use its services and also theirs to it. For example, the preconditions specify what the method required to be true when the method is called. Hence making sure that preconditions are. Similarly, postconditions specify what must be true when the method is finished, thus the called method has the responsibility of satisfying the post conditions.


In Java, the exception handling facilities support the use of design by contract, especially in the case of checked exceptions. The assert keyword can be used to make such contracts.


260    What are use cases?

A use case describes a situation that a program might encounter and what behavior the program should exhibit in that circumstance. It is part of the analysis of a program. The collection of use cases should, ideally, anticipate all the standard circumstances and many of the extraordinary circumstances possible so that the program will be robust.


261    What is the difference between interface and abstract class?

261.1   interface contains methods that must be abstract; abstract class may contain concrete methods.

261.2   interface contains variables that must be static and final; abstract class may contain non-final and final variables.

261.3   members in an interface are public by default, abstract class may contain non-public members.

261.4   interface is used to “implements”; whereas abstract class is used to “extends”.

261.5   interface can be used to achieve multiple inheritance; abstract class can be used as a single inheritance.

261.6   interface can “extends” another interface, abstract class can “extends” another class and “implements” multiple interfaces.

261.7   interface is absolutely abstract; abstract class can be invoked if a main() exists.

261.8   interface is more flexible than abstract class because one class can only “extends” one super class, but “implements” multiple interfaces.

261.9   If given a choice, use interface instead of abstract class.


262    What is HTTPSession Class?

HttpSession Class provides a way to identify a user across across multiple request. The servlet container uses HttpSession interface to create a session between an HTTP client and an HTTP server. The session lives only for a specified time period, across more than one connection or page request from the user.


263    Why do u use Session Tracking in HttpServlet?

In HttpServlet you can use Session Tracking to track the user state. Session is required if you are developing shopping cart application or in any e-commerce application.


264    What are the advantage of Cookies over URL rewriting?

Sessions tracking using Cookies are more secure and fast. Session tracking using Cookies can also be used with other mechanism of Session Tracking like url rewriting.


Cookies are stored at client side so some clients may disable cookies so we may not sure that the cookies may work or not.


In url  rewriting requites large data transfer from and to the server. So, it leads to network traffic and access may be become slow.


265    What is Session Migration?

Session Migration is a mechanism of moving the session from one server to another in case of server failure. Session Migration can be implemented by:

265.1   Persisting the session into database

265.2   Storing the session in-memory on multiple servers.


266    How to track a user session in Servlets?

The interface HttpSession can be used to track the session in the Servlet. Following code can be used to create session object in the Servlet: HttpSession session = req.getSession(true);


267    How you can destroy the session in Servlet?

You can call invalidate() method on the session object to destroy the session. e.g. session.invalidate();


268    It is said that the code in a finally clause will never fail to execute, Is there any example where it fails to execute?

Here is the example code where the finally clause code will not execute.


  public class testFinally{
        public static void main(String[] args){
               System.out.println(“Executing the program”);
                 try {
                       System.out.println(“In the try block”);
                        } finally {
                       System.out.println(“In the finally.”);


269    Why there are no global variables in Java?

Global variables are globally accessible. Java does not support globally accessible variables due to following reasons:


269.1   The global variables breaks the referential transparency

269.2   Global variables creates collisions in namespace.


270    What platforms is the Java-technology software available on?

Sun provides ports of the Java 2 Platform for Windows 95, Windows 98, Windows NT, Windows 2000, Solaris-SPARC, Solaris-Intel, and Linux.


271    Where can I download latest version of Java?

Latest version of JDK can be downloaded from Sun web site http://www.java.sun.com.


272    Do I need to know C++ to learn Java?

No, you don’t need to know C or C++ to learn Java. Java is much simpler that C++.


273    What is the difference between Java and Java Script?

In Java and Java Script only the “Java” word is common. Java is programming language from Sun. JavaScript is a programming language from Netscape, which runs in their browsers.


274    Differentiate between applet and application.

Java applications runs as stand-alone application whereas applet runs in web browser. Application is a Java class that has a main() method. Applet class extends java.applet.Applet class.


275    How to convert String to Number in java program?

The valueOf() function of Integer class is is used to convert string to Number. Here is the code example:


String strId = “10”;

int id=Integer.valueOf(strId);


276    What is interface?

In Java Interface defines the methods but does not implement them. Interface can include constants. A class that implements the interfaces is bound to implement all the methods defined in Interface.

Example of Interface:

public interface sampleInterface {

    public void functionOne();


    public long CONSTANT_ONE = 1000;



277    How you can force the garbage collection?

Garbage collection automatic process and can’t be forced.


278    What is the use of Object and Class Classes?

The Object class is the superclass of all other classes and it is highest-level class in the Java class hierarchy. Instances of the class Class represent classes and interfaces in a running Java application. Every array also belongs to a class that is reflected as a Class object that is shared by all arrays with the same element type and number of dimensions. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects.


279    What do you understand by a variable?

The variables plays very important role in computer programming. Variables enable programmers to write flexible programs. It is a memory location that has been named so that it can be easily be referred in the program. The variable is used to hold the data and it can be changed changed during the course of the execution of the program.


280    What do you understand by numeric promotion?

The Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating-point operations may take place. In the numerical promotion process the byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required.


281    What do you understand by casting in java language?

The process of converting one datatype to another in Java language is called Casting.


282    What are the types of casting?

There are two types of casting in Java, these are Implicit casting and explicit casting.


283    What is Implicit casting?

Implicit casting is the process of simply assigning one entity to another without any transformation guidance to the compiler. This type of casting is not permitted in all kinds of transformations and may not workout for all application scenarios.




int i = 4000;

long h = i; //Implicit casting


284    What is explicit casting?

Explicit casting in the process in which the complier are specifically informed to about transforming the object.


long ln = 700.20;


t = (int) ln; //Explicit casting


285    What do you understand by downcasting?

The process of Downcasting refers to the casting from a general to a more specific type, i.e. casting down the hierarchy


286    What do you understand by final value?

FINAL for a variable: value is constant. FINAL for a method: cannot be overridden. FINAL for a class: cannot be derived


287    What is a Servlet?

Java Servlets are server side components that provides a powerful mechanism for developing server side of web application. Earlier CGI was developed to provide server side capabilities to the web applications. Although CGI played a major role in the explosion of the Internet, its performance, scalability and reusability issues make it less than optimal solutions. Java Servlets changes all that. Built from ground up using Sun’s write once run anywhere technology java servlets provide excellent framework for server side processing.


288    What are the types of Servlet?

There are two types of servlets, GenericServlet and HttpServlet. GenericServlet defines the generic or protocol independent servlet. HttpServlet is subclass of GenericServlet and provides some http specific functionality linke doGet and doPost methods.


289    What are the differences between HttpServlet and Generic Servlets?

HttpServlet Provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site. A subclass of HttpServlet must override at least one method, usually one of these:


doGet, if the servlet supports HTTP GET requests

doPost, for HTTP POST requests

doPut, for HTTP PUT requests

doDelete, for HTTP DELETE requests

init and destroy, to manage resources that are held for the life of the servlet

getServletInfo, which the servlet uses to provide information about itself


There’s almost no reason to override the service method. service handles standard HTTP requests by dispatching them to the handler methods for each HTTP request type (the doXXX methods listed above). Likewise, there’s almost no reason to override the doOptions and doTrace methods.


290    Differentiate between Servlet and Applet.

Servlets are server side components that executes on the server whereas applets are client side components and executes on the web browser. Applets have GUI interface but there is not GUI interface in case of Servlets.


291    Differentiate between doGet and doPost method?

doGet is used when there are requirement of sending data appended to a query string in the URL. The doGet models the GET method of Http and it is used to retrieve the info on the client from some server as a request to it. The doGet cannot be used to send too much info appended as a query stream. GET puts the form values into the URL string. GET is limited to about 256 characters (usually a browser limitation) and creates really ugly URLs.


POST allows you to have extremely dense forms and pass that to the server without clutter or limitation in size. e.g. you obviously can’t send a file from the client to the server via GET. POST has no limit on the amount of data you can send and because the data does not show up on the URL you can send passwords. But this does not mean that POST is truly secure. For real security you have to look into encryption which is an entirely different topic


292    What are methods of HttpServlet?

The methods of HttpServlet class are :

292.1   doGet() is used to handle the GET, conditional GET, and HEAD requests

292.2   doPost() is used to handle POST requests

292.3   doPut() is used to handle PUT requests

292.4   doDelete() is used to handle DELETE requests

292.5   doOptions() is used to handle the OPTIONS requests and

292.6   doTrace() is used to handle the TRACE requests


293    What are the advantages of Servlets over CGI programs?

Java Servlets have a number of advantages over CGI and other API’s. They are:

293.1   Platform Independence

Java Servlets are 100% pure Java, so it is platform independence. It can run on any Servlet enabled web server. For example if you develop an web application in windows machine running Java web server. You can easily run the same on apache web server (if Apache Serve is installed) without modification or compilation of code. Platform independency of servlets provide a great advantages over alternatives of servlets.

293.2   Performance

Due to interpreted nature of java, programs written in java are slow. But the java servlets runs very fast. These are due to the way servlets run on web server. For any program initialization takes significant amount of time. But in case of servlets initialization takes place very first time it receives a request and remains in memory till times out or server shut downs. After servlet is loaded, to handle a new request it simply creates a new thread and runs service method of servlet. In comparison to traditional CGI scripts which creates a new process to serve the request. This intuitive method of servlets could be use to develop high speed data driven web sites.

293.3   Extensibility

Java Servlets are developed in java which is robust, well-designed and object oriented language which can be extended or polymorphed into new objects. So the java servlets takes all these advantages and can be extended from existing class the provide the ideal solutions.

293.4   Safety

Java provides a very good safety features like memory management, exception handling etc. Servlets inherits all these features and emerged as a very powerful web server extension.

293.5   Secure

Servlets are server side components, so it inherits the security provided by the web server. Servlets are also benefited with Java Security Manager.


294    What are the lifecycle methods of Servlet?

The interface javax.servlet.Servlet,  defines the three life-cycle methods. These are:

public void init(ServletConfig config) throws ServletException

public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException

public void destroy()


The container manages the lifecycle of the Servlet. When a new request come to a Servlet, the container performs the following steps.

294.1   If an instance of the servlet does not exist, the web container

294.1.1      Loads the servlet class.

294.1.2      Creates an instance of the servlet class.

294.1.3      Initializes the servlet instance by calling the init method. Initialization is covered in Initializing a Servlet.

294.2   The container invokes the service method, passing request and response objects.

294.3   To remove the servlet, container finalizes the servlet by calling the servlet’s destroy method.


295    What are the type of protocols supported by HttpServlet?

It extends the GenericServlet base class and provides an framework for handling the HTTP protocol. So, HttpServlet only supports HTTP and HTTPS protocol.


296    What are the directory Structure of Web Application?

Web component follows the standard directory structure defined in the J2EE specification.

Java Source

Web Content

—-jsp, html, css, images






297    What is ServletContext?

ServletContext is an Interface that defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. There is one context per “web application” per Java Virtual Machine. (A “web application” is a collection of servlets and content installed under a specific subset of the server’s URL namespace such as /catalog and possibly installed via a .war file.)


298    What is meant by Pre-initialization of Servlet?

When servlet container is loaded, all the servlets defined in the web.xml file does not initialized by default. But the container receives the request it loads the servlet. But in some cases if you want your servlet to be initialized when context is loaded, you have to use a concept called pre-initialization of Servlet. In case of Pre-initialization, the servlet is loaded when context is loaded. You can specify <load-on-startup>1</load-on-startup>

in between the <servlet></servlet> tag.


299    What mechanisms are used by a Servlet Container to maintain session information?

Servlet Container uses Cookies, URL rewriting, and HTTPS protocol information to maintain the session.


300    What do you understand by servlet mapping?

Servlet mapping defines an association between a URL pattern and a servlet. You can use one servlet to process a number of url pattern (request pattern). For example in case of Struts *.do url patterns are processed by Struts Controller Servlet.


301    What must be implemented by all Servlets?

The Servlet Interface must be implemented by all servlets.


302    What are the uses of Servlets?

302.1   Servlets are used to process the client request.

302.2   A Servlet can handle multiple requests concurrently and be used to develop high performance system

302.3   A Servlet can be used to load balance among several servers, as Servlet can easily forward request.


303    What are the objects that are received when a servlets accepts call from client?

The objects are ServletRequest and ServletResponse . The ServeltRequest encapsulates the communication from the client to the server. While ServletResponse encapsulates the communication from the Servlet back to the client.


304    What are design patterns?

A pattern is a proven (and recurring) solution to a problem in a context. Each pattern describes a problem which occurs over and over again in our environment, and describes its solution to this problem in such a way that we can use this solution a lots of times. In simple words, there are a lot of common problems which a lot of developers have faced over time. These common problems ideally should have a common solution too. It is this solution when documented and used over and over becomes a design pattern.


305    Can we always apply the same solution to different problems at hand?

No. Design patterns would study the different problems at hand. To these problems then it would suggest different design patterns to be used. However, the type of code to be written in that design pattern is solely the discretion of the Project Manager who is handling that project.


306    What should be the level of detail/abstraction which should be provided by a design pattern?

Design patterns should present a higher abstraction level though it might include details of the solution. However, these details are lower abstractions and are called strategies. There may be more than one way to apply these strategies in implementing the patterns.


307    What are the most common problems which one faces during the application design phase that are solved by design patterns?


307.1   Identifying components, internal structures of the components, and relationships between components.

307.2   Determining component granularity and appropriate interactions

307.3   Defining component interfaces.


308    How does one decide which Design pattern to use in our application?

We need to follow these steps:


308.1   We need to understand the problem at hand. Break it down to finer grained problems. Each design pattern is meant to solve certain kinds of problems. This would narrow down our search for design patterns.

308.2   Read the problem statement again along with the solution which the design pattern will provide. This may instigate to change a few patterns that we are to use.

308.3   Now figure out the interrelations between different patterns. Also decide what all patterns will remain stable in the application and what all need to change (with respect to Change Requests received from the clients).


309    What is Refactoring?

Learning different design patterns is not sufficient to becoming a good designer. We have to understand these patterns and use them where they have more benefits. Using too many patterns (more than required) would be over-engineering and using less design patterns than required would be under-engineering. In both these scenarios we use refactoring. Refactoring is a change made to the internal structure of the software to make it easier to understand and cheaper to modify, without changing its observable behaviour.


310    What are Antipatterns?

Though the use of patterns fulfils our objectives in the applications; there are also several instances where several applications did not fulfill their goals. The architects of these applications too need to document these wrong decisions. This helps us in repeating these mistakes in our future applications. Such documented mistakes are called antipatterns.


Thus antipatterns are negative solutions which cause more problems than what they address. For ex. We might use entity beans which have fine-grained interfaces which can directly be accessed from the client side. This would result in considerable RMI and transaction management overhead. It results in poor performance and un-scalable applications.


311    As we do development in tiers, how do we divide patterns in tiers?

The Sun Java Center has classified the patterns in three tiers. These are:


Presentation tier patterns for web-component tier,

Business tier patterns for business logic (EJB) tier, and

Integration tier patterns for connection to the databases.


The presentation tier patterns are:


Intercepting filter, Front Controller, View Helper, Composite View, Service-to-Worker, and Dispatcher View.


The business tier patterns are:


Business delegate, Value Object, Session Façade, Composite Entity, Value Object Assembler, Value List Handler, and Service Locator.


Integration tier patterns are:


Data Access Object (DAO) and Service Activator.


312    What is Intercepting Filter pattern?

Provides a solution for pre-processing and post-processing a request. It allows us to declaratively apply filters for intercepting requests and responses. For ex. Servlet filters.


313    What is Front Controller pattern?

It manages and handles requests through a centralized code. This could either be through a servlet or a JSP (through a Java Bean). This Controller takes over the common processing which happens on the presentation tier. The front controller manages content retrieval, security, view management and retrieval.


314    What is View Helper pattern?

There generally are two parts to any application – the presentation and the business logics. The “View” is responsible for the output-view formatting whereas “Helper” component is responsible for the business logic. Helper components do content retrieval, validation and adaptation. Helper components generally use Business delegate pattern to access business classes.


315    What is Composite View pattern?

This pattern is used for creating aggregate presentations (views) from atomic sub-components. This architecture enables says piecing together of elementary view components which makes the presentation flexible by allowing personalization and customization.


316    What is Service to Worker pattern?

This is used in larger applications wherein one class is used to process the requests while the other is used to process the view part. This differentiation is done for maintainability.


317    What is Dispatcher View pattern?

This is similar to Service to Worker pattern except that it is used for smaller applications. In this one class is used for both request and view processing.


318    What is Business Delegate pattern?

This pattern is used to reduce the coupling between the presentation and business-logic tier. It provides a proxy to the façade from where one could call the business classes or DAO class. This pattern can be used with Service Locator pattern for improving performance.


319    What is Value Object (VO) pattern?

Value Object is a serializable object which would contain lot of atomic values. These are normal java classes which may have different constructors (to fill in the value of different data) and getter methods to get access to these data. VOs are used as a course grained call which gets lots of data in one go (this reduces remote overhead). The VO is made serializable for it to be transferred between different tiers within a single remote method invocation.


320    What is Session Façade pattern?

This pattern hides the complexity of business components and centralizes the workflow. It provides course-grained interfaces to the clients which reduces the remote method overhead. This pattern fits well with declarative transactions and security management.


321    What is Value Object Assembler pattern?

This pattern allows for composing a Value Object from different sources which could be EJBs, DAOs or Java objects.


322    What is Value List Handler pattern?

This pattern provides a sound solution for query execution and results processing.


323    What is Service Locator pattern?

It provides a solution for looking-up, creating and locating services and encapsulating their complexity. It provides a single point of control and it also improves performance.


324    What is Data Access Object pattern?

It provides a flexible and transparent access to the data, abstracts the data sources and hides the complexity of Data persistence layer. This pattern provides for loose coupling between business and data persistence layer.


325    What is EJB Command pattern?

Session Façade and EJB Command patterns are competitor patterns. It wraps business logic in command beans, decouples the client and business logic tier, and reduces the number of remote method invocations.


326    What is Version Number pattern?

This pattern is used for transaction and persistence and provides a solution for maintaining consistency and protects against concurrency. Every time a data is fetched from the database, it comes out with a version number which is saved in the database. Once any update is requested on the same row of the database, this version is checked. If the version is same, the update is allowed else not.


327    What all patterns are used to improve performance and scalability of the application?

VO, Session Façade, Business Delegate and Service Locator.


328    What design patterns could be used to manage security?

Single Access Point, Check point and Role patterns.


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

The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This is how the standard output could be re-directed:


Stream st = new FileOutputStream(“output.txt”));





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

Synchronized blocks place locks for shorter periods than synchronized methods.


331    Explain the usage of the keyword transient?

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


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

If you assign a superclass object to a variable of a subclass’s data type, you need to do explicit casting. For example:


Object a; Customer b; b = (Customer) a;


When you assign a subclass to a variable having a supeclass type, the casting is performed automatically.


333    What’s the difference between the methods sleep() and wait()

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


334    Can you write a Java class that could be used both as an applet as well as an application?

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


335    What’s the difference between constructors and other methods?

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


336    Can you call one constructor from another if a class has multiple constructors?

Yes. Use this() syntax.


337    Explain the usage of Java packages.

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


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

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


c:\>java com.xyz.hr.Employee


339    What order does JVM search the path for the classes?


339.2   –classpath in java command

339.3   . the current directory


When you use CLASSPATH and –classpath, you must set the . (current directory) manually. Or the . (current director) is not searched.


340    What’s the difference between J2SDK 1.5 and J2SDK 5.0?

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


341    What would you use to compare two String variables – the operator == or the method equals()?


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


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

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


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

It’s possible if these variables are final.

Because the instance of the inner class have longer life cycle than the method. In addition, the final variant is special one, which will be stored beyond the method. So final variant inside the method can be access in method inner class.


344    What can go wrong if you replace && with & in the following code:

String a=null; if (a!=null && a.length()>10) {…}


A single ampersand here would lead to a NullPointerException.


345    What’s the main difference between a Vector and an ArrayList?

Java Vector class is internally synchronized and ArrayList is not.


346    When should the method invokeLater()be used?

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


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

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


348    What’s the difference between a queue and a stack?

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


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

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


350    What comes to mind when you hear about a young generation in Java?

Garbage collection.


351    What comes to mind when someone mentions a shallow copy in Java?

Object cloning.


352    If you’re overriding the method equals() of an object, which other method you might also consider?



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



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

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


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

Use object pooling and weak object references.


356    How to use the weak object reference?

If there is no strong reference to one object, the object may be reclaim or may not be relaim. Then softReference.get() can be used to get the object again if the object is not claimed.


import java.awt.Graphics;

import java.awt.Image;

import java.applet.Applet;

import java.lang.ref.SoftReference;


public class DisplayImage extends Applet {


        SoftReference sr = null;


        public void init() {




        public void paint(Graphics g) {

            Image im = (

              sr == null) ? null : (Image)(


            if (im == null) {


                “Fetching image”);

                im = getImage(getCodeBase(),


                sr = new SoftReference(im);



           g.drawImage(im, 25, 25, this);

           im = null; 

        /* Clear the strong reference to the image */



        public void start() {




        public void stop() {






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

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


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

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


359    Is a class a subclass of itself?

A class is a subclass of itself.


360    What an I/O filter?

An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.


361    If an object is garbage collected, can it become reachable again?

Once an object is garbage collected, it ceases to exist. It can no longer become reachable again.


362    How does Java handle integer overflows and underflows?

It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.


363    What is the difference between instanceof and isInstance?

instanceof is used to check to see if an object can be cast into a specified type without throwing a cast class exception. isInstance() Determines if the specified Object is assignment-compatible with the object represented by this Class. This method is the dynamic equivalent of the Java language instanceof operator. The method returns true if the specified Object argument is non-null and can be cast to the reference type represented by this Class object without raising a ClassCastException. It returns false otherwise.


364    What is Struts Flow?

Struts Flow is a port of Cocoon‘s Control Flow to Struts to allow complex workflow, like multi-form wizards, to be easily implemented using continuations-capable JavaScript. It provides the ability to describe the order of Web pages that have to be sent to the client, at any given point in time in an application. The code is based on a proof-of-concept Dave Johnson put together to show how the Control Flow could be extracted from Cocoon.


365    What is tunnelling?

Tunnelling is a route to somewhere. For example, RMI tunnelling is a way to make RMI application get through firewall. In CS world, tunnelling means a way to transfer data.


366    What is session hijacking?

If you application is not very secure then it is possible to get the access of system after acquiring or generating the authentication information. Session hijacking refers to the act of taking control of a user session after successfully obtaining or generating an authentication session ID. It involves an attacker using captured, brute forced or reverse-engineered session IDs to get a control of a legitimate user’s Web application session while that session is still in progress.


367    If a static method is synchronized, what object is used to synchronize?

The Class Object itself.


368    What is the usage of the parameterized type?

368.1   Validation at compile time.

368.2   Decrease the type cast.


369    What is the output?

public class Test {

    public static void main(String[] args) {




    private static void loopByNum(int num) {


            for  (int i = 1; i < 3; i ++) {

                for (int j = 0; j < 3; j++) {

                    if (num  == 5)

                        break loop;







Answer: No output.


370    GJ 程序的语法在表面上与 C++ 中的模板非常类似,但是二者之间有着本质的区别

首先,Java 语言中的泛型不能接受基本类型作为类型参数――它只能接受引用类型。这意味着可以定义 List<Integer>,但是不可以定义 List<int>

其 次,在 C++ 模板中,编译器使用提供的类型参数来扩充模板,因此,为 List<A> 生成的 C++ 代码不同于为 List<B> 生成的代码,List<A> List<B> 实际上是两个不同的类。而 Java 中的泛型则以不同的方式实现,编译器仅仅对这些类型参数进行擦除和替换。类型 ArrayList<Integer> ArrayList<String> 的对象共享相同的类,并且只存在一个 ArrayList 类。

371    What is the name of the configuration file in JSF?



372    If you declare the composite keys in hibernate configuration, how many classes do you really need?

One or Two.

372.1   The plain properties can be used as the composite keys.


        <key-property name=”medicareNumber”/>

        <key-property name=”dependent”/>


372.2   An encapsulated ID class can be used.

<composite-id class=”MedicareId” mapped=”true”>

        <key-property name=”medicareNumber”/>

        <key-property name=”dependent”/>



373  What are new features in JDK 1.5?

373.1 泛型(Generic Java)

373.2 枚举(Enums)

373.3 可变参数(Varargs)

373.4 For-Each循环

373.5 自动装包/拆包(Autoboxing/unboxing)


374    What selectors can you use in CSS?

Html Selector: style=”color:red”

Class Selector: tag.Classname {property:value}

Id Selector: #IDname {property:value}


375    What does it mean by $, $$, $F, $A, $H, $W, $R?

$, Return the element with the specific id.

$$, Return the element with the specific CSS id.

$F, Return the value of element with the specific id.

$A, Return an array.

$H, Return an Hash.

$W, Split the string by whitespace.

$R, Return a range.


376    How does Prototype support Ajax?

376.1   Ajax.Request -> Ajax Response (Ajax Responders)


new Ajax.Request(‘/your/url’, {
  onSuccess: function(transport) {


376.2 Ajax.Request -> Ajax.Updater -> Ajax.PeriodicalUpdater


Inherit from the previous one.


377    How does Ajax work?

function test(data) {
 // taking care of data
function handler() {
 if(this.readyState == 4 && this.status == 200) {
  // so far so good
  if(this.responseXML != null && this.responseXML.getElementById(‘test’).firstChild.data)
     // success!
 } else if (this.readyState == 4 && this.status != 200) {
  // fetched the wrong page or network error…
var client = new XMLHttpRequest();
client.onreadystatechange = handler;
client.open(“GET”, “test.xml”);


378    What does Hibernate handle inheritance?

378.1   Table per class hierarchy <subclass> (descriminator)

378.2   Table per each class <join-subclass>

378.3   Table per concrete class with unions <union-subclass>

379    What states does Hibernate Object have?





380    What is the difference between save and update?

Save: Insert a new record.

Update: Update a detached record.


381    What is the difference between update and saveOrUpdate?

Update: Update a detached record.

SaveOrUpdate: Save a new record or update a detached record.


382    What is difference between persist and save?

Persist, the DB operation will be hanging on until the transaction is committed or flush is called.

Save, the DB operation will be executed immediately.


383    What is the difference between saveOrUpdateCopy, merge and saveOrUpdate?

saveOrUpdateCopy is an old version of merge.

Merge, return the non-persistent object.

With saveOrUpdate, return the persistent object.


384    What is the difference between lock and update?

Lock, Make a none-changed Object to persistent.

Update, make a changed Object to persistent.


385    What does Hibernate provide?

385.1   Component Mapping

385.1.1      A contained class which is value type.

385.2   Collection Mapping

385.2.1      One to one.

385.2.2      One to Many.

385.2.3      Many to One.

385.2.4      Many to Mang.

385.3   Inheritance Mapping

385.3.1      Table per class hierarchy <subclass> (descriminator)

385.3.2      Table per each class <join-subclass>

385.3.3      Table per concrete class with unions <union-subclass>








mplayer -ss START_TIME -noframedrop -nosound -vo jpeg -frames N NAME_OF_VIDEO_FILE   
上例中,-ss指定开始的时间,结合-frames参数,限定从某个时间开始、截取几帧图像。为了体现整个影片的内容,我需要在影片中间隔时间相同的几个 点、每个点截取1帧图像,所以按道理应该用-frames 1,但是mplayer这样截图的情况下,第一帧似乎永远都会截取到一个黑屏,所以我常用-frames 2。截取下来的图像保存在了当前目录,名称从00000001.jpg开始依次递增,按照-frames 2,就是取00000002.jpg为结果,删除00000001.jpg即可。经过简单实验,在截取wmv、rmvb影片时,前面的好几帧都会是黑屏, 也只能参考上面的做法多取几帧了。

为了取影片中间隔大致相同的几个点,可以用-ss指定时间,也可以用-sb指定开始字节,在我的实际使用中,使用-sb只会得到黑屏,所以通过文件大小来 设置间隔点的办法不行,只能用-ss时间间隔了,这就需要首先得到影片的总时间。好在mplayer为我们提供了类似的功能:

mplayer -identify movie-filename -nosound -vc dummy -vo null   
这样会输出一大堆影片信息,从中截取所需内容即可,在bash shell中,取得影片总时间长度(以秒为单位)的命令如下:

FILESIZE=`mplayer -identify -nosound -vc dummy -vo null $1 | grep ID_LENGTH | sed -r ‘s/ID_LENGTH=([[:digit:]]*)(.[[:digit:]]*)?/1/g’`   
有了影片的总时长,我们就可以根据所要截取的帧数,计算出每个间隔点的时间位移了。不过要注意一般影片的开始-ss 0和结束-ss TOTAL_TIME_OF_VIDEO截取下来都会是黑屏,在处理的时候要分别加上和减去若干秒。

截取工作完成后,我们拥有了一堆000000xx.jpg文件,如果能把这些文件都放到一个文件中,每行2张,成为一张大图片,在发布的时候会很方便。所 以,我们使用imagemagick([url]http://www.imagemagick.org/script/index.php [/url])中的montage命令来实现:

montage -geometry +0+0 -tile 2 *.jpg montage.jpg   
-geometry +0+0是设定使用原始图片大小,-tile 2参数设定每行放2张图片,最后一个参数是要生成的目标文件名,现在,我们就能够得到像刚才那张一样的图片了。

原理已经讲清楚了,可以自己写一个bash脚本来方便调用,我在网上找到了一个很不错的例子([url]http: //www.linuxquestions.org/questions/showthread.php?t=361072[/url]),可以在这个基 础上进行修改,过程不再详述了。


mplayer -identify movie-filename -nosound -vc dummy -vo null
– filetype: ASF file format detected.
– dimensions and format: VIDEO: [MP43] 320×240 24bpp 1000.000 fps 0.0 kbps ( 0.0 kbyte/s)
– video format: ID_VIDEO_FORMAT=MP43
– width (dimensions): ID_VIDEO_WIDTH=320
– height (dimensions): ID_VIDEO_HEIGHT=240
– length in seconds: ID_LENGTH=98.00

mencoder *.jpg -mf on:w=800:h=600:fps=25 -ovc divx4 -o output.avi
mencoder -mf on:w=800:h=600:fps=25 -ovc divx4 -o output.avi *.jpg
#用当前目录中的所有JPEG文件创建Motion JPEG(MJPEG)文件:
mencoder -mf on:w=800:h=600:fps=25 -ovc copy -o output.avi *.jpg
mencoder -mf on:w=800:h=600:fps=25:type=png -ovc rawrgb -o output.avi *.png
mencoder *.jpg -mf on:fps=15 -o output.avi -ovc xvid
参考6 参考7([url]http://huangjiahua.livejournal.com/99358.html[/url])

ffmpeg -vcodec mpeg4 -b 1000 -r 10 -g 300 -vd x11:0,0 -s 1024×768 ~/test.avi
其中,-vd x11:0,0 指录制所使用的偏移为 x=0 和 y=0,-s 1024×768 指录制视频的大小为 1024×768。录制的视频文件为 test.avi,将保存到用户主目录中。其他选项可查阅其说明文档。
如果你只想录制一个应用程序窗口或者桌面上的一个固定区域,那么可以指定偏移位置和区域大小。使用xwininfo -frame命令可以完成查找上述参数。
你也可以重新调整视频尺寸大小,如:./ffmpeg -vcodec mpeg4 -b 1000 -r 10 -g 300 -i ~/test.avi -s 800×600 ~/test-800-600.avi。

mplayer对video进行截屏 截图(wmv mpeg mov flv all works)
mplayer 78.mov -ss 1 -nosound -vo jpeg:outdir=./ -frames 2

mencoder NOW.wmv -ffourcc FLV1 -of lavf -ovc lavc -lavcopts vcodec=flv:acodec=mp3:abitrate=56 -srate 22050 -oac mp3lame -o NOW.flv
ffmpeg -i a.asf -ab 56 -ar 22050 -b 500 -r 15 -s 320×240 asf.flv

ffmpeg -i test2.asf -y -f image2 -ss 08.010 -t 0.001 -s 352×240 b.jpg
jpg: ffmpeg -i test.asf -y -f image2 -t 0.001 -s 352×240 -ss a.jpg //注意-ss就是要提取视频文件中指定时间的图像
jpg: ffmpeg -i asf.flv -y -f image2 -t 1 asf.jpg
gif: ffmpeg -i test.asf -vframes 30 -y -f gif a.gif
参考3 参考2([url]http://www.killflash.net/blog/article.asp?id=77[/url])

mencoder -oac copy -ovc copy -idx -o output.avi video1.avi video2.avi video3.avi
* 其中,-oac copy 选项告诉 mencoder 要正确拷贝音频流。而 -ovc copy 选项则是拷贝视频流。
* 如果在视频文件中没有找到索引的话,那么 -idx 选项会要求 mencoder 建立它。
* -o 选项指定输出文件的名称。
* 最后几个参数为需要合并的几个视频片段。
参考1 ([url]http://linuxtoy.org/archives/join_several_videos.html[/url])

场景:想把 MPG 或 AVI 上传到你的服务器并自动转换成 FLV 吗?
1,FFmpeg ([url]http://sourceforge.net/projects/ffmpeg[/url]) | 教程一 ([url]http://soenkerohde.com/tutorials/ffmpeg[/url]) | 教程二 ([url]http://klaus.geekserver.net/flash/streaming.html[/url])(Google Video 使用的就是这个东东.)
2,Flix Engine ([url]http://www.on2.com/developer/flix-engine-sdk[/url]) | 教程 ([url]http://www.flexauthority.com/articlesIndex.cfm[/url]) | 范例 ([url]http://www.flexauthority.com/Samples/FlixEngine/index.html[/url])
3,Turbine Video Engine ([url]http://www.blue-pacific.com/products/turbinevideosdk/default.htm[/url])
4,Video to Flash Console ([url]http://www.geovid.com/Video_to_Flash_Console[/url])

1,RED5 ([url]http://www.osflash.org/red5[/url])
2,Flash Media Server ([url]http://www.macromedia.com/go/fms[/url])
在线编码,分享视频(Online Encode & Share)
1,Google Video ([url]http://video.google.com/[/url])
2,You Tube ([url]http://www.youtube.com/[/url])
本地 FLV 文件播放器(FLV Player)
场景:拿到了 FLV 文件不知道怎么播放了.
1,martijndevisser FLV Player ([url]http://www.martijndevisser.com/2005/10/flv_player_updated.html[/url])
2,FlashGuru FLV Player ([url]http://www.flashguru.co.uk/free-tool-flash-video-player[/url])
3,FCZone FLV Player ([url]http://fczone.com/2006/01/fms-media-player.cfm[/url])
在线 FLV 文件播放器(Online FLV Player)
1,Loadr ([url]http://dengjie.com/loadr[/url])
2,Google Player Generator ([url]http://dengjie.com/loadr/r.swf?file=/temp/google_player.swf&clr=000FFF[/url])
更多相关软件看这篇文章:Flash 网站的视频策略 ([url]http://www.macromedia.com/cfusion/knowledgebase/index.cfm?id=tn_14571[/url])

此文章转自 shadow

ffmpeg 参数



1. 网页文件允许上传视频文件(这个和上传其他文件一样的)(作者用的是python的架构)
2. 后台调用ffmpeg对上传的视频进行压缩,输出flv格式的文件。这个开源程序win32和linux都有实现,所以可以适应不用的主机环境。
3. 使用flvtools处理flv文件,标记上时长、帧速、关键帧等元数据,这样的flash文件才可以拖放。
4. 使用 ffmpeg 产生flv文件的缩略,和大图像文件的缩略图是一个道理。
5. 使用适当的flv播放器在网页中播放服务器端生成的flv文件。


从 [url]http://ffdshow.faireal.net/mirror/ffmpeg/[/url] 下载
最新版本的 FFMpeg.exe直接用就行(须rar解压)。



tar -xvzf lame-3.97.tar.gz;
cd lame-3.97;
./configure –enable-shared –prefix=/usr/;
make install;


编译的时候加上–enable-amr_nb –enable-amr_wb参数就行,根据编译系统的提示,所以我们得下载一些编译3gp所需得文件。

wget [url]http://www.3gpp.org/ftp/Specs/archive/26_series/26.204/26204-510.zip[/url]

wget [url]http://www.3gpp.org/ftp/Specs/archive/26_series/26.104/26104-510.zip[/url]

c、mpg4 aac格式支持,由于服务器还针对手机用户服务,所以,类似aac,mpg4铃声格式的支持,我们也得做。这里我们安装faad2和faac就行

tar zxvf faad2-2.5.tar.gz
cd faad2
echo > plugins/Makefile.am
echo > plugins/xmms/src/Makefile.am
sed -i ‘/E_B/d’ configure.in
autoreconf -vif
./configure –prefix=/usr
make &&
make install

tar zxvf faac-1.25.tar.gz
cd faac
sed -i ‘/[2de].M/d’ configure.in
echo “AC_OUTPUT(common/Makefile common/mp4v2/Makefile libfaac/Makefile frontend/Makefile include/Makefile Makefile)” >> configure.in
autoreconf -vif
./configure –prefix=/usr
make &&
make install

d、支持xvid; x264,现在最流行的两种高质量的压缩格式
wget [url]http://downloads.xvid.org/downloads/xvidcore-1.1.2.tar.gz[/url]
tar zvxf xvidcore-1.1.2.tar.gz

cd xvidcore-1.1.2/build/generic
./configure –prefix=/usr –enable-shared
make install

svn co svn://svn.videolan.org/x264/trunk x264



rpm -ivh nasm-0.98.39-1.i386.rpm(如-ivh不行就用-Uvh)

cd x264
./configure –prefix=/usr –enable-shared
make install

//as4.3系统已经支持ac3编码,只要加–enable-a52 –enable-gpl参数就行
./configure –prefix=/opt/ffmpeg/ –enable-mp3lame –enable-amr_nb –enable-amr_wb –enable-a52 –enable-xvid –enable-x264 –enable-faad –enable-faac –enable-gpl –enable-pthreads;
make clean;//一定要;否则有可能没声音。
make install;

./ffmpeg -i “/opt/input/1.mpg” -y -ab 32 -ar 22050 -b 800000 -s 640*480 /opt/output/1.flv”

./mencoder /input/a.rmvb -oac lavc -lavcopts acodec=mp3:abitrate=64 -ovc xvid -xvidencopts bitrate=600 -of avi -o /output/a.avi
在执行./ffmpeg -i “/opt/input/a.avi” -y -ab 32 -ar 22050 -b 800000 -s 640*480 /opt/output/a.flv”就可以转了。

./ffmpeg -i “/opt/input/a.flv” -y -f image2 -t 1 -s 300*200 “/opt/output/1.jpg” //获取静态图

./ffmpeg -i “/opt/input/a.mpg” -vframes 30 -y -f gif “/output/1.gif” //获取动态图;


MySQL Storage Engine 小记

这段时间在看《High Performance MySQL》,看到存储引擎这个地方感到很多细节比较陌生,所以总结小记一些

为了适应各种不同的运行环境,MYSQL提供了多种不同的存储引擎(Storage Engine ),在应用程序开发这个层面上,开发者可以根据不同的需求选择适合的Storage Engine 方案,更为灵活的是,你可以根据每张表将要存储数据的特点,选择不同的Storage Engine,也就是说,在一个MYSQL数据库中,可以混合使用多种不同的Storage Engine

首先小瞥一下MySQL的体系结构,在最高抽象层度下,可以用Garlan & Shaw的分层结构体系来表示(左)


图中右侧更为具体的描述了逻辑层的组成,查询处理子系统、事务管理子系统、恢复管理子系统和存储管理子系统共同组成了MySQL的逻辑层。相信Storage Engine的位置是在Storage Management处,既Storage Engine属于Storage Management子系统的一部分


上面三幅图来自于一篇非官方(不保证百分百的正确)的MySQL体系结构的报告,与《High Performance MySQL》一书中给出的MySQL大体结构(下图,基本对应于Logic Layer,从第一幅图右侧可以看出MySQL logic layer同样遵从分层体系结构)还是比较吻合的。



上面提到的四种存储引擎都有各自适用的环境,这取决于它们独有的一些特征。主要体现在性能、事务、并发控制、参照完整性、缓存、 故障恢复,备份及回存等几个方面


MyISAM是早期ISAM(Indexed Sequential Access Method,我现在用的MySQL5.0已经不支持ISAM了)的扩展实现,ISAM被设计为适合处理读频率远大于写频率这样一种情况,因此ISAM以及后来的MyISAM都没有考虑对事物的支持,排除了TPM,不需要事务记录,ISAM的查询效率相当可观,而且内存占用很少。MyISAM在继承了这类优点的同时,与时俱进的提供了大量实用的新特性和相关工具。例如考虑到并发控制,提供了表级锁,虽然MyISAM本身不支持容错,但可以通过myisamchk进行故障恢复。而且由于MyISAM是每张表使用各自独立的存储文件(MYD数据文件和MYI索引文件),使得备份及恢复十分方便(拷贝覆盖即可),而且还支持在线恢复。


InnoDB被设计成适用于高并发读写的情况.使用MVCC(Multi-Version Concurrency Control)以及行级锁来提供遵从ACID的事务支持。InnoDB支持外键参照完整性,具备故障恢复能力。另外 InnoDB的性能其实还是不错的,特别是在处理大数据量的情况下,用官方的话说就是: InnoDB的CPU效率是其他基于磁盘的关系数据库存储引擎所不能比的。不过InnoDB的备份恢复要麻烦一点,除非你使用了4.1以后版本提供的Mulit-tablespace支持,因为InnoDB和MyISAM不同,他的数据文件并不是独立对应于每张表的。而是使用的共享表空间,简单的拷贝覆盖方法对他不适用,必须在停掉MYSQL后对进行数据恢复。使用Per-Table Tablespacesd,使其每张表对应一个独立的表空间文件,则情况要简单很多。


至于Heap和BDB(Berkeley DB),相对来说,普及率不如前两种,但在有些情况下,还是挺适用的


BDB是MySQL第一款事务安全的存储引擎。在Berkeley DB database library的基础上建立,同样是事务安全的,但BDB的普及率显然不及InnoDB,因为大多数在MySQL中寻找支持事务的存储引擎的同时也在找支持MVCC或是行级锁定存储引擎,而BDB只支持Page-level Lock。



附上一张《High Performance MySQL》 中的各存储引擎的特性表











Lock granularity



Page (8 KB)



Split files


Single file per table


Isolation levels



Read committed


Portable format





Referential integrity





Primary key with data





MySQL caches data records






All versions

All versions


All Versions


Maven… 它是什么?

1.1. Maven… 它是什么?

如何回答这个问题要看你怎么看这个问题。 绝大部分Maven用户都称Maven是一个”构建工具”:一个用来把源代码构建成可发布的构件的工具。 构建工程师和项目经理会说Maven是一个更复杂的东西:一个项目管理工具。那么区别是什么? 像Ant这样的构建工具仅仅是关注预处理,编译,打包,测试和分发。像 Maven 这样的一个项目管理工具提供了构建工具所提供功能的超集。 除了提供构建的功能,Maven还可以生成报告,生成Web站点,并且帮助推动工作团 队成员间的交流。

一个更正式的 Apache Maven 的定义: Maven是一个项目管理工具,它包含了一个项目对象模型 (Project Object Model),一组标准集合,一个项目生命周期(Project Lifecycle),一个依赖管理系统(Dependency Management System),和用来运行定义在生命周期阶段(phase)中插件(plugin)目标(goal)的逻辑。 当你使用Maven的时候,你用一个明确定义的项目对象模型来描述你的项目,然后 Maven 可以应用横切的逻辑,这些逻辑来自一组共享的(或者自定义的)插件。

别让Maven是一个”项目管理”工具的事实吓跑你。如果你只是在找一个构建工具,Maven能做这个工作。 事实上,本书的一些章节将会涉及使用Maven来构建和分发你的项目。

1.2. 约定优于配置(Convention Over Configuration)

约定优于配置是一个简单的概念。 系统,类库,框架应该假定合理的默认值,而非要求提供不必要的配置。 流行的框架如 Ruby on RailsEJB3 已经开始坚持这些原则,以对像原始的 EJB 2.1 规范那样的框架的配置复杂度做出反应。 一个约定优于配置的例子就像 EJB3 持久化,将一个 特殊的Bean持久化,你所需要做的只是将这个类标注为 @Entity 。 框架将会假定表名和列名是基于类名是属性名。 系统也提供了一些钩子,当有需要的时候你可以重写这些名字,但是,在大部分情况下,你会发现使用框架提供的默认值会让你的项目运行的更快。

Maven通过给项目提供明智的默认行为来融合这个概念。 在没有自定义的情况下,源代码假定是在 ${basedir}/src/main/java,资源文件假定是在 ${basedir}/src/main/resources 。测试代码假定是在 ${basedir}/src/test 。项目假定会产生一个 JAR 文件。Maven 假定你想要把编译好的字节码放到 ${basedir}/target/classes 并且在 ${basedir}/target 创建一个可分发的 JAR 文件。 虽然这看起来无关紧要,但是想想大部分基于 Ant 的构建必须为每个子项目定义这些目录。 Maven 对约定优于配置的应用不仅仅是简单的目录位置,Maven 的核心插件使用了一组通用的约定,以用来编译源代码,打包可分发的构件,生成 web 站点,还有许多其他的过程。 Maven 的力量来自它的”武断”,它有一个定义好的生命周期和一组知道如何构建和装配软件的通用插件。如果你遵循这些约定,Maven 只需要几乎为零的工作——仅仅是将你的源代码放到正确的目录,Maven 将会帮你处理剩下的事情。

使用“遵循约定优于配置”系统的一个副作用是用户可能会觉得他们被强迫使用一种特殊的方法。 当然 Maven 有一些核心观点不应该被怀疑,但是其实很多默认行为还是可配置的。 例如项目源码的资源文件的位置可以被自定义,JAR 文件的名字可以被自定义,在开发自定义插件的时候,几乎任何行为可以被裁剪以满足你特定的环境需求。 如果你不想遵循约定,Maven 也会允许你自定义默认值来适应你的需求。

1.3. 一个一般的接口

在 Maven 为构建软件提供一个一般的接口之前,每个单独的项目都专门有人来管理一个完全自定义的构建系统。开发人员必须在开发软件之外去学习每个他们要参与的新项目的构建系统的特点。 在2001年,构建一个项目如 Turbine 和构建另外一个项目如 Tomcat ,两者方法是完全不同的。如果一个新的进行静态源码分析的源码分析工具面世了,或者如果有人开发了一个新的单元测试框架,每个人都必须放下手头的工作去想办法使这个新东西适应每个项目的自定义构建环境。 如何运行单元测试?世界上有一千种不同的答案。构建环境由无数无休止的关于工具和构建程序的争论所描述刻画。Maven 之前的时代是低效率的时代,是“构建工程师”的时代。

现在,大部分开源开发者已经或者正在使用 Maven 来管理他们新的软件项目。这种转变不仅仅是开发人员从一种构建工具转移到另外一种构建工具,更是开发人员开始为他们的项目采用一种一般的接口。随着软件系统变得越来越模块化,构建系统变得更复杂,而项目的数量更是如火箭般飞速上升。在 Maven 之前,当你想要从 Subversion 签出一个项目如 Apache ActiveMQApache ServiceMix ,然后从源码进行构建,你需要为每个项目留出一个小时来理解给它的构建系统。这个项目需要构建什么?需要现在什么类库?把类库放哪里?构建中我该运行什么目标?最好的情况下,理解一个新项目的构建需要几分钟,最坏的情况下(例如 Jakarta 项目的旧的 Servlet API 实现),一个项目的构建特别的困难,以至于花了几个小时以后,新的贡献者也只能编辑源码和编译项目。现在,你只要签出源码,然后运行: mvn install 。虽然 Maven 有很多优点,包括依赖管理和通过插件重用一般的构建逻辑,但它成功的最核心原因是它定义了构建软件的一般的接口。每当你看到一个使用 Maven 的项目如 Apache Wicket ,你就可以假设你能签出它的源码然后使用 mvn install 构建它,没什么好争论的。你知道点火开关在哪里,你知道油门在右边,刹车在左边。

1.4. 基于Maven插件的全局性重用

Maven 的核心其实不做什么实际的事情,除了解析一些 XML 文档,管理生命周期与插件之外,它什么也不懂。Maven 被设计成将主要的职责委派给一组 Maven 插件,这些插件可以影响 Maven 生命周期,提供对目标的访问。绝大多数 Maven 的动作发生于 Maven 插件的目标,如编译源码,打包二进制代码,发布站点和其它构建任务。你从 Apache 下载的 Maven 不知道如何打包 WAR 文件,也不知道如何运行单元测试,Maven 大部分的智能是由插件实现的,而插件从 Maven 仓库获得。事实上,第一次你用全新的 Maven 安装运行诸如 mvn install 命令的时候,它会从中央 Maven 仓库下载大部分核心 Maven 插件。这不仅仅是一个最小化 Maven 分发包大小的技巧,这种方式更能让你升级插件以给你项目的构建提高能力。Maven 从远程仓库获取依赖和插件的这一事实允许了构建逻辑的全局性重用。

Maven Surefire 插件是负责运行单元测试的插件。从版本 1.0 发展到目前广泛使用的在 JUnit 基础上增加了 TestNG 测试框架支持的版本。这种发展并没有破坏向后兼容性,如果你使用之前 Surefire 插件编译运行你的 JUnit 3 单元测试,然后你升级到了最新版本的 Surefire 插件,你的测试仍然能成功运行。但是,我们又获得了新的功能,如果你想使用 TestNG 运行单元测试,那么感谢 Surefire 插件的维护者,你已经可以使用 TestNG 了。你也能运行支持注解的 JUnit 4 单元测试。不用升级 Maven 安装或者新装任何软件,你就能获得这些功能。更重要的是,除了 POM 中一个插件的版本号,你不需要更改你项目的任何东西。

这种机制不仅仅适用于 Surefire 插件,项目使用 Compiler 插件进行编译,通过 Jar 插件变成 JAR 文件,还有一些插件生成报告,运行 JRuby 和 Groovy 的代码,以及一些用来向远程服务器发布站点的插件。Maven 将一般的构建任务抽象成插件,同时这些插件得到了很好的维护以及全局的共享,你不需要从头开始自定义你项目的构建系统然后提供支持。你完全可以从 Maven 插件获益,这些插件有人维护,可以从远程仓库下载到。这就是基于 Maven 插件的全局性重用。

1.5. 一个“项目”的概念模型

Maven 维护了一个项目的模型,你不仅仅需要把源码编译成字节码,你还需要开发软件项目的描述信息,为项目指定一组唯一的坐标。你要描述项目的的属性。项目的许可证是什么?谁开发这个项目,为这个项目做贡献?这个项目依赖于其它什么项目没有?Maven不仅仅是一个“构建工具”,它不仅仅是在类似于 make 和 Ant 的工具的基础上的改进,它是包含了一组关于软件项目和软件开发的语义规则的平台。这个基于每一个项目定义的模型实现了如下特征:




和项目依赖相关的,我们可以使用定义在项目对象模型(POM)中的坐标来创建 Maven 构件的仓库。




像 Eclipse,NetBeans,和 InteliJ 这样的工具现在有共同的地方来找到项目的信息。在 Maven 出现之前,每个 IDE 都有不同的方法来存储实际上是自定义项目对象模型(POM)的信息。Maven 标准化了这种描述,而虽然每个 IDE 仍然继续维护它的自定义项目文件,但这些文件现在可以很容易的由模型生成。


像 Nexus 这样的工具允许你使用存储在 POM 中的信息对仓库中的内容进行索引和搜索。

Maven 为软件项目的语义一致性描述的开端提供了一个基础。

1.6. Maven是Ant的另一种选择么?

当然,Maven 是 Ant 的另一种选择,但是 Apache Ant 继续是一个伟大的,被广泛使用的工具。它已经是多年以来 Java 构建的统治者,而你很容易的在你项目的 Maven 构建中集成 Ant 构建脚本。这是 Maven 项目一种很常见的使用模式。而另一方面,随着越来越多的开源项目转移到 Maven 用它作为项目管理平台,开发人员开始意识到 Maven 不仅仅简化了构建管理任务,它也帮助鼓励开发人员的软件项目使用通用的接口。Maven 不仅仅是一个工具,它更是一个平台,当你只是将 Maven 考虑成 Ant 的另一种选择的时候,你是在比较苹果和橘子。“Maven”包含了很多构建工具以外的东西。

有一个核心观点使得所有的关于 Maven 和. Ant, Maven 和 Buildr, Maven 和 Grandle 的争论变得无关紧要。Maven并不是完全根据你构建系统的机制来定义的,它不是为你构建的不同任务编写脚本,它提倡一组标注,一个一般的接口,一个生命周期,一个标准的仓库格式,一个标准的目录布局,等等。它当然也不太在意 POM 的格式正好是 XML 还是 YAML 还是 Ruby。它比这些大得多,Maven 涉及的比构建工具本身多得多。当本书讨论 Maven 的时候,它也设计到支持 Maven 的软件,系统和标准。Buildr,Ivy,Gradle,所有这些工具都和 Maven 帮助创建的仓库格式交互,而你可以很容易的使用如 Nexus 这样的工具来支持一个完全由 Buildr 编写的构建。Nexus 将在本书后面介绍。

虽然 Maven 是很多类似工具的另一个选择?但社区需要向前发展,就要看清楚技术是资本经济中不友好的竞争者之间持续的、零和的游戏。这可能是大企业之前相互关联的方式,但是和开源社区的工作方式没太大关系。“谁是胜利者?Ant 还是 Maven”这个大标题没什么建设性意义。如果你非要我们来回答这个问题,我们会很明确的说作为构建的基本技术,Maven 是 Ant 的更好选择;同时,Maven 的边界在持续的移动,Maven 的社区也在持续的是试图找到新的方法,使其更通用,互操作性更好,更易协同工作。Maven 的核心财产是声明性构建,依赖管理,仓库管理,基于插件的高度和重用,但是当前,和开源社区相互协作以降低”企业级构建“的低效率这个目标来比,这些想法的特定实现没那么重要。

1.7. 比较Maven和Ant

虽然上一节应该已经让你确信本书的作者没有兴趣挑起 Apache Ant 和 Apache Maven 之间的争执,但是我们认识到许多组织必须在 Apache Ant 和 Apache Maven 之间做一个选择。本节我们对比一下这两个工具。

Ant 在构建过程方面十分优秀,它是一个基于任务和依赖的构建系统。每个任务包含一组由 XML 编码的指令。有 copy 任务和 javac 任务,以及 jar 任务。在你使用 Ant 的时候,你为 Ant 提供特定的指令以编译和打包你的输出。看下面的例子,一个简单的 build.xml 文件:

Example 1.1. 一个简单的 Ant build.xml 文件

<project name=“my-project” default=“dist” basedir=“.”>
simple example build file
<!– set global properties for this build —>
<property name=“src” location=“src/main/java”/>
<property name=“build” location=“target/classes”/>
<property name=“dist” location=“target”/>

<target name=“init”>
<!– Create the time stamp —>
<!– Create the build directory structure used by compile —>
<mkdir dir=“${build}”/>

<target name=“compile” depends=“init”
description=“compile the source “ >
<!– Compile the java code from ${src} into ${build} —>
<javac srcdir=“${src}” destdir=“${build}”/>

<target name=“dist” depends=“compile”
description=“generate the distribution” >
<!– Create the distribution directory —>
<mkdir dir=“${dist}/lib”/>

<!– Put everything in ${build} into the MyProject-${DSTAMP}.jar file —>
<jar jarfile=“${dist}/lib/MyProject-${DSTAMP}.jar” basedir=“${build}”/>

<target name=“clean”
description=“clean up” >
<!– Delete the ${build} and ${dist} directory trees —>
<delete dir=“${build}”/>
<delete dir=“${dist}”/>

在这个简单的 Ant 例子中,你能看到,你需要明确的告诉 Ant 你想让它做什么。有一个包含 javac 任务的编译目标用来将 src/main/java 的源码编译至 target/classes 目录。你必须明确告诉 Ant 你的源码在哪里,结果字节码你想存储在哪里,如何将这些字节码打包成 JAR 文件。虽然最近有些进展以帮助 Ant 减少程序,但一个开发者对 Ant 的感受是用 XML 编写程序语言。

用 Maven 样例与之前的 Ant 样例做个比较。在 Maven 中,要从 Java 源码创建一个 JAR 文件,你只需要创建一个简单的 pom.xml,将你的源码放在 ${basedir}/src/main/java ,然后从命令行运行 mvn install。下面的样例 Maven pom.xml 文件能完成和之前 Ant 样例所做的同样的事情。

Example 1.2. 一个简单的 Maven pom.xml


这就是你 pom.xml 的全部。从命令行运行 mvn install 会处理资源文件,编译源代码,运行单元测试,创建一个 JAR ,然后把这个 JAR 安装到本地仓库以为其它项目提供重用性。不用做任何修改,你可以运行 mvn site ,然后在 target/site 目录找到一个 index.html 文件,这个文件链接了 JavaDoc 和一些关于源代码的报告。

诚然,这是一个最简单的样例项目。一个只包含源代码并且生成一个 JAR 的项目。一个遵循 Maven 的约定,不需要任何依赖和定制的项目。如果我们想要定制行为,我们的 pom.xml 的大小将会增加,在最大的项目中,你能看到一个非常复杂的 Maven POM 的集合,它们包含了大量的插件定制和依赖声明。但是,虽然你项目的 POM 文件变得增大,它们包含的信息与一个差不多大小的基于 Ant 项目的构建文件的信息是完全不同的。Maven POM 包含声明:“这是一个 JAR 项目”,“源代码在 src/main/java 目录”。Ant 构建文件包含显式的指令:“这是一个项目”,“源代码在 src/main/java ”,“针对这个目录运行 javac ”,“把结果放到 target/classes ”,“从……创建一个 JAR ”,等等。Ant 必须的过程必须是显式的,而 Maven 有一些“内置”的东西使它知道源代码在哪里,如何处理它们。

该例中 Ant 和 Maven 的区别是:

Apache Ant

  • Ant 没有正式的约定如一个一般项目的目录结构,你必须明确的告诉 Ant 哪里去找源代码,哪里放置输出。随着时间的推移,非正式的约定出现了,但是它们还没有在产品中模式化。

  • Ant 是程序化的,你必须明确的告诉 Ant 做什么,什么时候做。你必须告诉它去编译,然后复制,然后压缩。

  • Ant 没有生命周期,你必须定义目标和目标之间的依赖。你必须手工为每个目标附上一个任务序列。

Apache Maven

  • Maven 拥有约定,因为你遵循了约定,它已经知道你的源代码在哪里。它把字节码放到 target/classes ,然后在 target 生成一个 JAR 文件。

  • Maven 是声明式的。你需要做的只是创建一个 pom.xml 文件然后将源代码放到默认的目录。Maven 会帮你处理其它的事情。

  • Maven 有一个生命周期,当你运行 mvn install 的时候被调用。这条命令告诉 Maven 执行一系列的有序的步骤,直到到达你指定的生命周期。遍历生命周期旅途中的一个影响就是,Maven 运行了许多默认的插件目标,这些目标完成了像编译和创建一个 JAR 文件这样的工作。

Maven 以插件的形式为一些一般的项目任务提供了内置的智能。如果你想要编写运行单元测试,你需要做的只是编写测试然后放到 ${basedir}/src/test/java ,添加一个对于 TestNG 或者 JUnit 的测试范围依赖,然后运行 mvn test 。如果你想要部署一个 web 应用而非 JAR ,你需要做的是改变你的项目类型为 war ,然后把你文档根目录置为 ${basedir}/src/main/webapp 。当然,你可以用 Ant 做这些事情,但是你将需要从零开始写这些指令。使用 Ant ,你首先需要确定 JUnit JAR 文件应该放在哪里,然后你需要创建一个包含这个 JUnit JAR 文件的 classpath ,然后告诉 Ant 它应该从哪里去找测试源代码,编写一个目标来编译测试源代码为字节码,使用 JUnit 来执行单元测试。

没有诸如 antlibs 和 lvy 等技术的支持(即使有了这些支持技术),Ant 给人感觉是自定义的程序化构建。项目中一组高效的坚持约定的 Maven POM ,相对于 Ant 的配置文件,只有很少的 XML 。Maven 的另一个优点是它依靠广泛公用的 Maven 插件。所有人使用 Maven Surefire 插件来运行单元测试,如果有人添加了一些针对新的测试框架的支持,你可以仅仅通过在你项目的 POM 中升级某个特定插件的版本来获得新的功能。

使用 Maven 还是 Ant 的决定不是非此即彼的,Ant 在复杂的构建中还有它的位置。如果你目前的构建包含一些高度自定义的过程,或者你已经写了一些 Ant 脚本通过一种明确的方法完成一个明确的过程,而这种过程不适合 Maven 标准,你仍然可以在 Maven 中用这些脚本。作为一个 Maven 的核心插件, Ant 还是可用的。自定义的插件可以用 Ant 来实现,Maven 项目可以配置成在生命周期中运行 Ant 的脚本。

1.8. 总结

我们刻意的使这篇介绍保持得简短。 我们略述了一些Maven定义的要点,它们合起来是什么,它是基于什么改进的,同时介绍了其它构建工具。 下一章将深入一个简单的项目,看 Maven 如何能够通过最小数量的配置来执行典型的任务。



    看到JavaOne2007上有篇《Garbage-Collection-Friendly Programming》的68页PPT,心想都2007了还谈这个基本问题,一定总结得很全面了才好意思站出来讲吧。    

GC的基础概念见上篇:JDK5.0垃圾收集优化之–Don’t Pause  



  • Java的垃圾收集器喜欢短生命周期的对象,对象如果在新生代内,在垃圾收集发生前就死掉了,垃圾收集器就什么都不用做了。
  • 现代JVM构建一个新对象只需要10个本地CPU指令,并不弱于C/C++。 (但垃圾收集没有压缩算法时会稍慢,更频繁的New对象也导致更频繁的GC)。
  • 大对象的分配效率更低,而且对非压缩算法的垃圾收集器,更容易造成碎片。
  • 对象重用增加了代码的复杂度,降低了可读性。



    貌似很酷的把对象主动设为Null 的”好习惯”其实没什么用,JIT Compiler会自动分析local变量的生命周期。
    只有一个例外情况,就是String[1024] foo 这种赤裸裸的数组,你需要主动的foo[100]=null释放第100号元素,所以最好还是直接用ArrayList这些标准库算了。





  • 先用FindBugs 查一下所用到的全部第三方类库吧…
  • 至少RMI 就会老实不客气的执行System.gc()来实现分布式GC算法。但我也不会用RMI啊。那EJB呢,EJB可是建在RMI上的….

    如果无可避免,用-Dsun.rmi.dgc.client.gcInterval=3600000 -Dsun.rmi.dgc.server.gcInterval=3600000 (单位为微妙) 增大大GC的间隔(原默认值为1分钟),-XX:+ExplicitGCInvokesConcurrent 让System.gc() 也CMS并发执行。







   这是个平时不怎么会搭理,偶然知道了又觉得有用的Java特征。大家都知道Java里所有对象除int等基本类型外,都是Pass by Reference的指针,实例只要被一个对象连着,就不会被收集。

  Foo foo = new Foo(); 
  SoftReference sr
= new SoftReference(foo); 
  Foo bar 
=  sr.get(); 



  ReferenceQueue rq = new ReferenceQueue();
= new WeakReference(foo, rq); 
  WeakReference cleaned 
= rq.pool(); 



   java 不是有垃圾收集器了吗?怎么还泄漏啊,唬我啊??

  1. 被生命周期极长的集合类不当持有,号称是Java内存泄漏的首因。
  2. Scope定义不对,这个很简单了,方法的局部变量定义成类的变量,类的静态变量等。
  3. 异常时没有加finally{}来释放某些资源,JDBC时代也是很普遍的事情。
  4. 另外一些我了解不深的原因,如:Swing里的Listener没有显式remove;内部类持有外部对象的隐式引用;Finalizers造成关联对象没有被及时清空等。



  • 看看谁占满了Heap?
    先用jps 找到进程号,然后jmap -histo pid 显示或 jmap -dump:file=heap_file_name pid 导出heap文件
  • 为什么这些对象仍然可以到达?
    用jhat(Java Heap Analysis Tool) 分析刚才导出的heap文件。
    先jhat heap_file_name,然后打开浏览器http://localhost:7000/ 浏览。