JGuru
Wise Old Owl
Java : Interview Questions & Answers
Most of guys dread the Java interview in a company. Here are some of the frequently asked questions to help you
prepare for the interview in a better way. Read on and memorize these questions & answers.
Also understand the core concepts. You must read the following books:
1) Core Java by by C S Horstmann (2 volumes) - Helps to understand the core concepts in Java language
2) The Java FAQ by Jonni Kanerva - Helps you prepare for the interview questions
3) Java How To Program by H M Deitel & P J Deitel - Learn how to program using Java language
4) Beginning Java Objects (Wrox)/ Big Java Late Objects by Cay S. Horstmann - Learn Object-Oriented Programming in Java
5) Data Structures & Algorithms in Java by Robert Lafore / Algorithms in Java 4th Edition by Robert SedgeWick - Learn & understand the data structures & algorithms
Candidates are also advised to polish their English language skills - Spoken English.
You can read some good English magazine , newspaper, Watch TV channels - BBC, CNN etc.,
And finally you should study more Java books , write more programs. Then only you will be able to program better.
Work 12 hours a day writing Java programs, studying Java books for 6 months. Then write a project in Java (6 months to 12 months).
The candidates with poor communication skills & programming skills will not be selected.
I know Java is not enough to get a IT job. You must be able to program well using Java language.
To become a good Java programmer you must study more books , write more Java programs. Practise, practise, practise is the mantra!!!
So work very hard & get your dream IT job.
1) What is an Object?
Ans. An object is a software unit that combines a structured set of data with a set of operations for inspecting and manipulating
that data.Object-oriented programming reverses the function-data relationship familiar from non-object-oriented languages, like C, Pascal, Basic are often
based on direct data manipulation: they define data structures and provide functions that inspect or change that data from anywhere else
in the program.Object-orinted programming provides standard tools and techniques for reducing dependencies between different parts of a program.
An object starts with a structured set of data, but also includes a set of operatins for inspecting and manipulating that data.
2) What is a Class?
Ans. A Class is a blueprint for objects: it defines a type of object according to the data the object can hold and the operations the object can perform.
Classes are the fundamental units of design in object-oriented programming. A class is a pattern that defines a kind of object. It
specifies a data structure for the object together with a set of operations for acting on the the object's data.
3) What Is Inheritance?
Ans. Inheritance is the way a subclass uses the method definitions and variables from a superclass just as if they belonged to the subclass itself.
Inheritance is a powerful mechanism for reusing code.Inheritance provides a chain in which a class inherits not only from its
immediate superclass, but also from any superclass upwards to the Object class. All Java classes ultimately inherit from Object.
4) What is the difference between overriding & overloading?
Ans. Overloading occurs when two or more methods use the same name, but different parameter lists, such that both methods are
available side by side in the same class;overriding occurs when a subclass method and a superclass method use the same name
and matching parameter lists, such that the subclass method blocks out the superclass method.
Here in the following demo the print method is overloaded. it takes different arguments.
Here is a demo to show overriding.
Here the method setSize() is overriden. class Rectangle has it's own setSize(). class DisplayedRectangle defines it's own
setSize() method. Thus the sublass DisplayedRectangle defines it's own behaviour.
5) What is the use for the final keyword ?
Ans. Using the final keyword in the Java language has the general meaning that you define an entity once and cannot change it
or derive from it later. More specifically:
* A final class cannot be subclassed
* A final method cannot be overridden
* A final variable cannot change from its initialized value.
Classes are usually declared final for either performance or security reasons. On the performance side, the compiler can optimize
final classes to avoid dynamic method lookup because their method implementations are never overridden.
6) What is an interface?
Ans. In the Java language , an interface is like a stripped-down class: it specifies a set of methods that an instance must
handle, but it omits inheritance relations and method implementations.
For eg., the Runnable interface in the java.lang package is declared as follows :
Interfaces provide the minimal level of dependence between interacting objects. An interface can also contain static final variables called class constants.
7) Does Java language allow mutiple inheritance?
Ans. Yes and no.
A class in Java can implement any number of interfaces (mutiple interface inheritance) but can extend exactly one immediate superclass from which it inherits implementations (single class inheritance)
Similarly, an interface can have any number of superinterfaces. which are declared with the extends keyword.
For eg.,
Finally, does an interface have any superclasses? Yes. all interfaces are treated as having one superclass: the Object class. This amounts to a claim that
whatever class implements the interface will be a sublcass of Object.
8) What is a package?
Ans. A package is a namespace that organizes a set of related classes and interfaces.
A package groups together a set of classes and interfaces that need to work as a coherent whole. The java.io package for instance
contains classes and interfaces for managing various kinds of input and output.
9) If Java doesn't have pointers, how do I write classic data structures like a LinkedList?
Ans. Use object references in place of pointers.
Object references in Java are like object pointers minus the arithmetic. The Java language lets you refer to objects;it just doesn't let you change
numbers into references, references into numbers or otherwise treat references in a numerical way.
10) What is an exception?
Ans. An exception is a condition (typically an error condition) that transfers program execution from a thrower (at the source of the condition)
to a catcher (the handler for the condition);information about the condition is passes as an Exception or Error object.
11) What is the difference between a runtime exception and a plain exception - Why don't runtime exceptions have to be declared?
Ans. The Java language specifies that all runtime exceptions are exempted from the standard method declarations and compiler checks;
such exceptions belong more to the system as a whole than to the method that happens to be executing when the exception is thrown.
The checked exceptions describe the problems that can arise in a correct program, typically difficulties with the environment such as
user mistakes or I/O problems. For eg., attempting to open a socket can fail if the remote machine does not exist, is not providing the
requested service.Because these conditions can arise any time in a commercial-grade program you must write code to handle and recover from them.
In fact the Java compiler checks that you have indeed stated what is to be done when they arise. and it's because of this checking that they are called
checked exceptions.
12) When and by whomm is the main method of a class invoked?
Ans. Normally, you don't invoke main yourself: the Java Virtua;l Machine (JVM) invokes it for you if it uses your class as its starting point of execution.
A JVM always starts execution from the main method of some class. Even a large Java application like NetBeans starts exeuction
in one class's main method. The main method must be decalred as public and static, it must have no return value, and it must declare a String array as its sole
parameter.
13) What are bytecodes?
Ans. Java bytecodes are a language of machine instaructions understood by the Java Virtual Machine (JVM) and are generated from
the Java language source code.
Java bytecodes encode instructions for the JVM.The instructions specify both operations and operands, always in the following
format.
* opcode (1 byte): specifies what operation to perform
* operands (0-n bytes): specify data for the operation
14) What does it mean to say that Java is interpreted?
Ans. Several implementations of the JVM interpret the compiled Java code (virtual machine instructions) - for each
instruction, the virtual machine carries out the specified behaviour before reading the next instruction.
Interpretion also involves translating code from one language to another, except you directly excute the translation instead of
storing it. The JVM instructions which were compiled from source code are interpreted by the virtual machine - converted on the
fly into native machine code, which is then executed rather than stored.
15) What is garbage collection?
Ans. The Java Virtual Machine is required to provide automatic storage management for objects.
For instance, the storage space for all objects is allocated from a central Java heap, and a running Java program
uses pointers into the heap area called object references to access its objects.When a program no longer holds a reference
to an object, that object's space on the heap can be reclaimed or garbage collected. Automatic garbage collection means
that the run-time system, not the programmer , is responsible for tracking memory use and deciding when to free memory
that is no longer needed.
16) What is an Applet?
Ans. An applet is a Java program that you can embed in a web page.
An applet itself is fairly simple; it is usually composed of several pieces:
* code : the Java class files that represent the executable code of the applet
* other resources : data needed by the applt, including images and sound.
17) Can I write a Java code that works both as an applet and a stand-alone application?
Ans. Yes, but with limitations.
Applets and applications share the standard Java class libraries, including the user-interface tools in the Abstract Window Toolkit (AWT).
These classes let you present a user interface, handle events, manage input and output (subject to security restrictions)
and generally define objects and their interactions.
To work as a combined applet/application your Applet subclass must include a main method: The main method is required as the starting
point for all applications.
You must also include the init, start, stop, destroy methods.
Here is a code that does just that!
18) What is the paint method for when is it invoked, and by whom?
Ans. The paint method is usually invoked by Abstract Window Toolkit(AWT), via the update method, in order to provide
an up-to-date image on screen of the component.The paint method is the fundamental means by which an AWT component draws itself on the screen. Typically , paint is
invoked for you by update, but it can also be invoked directly, bypassing update, such as when a Component is scrolled
or resized or when the part of the window is exposed after being covered by another window.You must put the minimum necessary
to paint your Component completely and quickly.
19) What is a thread?
Ans. A thread is a sequence of executing instructions that run independently of other thread yet can directly share data with other
threads.Threads let you organize your program into logically separate paths of execution. Mutiple threads are like independent agents at your
disposal. You give eache one a list of instructions and then send it off on its way. From the individual thread's perspective,
life is simple:it works on its own list of instructions until it either finishes the list or is told to stop.In this respect, a
thread resembles a process or a separately running program.
20) What is a monitor?
Ans. A monitor is a one-thread at a time set of code blocks and methods that also provides a wait-notify service.
When multiple threads access common changeable data , you must regulate the timing of those threads to ensure that one thread doesn't interfere
with another thread's assumptions of data integrity. The Java platform lets you restrict thread interactions by means of monitors.
A monitor groups a set of code blocks into a single protected space, such that only one thread at a time can be in the monitor,
that is , executing any code under the monitor's protection.
A monitor uses a mutual exclusion lock to protect its region of code.A thread must acquire the lock in order to enter the monitor, and
it relinquishes the lock when it exits the monitor.
21) If Java is platform-independant, why doesn't it run on all the platforms?
Ans. The Java language , standard class libraries , and compiled class files are platform-independent, but the Java Virtual Machine (JVM)
underneath them must be ported to specific native platforms (native code usually in C/C++) one by one.
Since most of the Java libraries are written in Java language, the work is already half done.The Java API also defines cross-platform
capabilities and behaviours which gets mapped onto specific native platforms(native code usually in C language).Your Java program
should essentially behave the same way across all the platforms(Windows, Solaris, Mac OS, Linux etc.,)
22) How do I obtain the performance profile of my Java program?
Ans. You can use the Java interpreter's -prof option. This creates a java,prof file with the information about which methods call
data - how much time is spent executing a given method.
java -prof classname
23)Why does my Java program throws java.lang.OutOfMemoryError even though there is enough memory for the program to run.
How do I solve this?
Ans. Your Java program is throwing java.lang.OutOfMemoryError since the program doesn't get the memory required for it to run properly.
You can allocate more memory (heap area) for your Java program as follows :
java -Xms128m -Xmx256m classname
Here we allocate a initial memory of 128 MB (-Xms128m) and a maximum of 256 MB (-Xmx256m). Where classname is the name of the class (your program)
Q) What project have you done in Java?
Ans. Show the Project book containing the screenshots , synopsis, diagrams etc.,
Explain the project in detail.
Here is the list of projects that you can do in Java :
Q) What are the projects I can do in Java?
Ans. You can write a GUI (Swing) application, applet or a e-commerce application (Servlet/JSP) or a JavaME (Java Micro Edition).
Here are some projects that you can do.
Swing (GUI)
1) Banking System
2) Customer Relationship Software (CRM)
3) Text Editor (TextPad)
4) Integrated Development Environment (IDE like NetBeans, Eclipse, JDeveloper) (NOTE : IDE Development is only for Java experts !!, not for novice programmers!!!)
5) Media Player (WinAmp, iTunes)
6) Web Browser (FireFox, Chrome, Opera)
7) Image Processing (PhotoShop, GIMP)
8) Peer to Peer (P2P like LimeWire)
9) DataBase Explorer
10) Download Manager (FlashGet, DAP)
11) RDBMS (Oracle, DB2, SQL Server)
12) Supply Chain Management (SCM)
13) Text to Speech Converter
14) Accounting (Tally, Busy)
15) 3D Modelling program (using Java3D - like Blender, ZBrush, Sculptris)
16) Geographical Information System (GIS)
17) Enterpise Resource Planning (ERP like SAP, Oracle Financials)
18) Compiler design in Java ( Compiler design is for Java experts , it needs professional expertise!!! It's not for novice programmers!!!)
19) Stock Market monitoring Applet or application
20) XML Editor
21) Zip archiver like WinZip, WinRAR
22) UML Editor (Unified Modeling Language)
23) FTP Client
24) Web Server
25) Voice Chat & Video Conferencing (using JMF)
26) Word processor (like MS Word )
E-Commerce (JSP/Servlets)
1) Banking System
2) HRM (Human Resource Management)
3) Airline Reservation System
4) Job Portal System (naukri.com, monster.com)
5) Inventory Management System
6) Hotel Management System
7) Energy Billing System
8) Travel Billing System
9) Online ecommerce Portal (eBay, amazon.com)
10) Telecom management System
11) Voice chat & Video conferencing (using JMF)
Mobile Development (JavaME)
1) M-commerce
2) Game Development
3) Media Player
4) Web Crawler
5) Download Manager
6) Web Browser
Q) What are the books I need to study, to write a Project in Java ?
Ans.
Must read Books for writing Java Projects:
1) Core Java - Vol -I & II by Horstmann C S
2) Beginning Java Objects (Wrox)/ Object-Oriented Programming in Java by Balagurusamy
3) Java Tutorial 5th Edition
4) Graphic Java 2 ,Volume 2 Swing: Mastering the JFC by David M Geary
5) Data Structures & Algorithms in Java by Robert Lafore (Techmedia) / Algorithms in Java 4th Edition by Robert SedgeWick
6) The Java Developers Almanac 1.4, Volume I & II by Patrick Chan
7) Java Swing 5th Edition by Eckstein (Oreilly)
8) Thinking in Java
9) Object-Oriented Design in Java by Stephen Gilbert and Bill McCarty
10) Oracle Database JDBC Developer's Guide & Reference
11) Beginning Java Databases / Java Database Programming Bible by John O' Donahue
12) Professional Java Programming (Wrox)
13) Beginning Java Networking (Wrox)/ An Itroduction to Network Programming with Java : Java 7 Compatible by Jan Graba
14) JSP 2.0 : The Complete Reference by Phil Hanna (Tata McGraw Hill)
15) Struts : The Complete Reference (Tata McGraw Hill)
16) Mastering HTML 5 (Sybex/ BPB)
17) Professional Java Networking (Wrox)
18) Oracle 12c: The Complete Reference (Tata McGraw Hill)
19) Java Threads (Oreilly)
20) Java How To Program by H M Deitel & P J Deitel
21) Software Engineering in Java
23) Desktop Java Live (Discusses various Layout Managers , GUI Builders, Swing Threading, Data Binding , Validation, Packaging & Deployment )
24) Java Servlet Programming by Jason Hunter, William Crawford (Oreilly)
Study the best Java books, work hard write more Java code and succeed in life!!
Goodluck!!
Most of guys dread the Java interview in a company. Here are some of the frequently asked questions to help you
prepare for the interview in a better way. Read on and memorize these questions & answers.
Also understand the core concepts. You must read the following books:
1) Core Java by by C S Horstmann (2 volumes) - Helps to understand the core concepts in Java language
2) The Java FAQ by Jonni Kanerva - Helps you prepare for the interview questions
3) Java How To Program by H M Deitel & P J Deitel - Learn how to program using Java language
4) Beginning Java Objects (Wrox)/ Big Java Late Objects by Cay S. Horstmann - Learn Object-Oriented Programming in Java
5) Data Structures & Algorithms in Java by Robert Lafore / Algorithms in Java 4th Edition by Robert SedgeWick - Learn & understand the data structures & algorithms
Candidates are also advised to polish their English language skills - Spoken English.
You can read some good English magazine , newspaper, Watch TV channels - BBC, CNN etc.,
And finally you should study more Java books , write more programs. Then only you will be able to program better.
Work 12 hours a day writing Java programs, studying Java books for 6 months. Then write a project in Java (6 months to 12 months).
The candidates with poor communication skills & programming skills will not be selected.
I know Java is not enough to get a IT job. You must be able to program well using Java language.
To become a good Java programmer you must study more books , write more Java programs. Practise, practise, practise is the mantra!!!
So work very hard & get your dream IT job.
1) What is an Object?
Ans. An object is a software unit that combines a structured set of data with a set of operations for inspecting and manipulating
that data.Object-oriented programming reverses the function-data relationship familiar from non-object-oriented languages, like C, Pascal, Basic are often
based on direct data manipulation: they define data structures and provide functions that inspect or change that data from anywhere else
in the program.Object-orinted programming provides standard tools and techniques for reducing dependencies between different parts of a program.
An object starts with a structured set of data, but also includes a set of operatins for inspecting and manipulating that data.
2) What is a Class?
Ans. A Class is a blueprint for objects: it defines a type of object according to the data the object can hold and the operations the object can perform.
Classes are the fundamental units of design in object-oriented programming. A class is a pattern that defines a kind of object. It
specifies a data structure for the object together with a set of operations for acting on the the object's data.
3) What Is Inheritance?
Ans. Inheritance is the way a subclass uses the method definitions and variables from a superclass just as if they belonged to the subclass itself.
Inheritance is a powerful mechanism for reusing code.Inheritance provides a chain in which a class inherits not only from its
immediate superclass, but also from any superclass upwards to the Object class. All Java classes ultimately inherit from Object.
4) What is the difference between overriding & overloading?
Ans. Overloading occurs when two or more methods use the same name, but different parameter lists, such that both methods are
available side by side in the same class;overriding occurs when a subclass method and a superclass method use the same name
and matching parameter lists, such that the subclass method blocks out the superclass method.
Here in the following demo the print method is overloaded. it takes different arguments.
Code:
class OverloadDemo {
Overload() {
}
void print(String str) {
// implementation not shown
}
void print(int num) {
// implementation not shown
}
}
Here is a demo to show overriding.
Code:
class Rectangle {
int x, y, w, h;
public void setSize(int w, int h) {
this.w = w;
this.h = h;
}
}
class DisplayedRectangle extends Rectangle {
public void setSize(int w, int h) {
this.w = w;
this.h = h;
redisplay();
}
public void redisplay() {
// implementation not shown
}
}
Here the method setSize() is overriden. class Rectangle has it's own setSize(). class DisplayedRectangle defines it's own
setSize() method. Thus the sublass DisplayedRectangle defines it's own behaviour.
5) What is the use for the final keyword ?
Ans. Using the final keyword in the Java language has the general meaning that you define an entity once and cannot change it
or derive from it later. More specifically:
* A final class cannot be subclassed
* A final method cannot be overridden
* A final variable cannot change from its initialized value.
Classes are usually declared final for either performance or security reasons. On the performance side, the compiler can optimize
final classes to avoid dynamic method lookup because their method implementations are never overridden.
6) What is an interface?
Ans. In the Java language , an interface is like a stripped-down class: it specifies a set of methods that an instance must
handle, but it omits inheritance relations and method implementations.
For eg., the Runnable interface in the java.lang package is declared as follows :
Code:
public interface Runnable {
public abstract void run();
}
Interfaces provide the minimal level of dependence between interacting objects. An interface can also contain static final variables called class constants.
7) Does Java language allow mutiple inheritance?
Ans. Yes and no.
A class in Java can implement any number of interfaces (mutiple interface inheritance) but can extend exactly one immediate superclass from which it inherits implementations (single class inheritance)
Similarly, an interface can have any number of superinterfaces. which are declared with the extends keyword.
For eg.,
Code:
// interfaces Redable, Writable declared elsewhere
public interface StreamInputOutput extends Readable, Writable {
// .. additional methods not in Readable or Writable
}
Finally, does an interface have any superclasses? Yes. all interfaces are treated as having one superclass: the Object class. This amounts to a claim that
whatever class implements the interface will be a sublcass of Object.
8) What is a package?
Ans. A package is a namespace that organizes a set of related classes and interfaces.
A package groups together a set of classes and interfaces that need to work as a coherent whole. The java.io package for instance
contains classes and interfaces for managing various kinds of input and output.
9) If Java doesn't have pointers, how do I write classic data structures like a LinkedList?
Ans. Use object references in place of pointers.
Object references in Java are like object pointers minus the arithmetic. The Java language lets you refer to objects;it just doesn't let you change
numbers into references, references into numbers or otherwise treat references in a numerical way.
10) What is an exception?
Ans. An exception is a condition (typically an error condition) that transfers program execution from a thrower (at the source of the condition)
to a catcher (the handler for the condition);information about the condition is passes as an Exception or Error object.
11) What is the difference between a runtime exception and a plain exception - Why don't runtime exceptions have to be declared?
Ans. The Java language specifies that all runtime exceptions are exempted from the standard method declarations and compiler checks;
such exceptions belong more to the system as a whole than to the method that happens to be executing when the exception is thrown.
The checked exceptions describe the problems that can arise in a correct program, typically difficulties with the environment such as
user mistakes or I/O problems. For eg., attempting to open a socket can fail if the remote machine does not exist, is not providing the
requested service.Because these conditions can arise any time in a commercial-grade program you must write code to handle and recover from them.
In fact the Java compiler checks that you have indeed stated what is to be done when they arise. and it's because of this checking that they are called
checked exceptions.
12) When and by whomm is the main method of a class invoked?
Ans. Normally, you don't invoke main yourself: the Java Virtua;l Machine (JVM) invokes it for you if it uses your class as its starting point of execution.
A JVM always starts execution from the main method of some class. Even a large Java application like NetBeans starts exeuction
in one class's main method. The main method must be decalred as public and static, it must have no return value, and it must declare a String array as its sole
parameter.
13) What are bytecodes?
Ans. Java bytecodes are a language of machine instaructions understood by the Java Virtual Machine (JVM) and are generated from
the Java language source code.
Java bytecodes encode instructions for the JVM.The instructions specify both operations and operands, always in the following
format.
* opcode (1 byte): specifies what operation to perform
* operands (0-n bytes): specify data for the operation
14) What does it mean to say that Java is interpreted?
Ans. Several implementations of the JVM interpret the compiled Java code (virtual machine instructions) - for each
instruction, the virtual machine carries out the specified behaviour before reading the next instruction.
Interpretion also involves translating code from one language to another, except you directly excute the translation instead of
storing it. The JVM instructions which were compiled from source code are interpreted by the virtual machine - converted on the
fly into native machine code, which is then executed rather than stored.
15) What is garbage collection?
Ans. The Java Virtual Machine is required to provide automatic storage management for objects.
For instance, the storage space for all objects is allocated from a central Java heap, and a running Java program
uses pointers into the heap area called object references to access its objects.When a program no longer holds a reference
to an object, that object's space on the heap can be reclaimed or garbage collected. Automatic garbage collection means
that the run-time system, not the programmer , is responsible for tracking memory use and deciding when to free memory
that is no longer needed.
16) What is an Applet?
Ans. An applet is a Java program that you can embed in a web page.
An applet itself is fairly simple; it is usually composed of several pieces:
* code : the Java class files that represent the executable code of the applet
* other resources : data needed by the applt, including images and sound.
17) Can I write a Java code that works both as an applet and a stand-alone application?
Ans. Yes, but with limitations.
Applets and applications share the standard Java class libraries, including the user-interface tools in the Abstract Window Toolkit (AWT).
These classes let you present a user interface, handle events, manage input and output (subject to security restrictions)
and generally define objects and their interactions.
To work as a combined applet/application your Applet subclass must include a main method: The main method is required as the starting
point for all applications.
You must also include the init, start, stop, destroy methods.
Here is a code that does just that!
Code:
import java.applet.Applet;
import java.awt.AWTEvent;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Canvas;
import java.awt.Choice;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.FontMetrics;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Label;
import java.awt.LayoutManager;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.TextEvent;
import java.awt.image.ColorModel;
import java.awt.image.MemoryImageSource;
enum DitherMethod {
NOOP, RED, GREEN, BLUE, ALPHA, SATURATION
};
[MENTION=139512]Sup[/MENTION]pressWarnings("serial")
public class DitherTest extends Applet implements Runnable {
private Thread runner;
private DitherControls XControls;
private DitherControls YControls;
private DitherCanvas canvas;
public static void main(String args[]) {
Frame f = new Frame("DitherTest");
DitherTest ditherTest = new DitherTest();
ditherTest.init();
f.add("Center", ditherTest);
f.pack();
f.setVisible(true);
ditherTest.start();
}
@Override
public void init() {
String xspec = null, yspec = null;
int xvals[] = new int[2];
int yvals[] = new int[2];
try {
xspec = getParameter("xaxis");
yspec = getParameter("yaxis");
} catch (NullPointerException ignored) {
//only occurs if run as application
}
if (xspec == null) {
xspec = "red";
}
if (yspec == null) {
yspec = "blue";
}
DitherMethod xmethod = colorMethod(xspec, xvals);
DitherMethod ymethod = colorMethod(yspec, yvals);
setLayout(new BorderLayout());
XControls = new DitherControls(this, xvals[0], xvals[1],
xmethod, false);
YControls = new DitherControls(this, yvals[0], yvals[1],
ymethod, true);
YControls.addRenderButton();
add("North", XControls);
add("South", YControls);
add("Center", canvas = new DitherCanvas());
}
private DitherMethod colorMethod(String s, int vals[]) {
DitherMethod method = DitherMethod.NOOP;
if (s == null) {
s = "";
}
String lower = s.toLowerCase();
for (DitherMethod m : DitherMethod.values()) {
if (lower.startsWith(m.toString().toLowerCase())) {
method = m;
lower = lower.substring(m.toString().length());
}
}
if (method == DitherMethod.NOOP) {
vals[0] = 0;
vals[1] = 0;
return method;
}
int begval = 0;
int endval = 255;
try {
int dash = lower.indexOf('-');
if (dash < 0) {
endval = Integer.parseInt(lower);
} else {
begval = Integer.parseInt(lower.substring(0, dash));
endval = Integer.parseInt(lower.substring(dash + 1));
}
} catch (NumberFormatException ignored) {
}
if (begval < 0) {
begval = 0;
} else if (begval > 255) {
begval = 255;
}
if (endval < 0) {
endval = 0;
} else if (endval > 255) {
endval = 255;
}
vals[0] = begval;
vals[1] = endval;
return method;
}
/**
* Calculates and returns the image. Halts the calculation and returns
* null if the Applet is stopped during the calculation.
*/
private Image calculateImage() {
Thread me = Thread.currentThread();
int width = canvas.getSize().width;
int height = canvas.getSize().height;
int xvals[] = new int[2];
int yvals[] = new int[2];
int xmethod = XControls.getParams(xvals);
int ymethod = YControls.getParams(yvals);
int pixels[] = new int[width * height];
int c[] = new int[4]; //temporarily holds R,G,B,A information
int index = 0;
for (int j = 0; j < height; j++) {
for (int i = 0; i < width; i++) {
c[0] = c[1] = c[2] = 0;
c[3] = 255;
if (xmethod < ymethod) {
applyMethod(c, xmethod, i, width, xvals);
applyMethod(c, ymethod, j, height, yvals);
} else {
applyMethod(c, ymethod, j, height, yvals);
applyMethod(c, xmethod, i, width, xvals);
}
pixels[index++] = ((c[3] << 24) | (c[0] << 16) | (c[1] << 8)
| c[2]);
}
// Poll once per row to see if we've been told to stop.
if (runner != me) {
return null;
}
}
return createImage(new MemoryImageSource(width, height,
ColorModel.getRGBdefault(), pixels, 0, width));
}
private void applyMethod(int c[], int methodIndex, int step,
int total, int vals[]) {
DitherMethod method = DitherMethod.values()[methodIndex];
if (method == DitherMethod.NOOP) {
return;
}
int val = ((total < 2)
? vals[0]
: vals[0] + ((vals[1] - vals[0]) * step / (total - 1)));
switch (method) {
case RED:
c[0] = val;
break;
case GREEN:
c[1] = val;
break;
case BLUE:
c[2] = val;
break;
case ALPHA:
c[3] = val;
break;
case SATURATION:
int max = Math.max(Math.max(c[0], c[1]), c[2]);
int min = max * (255 - val) / 255;
if (c[0] == 0) {
c[0] = min;
}
if (c[1] == 0) {
c[1] = min;
}
if (c[2] == 0) {
c[2] = min;
}
break;
}
}
@Override
public void start() {
runner = new Thread(this);
runner.start();
}
@Override
public void run() {
canvas.setImage(null); // Wipe previous image
Image img = calculateImage();
if (img != null && runner == Thread.currentThread()) {
canvas.setImage(img);
}
}
@Override
public void stop() {
runner = null;
}
@Override
public void destroy() {
remove(XControls);
remove(YControls);
remove(canvas);
}
@Override
public String getAppletInfo() {
return "An interactive demonstration of dithering.";
}
@Override
public String[][] getParameterInfo() {
String[][] info = {
{ "xaxis", "{RED, GREEN, BLUE, ALPHA, SATURATION}",
"The color of the Y axis. Default is RED." },
{ "yaxis", "{RED, GREEN, BLUE, ALPHA, SATURATION}",
"The color of the X axis. Default is BLUE." }
};
return info;
}
}
[MENTION=139512]Sup[/MENTION]pressWarnings("serial")
class DitherCanvas extends Canvas {
private Image img;
private static String calcString = "Calculating...";
@Override
public void paint(Graphics g) {
int w = getSize().width;
int h = getSize().height;
if (img == null) {
super.paint(g);
g.setColor(Color.black);
FontMetrics fm = g.getFontMetrics();
int x = (w - fm.stringWidth(calcString)) / 2;
int y = h / 2;
g.drawString(calcString, x, y);
} else {
g.drawImage(img, 0, 0, w, h, this);
}
}
@Override
public void update(Graphics g) {
paint(g);
}
@Override
public Dimension getMinimumSize() {
return new Dimension(20, 20);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
public Image getImage() {
return img;
}
public void setImage(Image img) {
this.img = img;
repaint();
}
}
[MENTION=139512]Sup[/MENTION]pressWarnings("serial")
class DitherControls extends Panel implements ActionListener {
private CardinalTextField start;
private CardinalTextField end;
private Button button;
private Choice choice;
private DitherTest applet;
private static LayoutManager dcLayout = new FlowLayout(FlowLayout.CENTER,
10, 5);
public DitherControls(DitherTest app, int s, int e, DitherMethod type,
boolean vertical) {
applet = app;
setLayout(dcLayout);
add(new Label(vertical ? "Vertical" : "Horizontal"));
add(choice = new Choice());
for (DitherMethod m : DitherMethod.values()) {
choice.addItem(m.toString().substring(0, 1)
+ m.toString().substring(1).toLowerCase());
}
choice.select(type.ordinal());
add(start = new CardinalTextField(Integer.toString(s), 4));
add(end = new CardinalTextField(Integer.toString(e), 4));
}
/* puts on the button */
public void addRenderButton() {
add(button = new Button("New Image"));
button.addActionListener(this);
}
/* retrieves data from the user input fields */
public int getParams(int vals[]) {
try {
vals[0] = scale(Integer.parseInt(start.getText()));
} catch (NumberFormatException nfe) {
vals[0] = 0;
}
try {
vals[1] = scale(Integer.parseInt(end.getText()));
} catch (NumberFormatException nfe) {
vals[1] = 255;
}
return choice.getSelectedIndex();
}
/* fits the number between 0 and 255 inclusive */
private int scale(int number) {
if (number < 0) {
number = 0;
} else if (number > 255) {
number = 255;
}
return number;
}
/* called when user clicks the button */
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
applet.start();
}
}
}
[MENTION=139512]Sup[/MENTION]pressWarnings("serial")
class CardinalTextField extends TextField {
String oldText = null;
public CardinalTextField(String text, int columns) {
super(text, columns);
enableEvents(AWTEvent.KEY_EVENT_MASK | AWTEvent.TEXT_EVENT_MASK);
oldText = getText();
}
// Consume non-digit KeyTyped events
// Note that processTextEvent kind of eliminates the need for this
// function, but this is neater, since ideally, it would prevent
// the text from appearing at all. Sigh. See bugid 4100317/4114565.
//
@Override
protected void processEvent(AWTEvent evt) {
int id = evt.getID();
if (id != KeyEvent.KEY_TYPED) {
super.processEvent(evt);
return;
}
KeyEvent kevt = (KeyEvent) evt;
char c = kevt.getKeyChar();
// Digits, backspace, and delete are okay
// Note that the minus sign is not allowed (neither is decimal)
if (Character.isDigit(c) || (c == '\b') || (c == '\u007f')) {
super.processEvent(evt);
return;
}
Toolkit.getDefaultToolkit().beep();
kevt.consume();
}
// Should consume TextEvents for non-integer Strings
// Store away the text in the tf for every TextEvent
// so we can revert to it on a TextEvent (paste, or
// legal key in the wrong location) with bad text
//
// Note: it would be easy to extend this to an eight-bit
// TextField (range 0-255), but I'll leave it as-is.
//
@Override
protected void processTextEvent(TextEvent te) {
// The empty string is okay, too
String newText = getText();
if (newText.equals("") || textIsCardinal(newText)) {
oldText = newText;
super.processTextEvent(te);
return;
}
Toolkit.getDefaultToolkit().beep();
setText(oldText);
}
// Returns true for Cardinal (non-negative) numbers
// Note that the empty string is not allowed
private boolean textIsCardinal(String textToCheck) {
try {
return Integer.parseInt(textToCheck, 10) >= 0;
} catch (NumberFormatException nfe) {
return false;
}
}
}
18) What is the paint method for when is it invoked, and by whom?
Ans. The paint method is usually invoked by Abstract Window Toolkit(AWT), via the update method, in order to provide
an up-to-date image on screen of the component.The paint method is the fundamental means by which an AWT component draws itself on the screen. Typically , paint is
invoked for you by update, but it can also be invoked directly, bypassing update, such as when a Component is scrolled
or resized or when the part of the window is exposed after being covered by another window.You must put the minimum necessary
to paint your Component completely and quickly.
19) What is a thread?
Ans. A thread is a sequence of executing instructions that run independently of other thread yet can directly share data with other
threads.Threads let you organize your program into logically separate paths of execution. Mutiple threads are like independent agents at your
disposal. You give eache one a list of instructions and then send it off on its way. From the individual thread's perspective,
life is simple:it works on its own list of instructions until it either finishes the list or is told to stop.In this respect, a
thread resembles a process or a separately running program.
20) What is a monitor?
Ans. A monitor is a one-thread at a time set of code blocks and methods that also provides a wait-notify service.
When multiple threads access common changeable data , you must regulate the timing of those threads to ensure that one thread doesn't interfere
with another thread's assumptions of data integrity. The Java platform lets you restrict thread interactions by means of monitors.
A monitor groups a set of code blocks into a single protected space, such that only one thread at a time can be in the monitor,
that is , executing any code under the monitor's protection.
A monitor uses a mutual exclusion lock to protect its region of code.A thread must acquire the lock in order to enter the monitor, and
it relinquishes the lock when it exits the monitor.
21) If Java is platform-independant, why doesn't it run on all the platforms?
Ans. The Java language , standard class libraries , and compiled class files are platform-independent, but the Java Virtual Machine (JVM)
underneath them must be ported to specific native platforms (native code usually in C/C++) one by one.
Since most of the Java libraries are written in Java language, the work is already half done.The Java API also defines cross-platform
capabilities and behaviours which gets mapped onto specific native platforms(native code usually in C language).Your Java program
should essentially behave the same way across all the platforms(Windows, Solaris, Mac OS, Linux etc.,)
22) How do I obtain the performance profile of my Java program?
Ans. You can use the Java interpreter's -prof option. This creates a java,prof file with the information about which methods call
data - how much time is spent executing a given method.
java -prof classname
23)Why does my Java program throws java.lang.OutOfMemoryError even though there is enough memory for the program to run.
How do I solve this?
Ans. Your Java program is throwing java.lang.OutOfMemoryError since the program doesn't get the memory required for it to run properly.
You can allocate more memory (heap area) for your Java program as follows :
java -Xms128m -Xmx256m classname
Here we allocate a initial memory of 128 MB (-Xms128m) and a maximum of 256 MB (-Xmx256m). Where classname is the name of the class (your program)
Q) What project have you done in Java?
Ans. Show the Project book containing the screenshots , synopsis, diagrams etc.,
Explain the project in detail.
Here is the list of projects that you can do in Java :
Q) What are the projects I can do in Java?
Ans. You can write a GUI (Swing) application, applet or a e-commerce application (Servlet/JSP) or a JavaME (Java Micro Edition).
Here are some projects that you can do.
Swing (GUI)
1) Banking System
2) Customer Relationship Software (CRM)
3) Text Editor (TextPad)
4) Integrated Development Environment (IDE like NetBeans, Eclipse, JDeveloper) (NOTE : IDE Development is only for Java experts !!, not for novice programmers!!!)
5) Media Player (WinAmp, iTunes)
6) Web Browser (FireFox, Chrome, Opera)
7) Image Processing (PhotoShop, GIMP)
8) Peer to Peer (P2P like LimeWire)
9) DataBase Explorer
10) Download Manager (FlashGet, DAP)
11) RDBMS (Oracle, DB2, SQL Server)
12) Supply Chain Management (SCM)
13) Text to Speech Converter
14) Accounting (Tally, Busy)
15) 3D Modelling program (using Java3D - like Blender, ZBrush, Sculptris)
16) Geographical Information System (GIS)
17) Enterpise Resource Planning (ERP like SAP, Oracle Financials)
18) Compiler design in Java ( Compiler design is for Java experts , it needs professional expertise!!! It's not for novice programmers!!!)
19) Stock Market monitoring Applet or application
20) XML Editor
21) Zip archiver like WinZip, WinRAR
22) UML Editor (Unified Modeling Language)
23) FTP Client
24) Web Server
25) Voice Chat & Video Conferencing (using JMF)
26) Word processor (like MS Word )
E-Commerce (JSP/Servlets)
1) Banking System
2) HRM (Human Resource Management)
3) Airline Reservation System
4) Job Portal System (naukri.com, monster.com)
5) Inventory Management System
6) Hotel Management System
7) Energy Billing System
8) Travel Billing System
9) Online ecommerce Portal (eBay, amazon.com)
10) Telecom management System
11) Voice chat & Video conferencing (using JMF)
Mobile Development (JavaME)
1) M-commerce
2) Game Development
3) Media Player
4) Web Crawler
5) Download Manager
6) Web Browser
Q) What are the books I need to study, to write a Project in Java ?
Ans.
Must read Books for writing Java Projects:
1) Core Java - Vol -I & II by Horstmann C S
2) Beginning Java Objects (Wrox)/ Object-Oriented Programming in Java by Balagurusamy
3) Java Tutorial 5th Edition
4) Graphic Java 2 ,Volume 2 Swing: Mastering the JFC by David M Geary
5) Data Structures & Algorithms in Java by Robert Lafore (Techmedia) / Algorithms in Java 4th Edition by Robert SedgeWick
6) The Java Developers Almanac 1.4, Volume I & II by Patrick Chan
7) Java Swing 5th Edition by Eckstein (Oreilly)
8) Thinking in Java
9) Object-Oriented Design in Java by Stephen Gilbert and Bill McCarty
10) Oracle Database JDBC Developer's Guide & Reference
11) Beginning Java Databases / Java Database Programming Bible by John O' Donahue
12) Professional Java Programming (Wrox)
13) Beginning Java Networking (Wrox)/ An Itroduction to Network Programming with Java : Java 7 Compatible by Jan Graba
14) JSP 2.0 : The Complete Reference by Phil Hanna (Tata McGraw Hill)
15) Struts : The Complete Reference (Tata McGraw Hill)
16) Mastering HTML 5 (Sybex/ BPB)
17) Professional Java Networking (Wrox)
18) Oracle 12c: The Complete Reference (Tata McGraw Hill)
19) Java Threads (Oreilly)
20) Java How To Program by H M Deitel & P J Deitel
21) Software Engineering in Java
23) Desktop Java Live (Discusses various Layout Managers , GUI Builders, Swing Threading, Data Binding , Validation, Packaging & Deployment )
24) Java Servlet Programming by Jason Hunter, William Crawford (Oreilly)
Study the best Java books, work hard write more Java code and succeed in life!!
Goodluck!!