Infolinks In Text Ads

May 18, 2017

java questions

    *      What is the use of bin and lib in JDK?- Bin contains all tools such as javac, appletviewer, awt tool, etc., whereas lib contains API and all packages.

    *      What is casting?- Casting is used to convert the value of one type to another.
    *      What is final, finalize() and finally?- final : final keyword can be used for class, method and variables. A final class cannot be subclassed and it prevents other programmers from subclassing a secure class to invoke insecure methods. A final method can’t be overridden. A final variable can’t change from its initialized value. finalize() : finalize() method is used just before an object is destroyed and can be called just prior to garbage collection. finally : finally, a key word used in exception handling, creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block. The finally block will execute whether or not an exception is thrown. For example, if a method opens a file upon exit, then you will not want the code that closes the file to be bypassed by the exception-handling mechanism. This finally keyword is designed to address this contingency.


      What is UNICODE?- Unicode is used for internal representation of characters and strings and it uses 16 bits to represent each other.


      What is Garbage Collection and how to call it explicitly?- When an object is no longer referred to by any variable, java automatically reclaims memory used by that object. This is known as garbage collection. System. gc() method may be used to call it explicitly.

      What are Transient and Volatile Modifiers?- Transient: The transient modifier applies to variables only and it is not stored as part of its object’s Persistent state. Transient variables are not serialized. Volatile: Volatile modifier applies to variables only and it tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program.


      What is method overloading and method overriding?- Method overloading: When a method in a class having the same method name with different arguments is said to be method overloading. Method overriding : When a method in a class having the same method name with same arguments is said to be method overriding.


      What is difference between overloading and overriding?- a) In overloading, there is a relationship between methods available in the same class whereas in overriding, there is relationship between a superclass method and subclass method. b) Overloading does not block inheritance from the superclass whereas overriding blocks inheritance from the superclass. c) In overloading, separate methods share the same name whereas in overriding, subclass method replaces the superclass. d) Overloading must have different method signatures whereas overriding must have same signature.

      What is the difference between this() and super()?- this() can be used to invoke a constructor of the same class whereas super() can be used to invoke a super class constructor.

      What are inner class and anonymous class?- Inner class : classes defined in other classes, including those defined in methods are called inner classes. An inner class can have any accessibility including private. Anonymous class : Anonymous class is a class defined inside a method without a name and is instantiated and declared in the same place and cannot have explicit constructors.

      What is a reflection package?- java. lang. reflect package has the ability to analyze itself in runtime.

      What is the difference between Integer and int?- a) Integer is a class defined in the java. lang package, whereas int is a primitive data type defined in the Java language itself. Java does not automatically convert from one to the other. b) Integer can be used as an argument for a method that requires an object, whereas int can be used for calculations.


      What is a cloneable interface and how many methods does it contain?- It is not having any method because it is a TAGGED or MARKER interface.


      What is the difference between abstract class and interface?- a) All the methods declared inside an interface are abstract whereas abstract class must have at least one abstract method and others may be concrete or abstract. b) In abstract class, key word abstract must be used for the methods whereas interface we need not use that keyword for the methods. c) Abstract class must have subclasses whereas interface can’t have subclasses.

      What is daemon thread and which method is used to create the daemon thread?- Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system. setDaemon method is used to create a daemon thread.

      What is the difference between applications and applets?- a)Application must be run on local machine whereas applet needs no explicit installation on local machine. b)Application must be run explicitly within a java-compatible virtual machine whereas applet loads and runs itself automatically in a java-enabled browser. d)Application starts execution with its main method whereas applet starts execution with its init method. e)Application can run with or without graphical user interface whereas applet must run within a graphical user interface.

      How does applet recognize the height and width?- Using getParameters() method.

      How do you set security in applets?- using setSecurityManager() method

      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.

      What is the difference between an applet and a servlet?- a) Servlets are to servers what applets are to browsers. b) Applets must have graphical user interfaces whereas servlets have no graphical user interfaces.

      What is a Java Bean?- A Java Bean is a software component that has been designed to be reusable in a variety of different environments.


      What is a Jar file?- Jar file allows to efficiently deploying a set of classes and their associated resources. The elements in a jar file are compressed, which makes downloading a Jar file much faster than separately downloading several uncompressed files. The package java. util. zip contains classes that read and write jar files.

May 4, 2011

Capture image from webcam java code, examples

import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;

import javax.swing.JButton;
import javax.swing.JComponent;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class Camagain extends Applet implements ActionListener {

    private static final long serialVersionUID = -196359544994677518L;
    public static Player player;
    public CaptureDeviceInfo DI;
    public MediaLocator ML;
    public JButton CAPTURE;
    public Buffer BUF;
    public Image img;
    public VideoFormat VF;
    public BufferToImage BtoI;
    public ImagePanel imgpanel;
    public javax.swing.Timer timer = new javax.swing.Timer(200, this); // 200ms is too fast increase it to suit your need

    public void init(){
         purl = getParameter("url");
         url = purl;
        setLayout(new BorderLayout());
        setSize(320, 600);

        imgpanel = new ImagePanel();
        CAPTURE = new JButton("Capture");

        String str1 = "vfw:Logitech USB Video Camera:0";
        String str2 = "vfw:Microsoft WDM Image Capture (Win32):0";
        DI = CaptureDeviceManager.getDevice(str2);
        ML = new MediaLocator("vfw://0");

        try {
            player = Manager.createRealizedPlayer(ML);
            Component comp;
            if ((comp = player.getVisualComponent()) != null) {
                add(comp, BorderLayout.NORTH);
            add(CAPTURE, BorderLayout.CENTER);
            add(imgpanel, BorderLayout.SOUTH);
            Thread.sleep(5000);     // this is important, otherwise you may get NPE somewhere, needs polishing ;-)
            timer.start();                // start timer
        } catch (Exception e) {
    public void executeCapture(Camagain cf) {
        Frame f = new Frame("SwingCapture");
        //camagain cf = new camagain();   // I didn't had 'SwingCapture, so I added camgain.....

        f.addWindowListener(new WindowAdapter() {

            public void windowClosing(WindowEvent e) {

        f.add("Center", cf);
        f.setSize(new Dimension(320, 600));
    public static void playerclose() {

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() instanceof JComponent) {
            JComponent c = (JComponent) e.getSource();
            if (c == CAPTURE) {
                actionCapture();  // maoved every thing to new method action()
        } else if (e.getSource() instanceof javax.swing.Timer) {
            action();       // timer event , call action() again

    public void action() {    // your action handler code.....
        // Grab a frame
        FrameGrabbingControl fgc = (FrameGrabbingControl) player.getControl("");
        BUF = fgc.grabFrame();

        // Convert it to an image
        BtoI = new BufferToImage((VideoFormat) BUF.getFormat());
        img = BtoI.createImage(BUF);

        // show the image

        // save image
       /* String path = System.getProperty("user.home")+"/xtest.jpg";
        // save image
        saveJPG(img, path);*/

        /*System.out.println("Before Alert----");
        try {
              (new URL("javascript:webImageShow(\"" + path +"\")"));
          catch (MalformedURLException me) { }
          System.out.println("After Alert----");*/

    public void actionCapture() {    // your action handler code.....
        // Grab a frame
        FrameGrabbingControl fgc = (FrameGrabbingControl) player.getControl("");
        BUF = fgc.grabFrame();

        // Convert it to an image
        BtoI = new BufferToImage((VideoFormat) BUF.getFormat());
        img = BtoI.createImage(BUF);

        // show the image

        // save image
        String fileName = System.currentTimeMillis()+".jpg";
        String path = System.getProperty("user.home")+"/"+fileName;
        // save image
        saveJPG(img, path);
        //upload(path, url);
        //Upload upload1 = new Upload(null, path, "");
        Upload upload1 = new Upload(null, path, url);
        (new Thread(upload1)).start();
       //path = path.replace("\\", "/");
        //System.out.println("Before Alert----" + path);
        try {
              (new URL("javascript:webImageShow(\"" + fileName +"\")"));
          catch (MalformedURLException me) { }
          System.out.println("After Alert----");
    class ImagePanel extends Panel {

        public Image myimg = null;

        public ImagePanel() {
            setSize(320, 240);

        public void setImage(Image img) {
            this.myimg = img;

        public void paint(Graphics g) {
            g.drawImage(myimg, 0, 0, this);

    public static void saveJPG(Image img, String s) {
        BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = bi.createGraphics();
        g2.drawImage(img, null, null);
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(s);
        } catch ( io) {
            System.out.println("File Not Found");

        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
        param.setQuality(0.5f, false);

        try {
        } catch ( io) {
    String url;
    String purl;

Feb 12, 2011

Map.Entry Interface

Map.Entry Interface -
    Map.Entry Interface is used to hold the view of key-value pair from Map.
Map interface has a method entrySet() which returns the Set object that holds the key value pair. You can iterate the key and value from getKey() and getValue().
You can also set value an element by the setValue() method.

List of methods within the Map.Entry Interface -

 boolean equals(Object o) -
         This method is used to compares the specified object with this entry. If both are equal it return true otherwise return false.

 K getKey() -
    This method returns the key of map.

 V getValue() -
    This method returns the value of corresponding to this entry.

 int hashCode() -
    This method is used to return the hash code value for this map entry.

 V setValue(V value) -
    This method is used to set the values at  corresponding the key.

Example -
public class Test {
    public static void main(String[] args) {
        Map map = new HashMap();
        Iterator s = map.entrySet().iterator();
            Map.Entry m = (Map.Entry);


ListIterator Interface

ListIterator Interface -
    ListIterator Interface is used for traverse list in both direction. You can find previous element by previous() method and next element by next() method. Within the both method ListIterator maintain the cursor position. ListIterator has previousIndex() for checking that List has previous index or not.
     ListIterator Interface extends Iterator Interface. You can also set any new element in the list.

List of methods within the ListIterator Interface -

void add(E e) -
    This method is used to add a given element into the list.

boolean hasNext() -
    This method is used to check the presence of element in the list when traversing the list in the forward direction.

boolean hasPrevious() -
    This method is used to check the presence of element in the list when traversing the list in the reverse direction.

E next() -
    this method is used to return the next element in the list.

int nextIndex() -
    This method is used for return the index of the next element in the list.

E previous() -
          this method is used to return the previous element in the list.

int previousIndex() -
    This method is used for return the index of the previous element in the list.
void remove() -
          This method is used for removes element from the list at the cursor position.

void set(E e) -
    This method is used to replace the element at the cursor position.


Related Posts Plugin for WordPress, Blogger...