Tuesday, April 17, 2007

What is conversational state ?

The field values of a session bean plus the transitive closure of the objects reachable from the bean's fields. The transitive closure of a bean is defined in terms of the serialization protocol for the Java programming language, that is, the fields that would be stored by serializing the bean instance.


SOURCE : www.referjava.com

What is continue ?

A Java keyword used to resume program execution at the end of the current loop. If followed by a label, continue resumes execution where the label occurs.


SOURCE : www.referjava.com

What is const ?

A reserved Java keyword not used by current versions of the Java programming language.

SOURCE : www.referjava.com

What is Collections?

Common collection activities include adding objects, removing objects, verifying object inclusion, retrieving objects and iterating.


SOURCE : www.referjava.com

What is compositing ?

The process of superimposing one image on another to create a single image.


SOURCE : www.referjava.com

What is commit ?

The point in a transaction when all updates to any resources involved in the transaction are made permanent.


SOURCE : www.referjava.com

What is comment ?

In a program, explanatory text that is ignored by the compiler. In programs written in the Java programming language, comments are delimited using // or /*...*/.


SOURCE : www.referjava.com

What is codebase ?

Works together with the code attribute in the tag to give a complete specification of where to find the main applet class file: code specifies the name of the file, and codebase specifies the URL of the directory containing the file.


SOURCE : www.referjava.com

What is a compiler ?

A program to translate source code into code to be executed by a computer. The Java compiler translates source code written in the Java programming language into bytecode for the Java virtual machine.

In the client/server model of communications, the client is a process that remotely accesses resources of a compute server, such as compute power and large memory capacity.


SOURCE : www.referjava.com

What is compilation unit ?

The smallest unit of source code that can be compiled. In the current implementation of the Java platform, the compilation unit is a file.


SOURCE : www.referjava.com

What is class variable ?

A data item associated with a particular class as a whole--not with particular instances of the class. Class variables are defined in class definitions.


SOURCE : www.referjava.com

What is class ?

In the Java programming language, a type that defines the implementation of a particular kind of object. A class definition defines instance and class variables and methods, as well as specifying the interfaces the class implements and the immediate superclass of the class. If the superclass is not explicitly specified, the superclass will implicitly be Object.


SOURCE : www.referjava.com

What is catch ?

A Java keyword used to declare a block of statements to be executed in the event that a Java exception, or run time error, occurs in a preceding try block.


SOURCE : www.referjava.com

What is char ?

A Java keyword used to declare a variable of type character.

SOURCE : www.referjava.com

What is casting ?

Explicit conversion from one data type to another.

SOURCE : www.referjava.com

What is case ?

A Java keyword that defines a group of statements to begin executing if a value specified matches the value defined by a preceding switch keyword.


SOURCE : www.referjava.com

What is BufferedWriter ?

This class is used to make low-level Writer classes like FileWriter more efficient and easier to use. BufferedWriters write relatively large chunks of data to a file at once.

SOURCE : www.referjava.com

What is BufferedReader ?

This class is used to make low-level Reader classes like FileReader more efficient and easier to use.BufferedReaders read relatively large chunks of data from a file at once and keep this data in a buffer.


SOURCE : www.referjava.com

What is Boxing?

Allows you to convert primitives to wrappers or to convert wrappers to primitives.


SOURCE : www.referjava.com

What is bytecode ?

Machine-independent code generated by the Java compiler and executed by the Java interpreter.


SOURCE : www.referjava.com

What is byte?

A sequence of eight bits. Java provides a corresponding byte type.


SOURCE : www.referjava.com

What is break ?

A Java keyword used to resume program execution at the statement immediately following the current statement. If followed by a label, the program resumes execution at the labeled statement.


SOURCE : www.referjava.com

What is boolean ?

Refers to an expression or variable that can have only a true or false value. The Java programming language provides the boolean type and the literal values true and false.


SOURCE : www.referjava.com

What is a block ?

In the Java programming language, any code between matching braces. Example: { x = 1; }.


SOURCE : www.referjava.com

What is bitwise operator ?

An operator that manipulates the bits of one or more of its operands individually and in parallel. Examples include the binary logical operators (&, |, ^), the binary shift operators (<<, >>, >>>) and the unary one's complement operator (~).


SOURCE : www.referjava.com

What is bit ?

The smallest unit of information in a computer, with a value of either 0 or 1.


SOURCE : www.referjava.com

What is binary operator ?

An operator that has two arguments.


SOURCE : www.referjava.com

Friday, March 16, 2007

What is bean ?

A reusable software component that conforms to certain design and naming conventions. The conventions enable beans to be easily combined to create an application using tools that understand the conventions.


SOURCE : www.referjava.com

What is ArrayList?

A growable array. It gives you fast iteration and fast random access. It is an ordered collection but not sorted.


SOURCE : www.referjava.com

What is Assertion ?

Assertions give you a way to test your assumptions during development and debugging. They are enabled during testing but disabled during deployment. The keywords assert is used as of version1.4


SOURCE : www.referjava.com

What is array?

Arrays are objects in Java that store multiple variables of the same type. They can hold primitive types or object references. Arrays are objects on the heap.
or
A collection of data items, all of the same type, in which each item's position is uniquely designated by an integer.


SOURCE : www.referjava.com

What is argument?

A data item specified in a method call. An argument can be a literal value, a variable, or an expression.


SOURCE : www.referjava.com

What is Applet?

A component that typically executes in a Web browser, but can execute in a variety of other applications or devices that support the applet programming model.


SOURCE : www.referjava.com

What is Application Programming Interface (API)

Application Programming Interface. The specification of how a programmer writing an application accesses the behavior and state of classes and objects.


SOURCE : www.referjava.com

Saturday, March 10, 2007

What are the services provided by the container?

i. Manages execution and life cycle of EJBs.
ii. May provide transaction services.
iii.Shields clients from lower level network management.
iv. May provide persistent storage.


SOURCE : www.referjava.com

What is scalable, portability in J2EE?

i. Scalable in the sense could handle number of clients at the same time.



ii. Portable - platform independent, app server independent, data store independent.


SOURCE : www.referjava.com

When to use container managed and bean managed persistence?

Container managed persistance is used when the persistant datastore is a

relational database and there is one to one mapping between a data represented in a table in the relational database and the ejb object. Bean managed persistance in used when there is no one to one mapping of the table and a complex query reteriving data from several tables needs to be performed to construct an ejb object. Bean managed is also used when the

persistence datastorage is not a relational database.



SOURCE : www.referjava.com

How is entity bean created using Container managed entity bean ?

In both container managed and bean managed when the client calls create the call is passed on to ejbCreate.



In a container managed bean ejbCreate method will initialize all instance variables based ont he input arguments passed in. Once ejbCreate method completesthe container will automatically persist the bean. ejbCreate would return null.This is because: it is not practially possible to generate a primary key in ejbCreate and it would be impossible to get hold of the primary key for a row in a table even before the row exists as storage happens only after

ejbCreatecall completes.



In a bean managed persistance the ejbCreate will perform the fallowing:

i. Create an entry in the database

ii. Initialize the instance variables

iii. Return the primary key.



SOURCE : www.referjava.com

What are the methods of Entity Bean?

setEntityState

create

ejbCreate

ejbPostCreate

ejbActivate

ejbPassivate

remove

ejbRemove

unsetEntityState


SOURCE : www.referjava.com

Why does EJB needs two interface (Home and Remote Interface) ?

To handle the network tranport layer. TODO I do not have much knowledge to explain further.


SOURCE : www.referjava.com

When to use session, entity and message driven beans?

Session beans are used to represent a business procedure and no persistance

Is required. Session bean represents a client in the server. Entity beans represent a business logic compared procedure. Entity beans are typically shared between several session beans and persist beyond the scope of the application.



Message driven beans are new in j2ee 2.0 and are asynchronous beans typically

used to inteact with legacy batch processing systems.


SOURCE : www.referjava.com

Monday, March 5, 2007

What is component mapping in hibernate?

Lazy setting decides whether to load child objects while loading the Parent Object.You need to do this setting respective hibernate mapping file of the parent class.Lazy = true (means not to load child)By default the lazy loading of the child objects is true. This make sure that the child objects are not loaded unless they are explicitly invoked in the application by calling getChild() method on parent.In this case hibernate issues a fresh database call to load the child when getChild() is actully called on the Parent object.But in some cases you do need to load the child objects when parent is loaded. Just make the lazy=false and hibernate will load the child when parent is loaded from the database.Exampleslazy=true (default)Address child of User class can be made lazy if it is not required frequently.lazy=falseBut you may need to load the Author object for Book parent whenever you deal with the book for online bookshop.

SOURCE : www.referjava.com

Why do you need ORM tools like hibernate?

To overcome the "paradigm mismatch" between object oriented data and table oriented relational databases.

SOURCE : www.referjava.com

What is the difference between sorted and orderd collection in hibernate?

A sorted collection is sorted in-memory using java comparator, while order collection is ordered at the database level using order by clause.

SOURCE : www.referjava.com

What is the main advantage of using the hibernate than using the sql?

Main advantage is that it avoids writing queries. Ofcourse, u have to write to some extent but a lot is relaxed.Most of the work is taken care by mapping.Also criteria class is very useful for complex joins.

Using ORM we can avoid the jdbc API completely and also provides ease to the developer in developing the classes.


SOURCE : www.referjava.com

How to create primary key using hibernate?

id field in hbm.xml file is used to specify the primary key in database. We also use generator to specify the way primary key is generated to the database. For example

< id name="testId" type="string" >
< column name="testColumn" length="40" / >
< generator class="increment" / >
< /id >

here the primary key field name in database is testColumn and it will autonmatically incremented by one as the generator is specified as increment.


SOURCE : www.referjava.com

What is the advantage of Hibernate over jdbc?

Hibernate is used to persist the objects in the database, but we have to use the jdbc to connect to database. JDBC is used to store the primitivies in the database.
Hibernate is basically a ORM tool which allows you to perform database activies without bothering about the Database change.

You dont need to change the SQL scripts if you change database.

Apart from that you dont need to write most of the SQL scripts for persisting ,deleting object and parsing the resultsets.With respect to perfomance, hibernate provide the capability to reduce the number of database trips by creating the betch processing and session cache and second level cache.

It also supports the transactions.
More then this all, it is very easy to make a cleaner seperation of Data Access Layer from usiness logic layer.
With all the capabilities mention above it is fast and easy to learn hibernate, develop application and maintain easily.


SOURCE : www.referjava.com

What is the difference between Hibernate and EJB 2.1?

Hibernate is a ORM(object relation mapping ) tool which can be used for creating a mapping between plain java bean objects (POJO) and a persitent storage (rdbms).The EJB 3.0 specification is divided into two parts The first which deals with session and MDBs and the second which deals with persistence and entity beans. The latter part is called JPA(java persistance API ). Hibernate 3.0 implements the JPA specification.EJB 2.1 is a specification for defining loosely coupled reusable business componenets.

EJB 2.1 and hibernate serve two different purposes. Hibernate can be co related with the entity beans in EJB 2.1.HIbernate offers far more extensive features then plain entity beans.still there are no containers (applicaiton servers) available which fully implement the EJB 3.0 specification. depending upon the buisness needs hibernate framework can be used in conjuction with EJB2.1 to achieve the JPA abstraction.

SOURCE : www.referjava.com

What is the difference between beans and hibernate?

Beans are at form level and hibernate at data base level.

Hibernate adapts beans.Its plain old Java objects. POJO. Hibernate always has a bean orientation.But the Bean is just not persistent, using hibernate you can make a bean persistent.A bean when used in Hibernate It can create a table ,Add a row,Delete a rowUpdate row.THis is all done with Hib Configuration stuff.Hibernate is ORM as it can relate a bean to a row in a table


SOURCE : www.referjava.com

Thursday, March 1, 2007

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, you'll 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.


SOURCE : www.referjava.com

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.


SOURCE : www.referjava.com

Describe what happens when an object is created in Java?

Several things happen in a particular order to ensure the object is constructed properly:

1. 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.

2. The instance variables of the objects are initialized to their default values.

3. 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.

4. 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.


SOURCE : www.referjava.com

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.


SOURCE : www.referjava.com

How to Retrieve Warnings?

SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do; they simply alert the user that something did not happen as planned. A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object

E.g.

SQLWarning warning = stmt.getWarnings();

if (warning != null) {

while (warning != null) {

System.out.println("Message: " + warning.getMessage());

System.out.println("SQLState: " + warning.getSQLState());

System.out.print("Vendor error code: ");

System.out.println(warning.getErrorCode());

warning = warning.getNextWarning();

}

}



SOURCE : www.referjava.com

What Class.forName will do while loading drivers?

It is used to create an instance of a driver and register it with the DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS.


SOURCE : www.referjava.com

What information is needed to create a TCP Socket?

The Local System's IP Address and Port Number. And the Remote System's IPAddress and Port Number.


SOURCE : www.referjava.com

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.


SOURCE : www.referjava.com

Tuesday, February 27, 2007

Can a for statement loop indefinitely?

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


SOURCE : www.referjava.com

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


SOURCE : www.referjava.com

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.

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.


SOURCE : www.referjava.com

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.


SOURCE : www.referjava.com

What is user defined exception ?

Apart from the exceptions already defined in Java package libraries, user can define his own exception classes by extending Exception class.


SOURCE : www.referjava.com

You can create a String object as String str = "abc"; Why cant a button object be created as Button bt = "abc";? Explain

The main reason you cannot create a button by Button bt1= "abc"; is because "abc" is a literal string (something slightly different than a String object, by-the-way) and bt1 is a Button object. The only object in Java that can be assigned a literal String is java.lang.String. Important to note that you are NOT calling a java.lang.String constuctor when you type String s = "abc";


SOURCE : www.referjava.com

What is passed by ref and what by value ?

All Java method arguments are passed by value. However, Java does manipulate objects by reference, and all object variables themselves are references


SOURCE : www.referjava.com

What is constructor chaining and how is it achieved in Java ?

A child object constructor always first needs to construct its parent (which in turn calls its parent constructor.). In Java it is done via an implicit call to the no-args constructor as the first statement.


SOURCE : www.referjava.com

Monday, February 26, 2007

What is a "stateless" protocol ?

Without getting into lengthy debates, it is generally accepted that protocols like HTTP are stateless i.e. there is no retention of state between a transaction which is a single request response combination


SOURCE : www.referjava.com

Difference between a Class and an Object ?

A class is a definition or prototype whereas an object is an instance or living representation of the prototype


SOURCE : www.referjava.com

What gives java it's "write once and run anywhere" nature?

Java is compiled to be a byte code which is the intermediate language between source code and machine code. This byte code is not platorm specific and hence can be fed to any platform. After being fed to the JVM, which is specific to a particular operating system, the code platform specific machine code is generated thus making java platform independent.


SOURCE : www.referjava.com

I made my class Cloneable but I still get 'Can't access protected method clone. Why?

Yeah, some of the Java books, in particular "The Java Programming Language", imply that all you have to do in order to have your class support clone() is implement the Cloneable interface. Not so. Perhaps that was the intent at some point, but that's not the way it works currently. As it stands, you have to implement your own public clone() method, even if it doesn't do anything special and just calls super.clone().


SOURCE : www.referjava.com

What is the purpose of the System class?

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


SOURCE : www.referjava.com

How is rounding performed under integer division?

The fractional part of the result is truncated. This is known as rounding toward zero.


SOURCE : www.referjava.com

Is the ternary operator written x : y ? z or x ? y : z ?

It is written x ? y : z.


SOURCE : www.referjava.com

Can an object be garbage collected while it is still reachable?

A reachable object cannot be garbage collected. Only unreachable objects may be garbage collected


SOURCE : www.referjava.com

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.


SOURCE : www.referjava.com

What is the % operator?

It is referred to as the modulo or remainder operator. It returns the remainder of dividing the first operand by the second operand.


SOURCE : www.referjava.com

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.


SOURCE : www.referjava.com

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.


SOURCE : www.referjava.com

Sunday, February 25, 2007

Can a Byte object be cast to a double value?

No, an object cannot be cast to a primitive value.


SOURCE : www.referjava.com

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

The read() method returns -1 when it has reached the end of a file.


SOURCE : www.referjava.com

How are commas used in the intialization and iteration parts of a for statement?

Commas are used to separate multiple statements within the initialization and iteration parts of a for statement.

SOURCE : www.referjava.com

What is the advantage of the event-delegation model over the earlier event-inheritance model?

The event-delegation model has two advantages over the event-inheritance model. First, it enables event handling to be handled by objects other than the ones that generate the events (or their containers). This allows a clean separation between a component's design and its use. The other advantage of the event-delegation model is that it performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to repeatedly process unhandled events, as is the case of the event-inheritance model.


SOURCE : www.referjava.com

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.


SOURCE : www.referjava.com

What is the difference between a break statement and a continue statement?

A break statement results in the termination of the statement to which it applies (switch, for, do, or while). A continue statement is used to end the current loop iteration and return control to the loop statement.


SOURCE : www.referjava.com

Can a double value be cast to a byte?

Yes, a double value can be cast to a byte.


SOURCE : www.referjava.com

Which Java operator is right associative?

The = operator is right associative.

SOURCE : www.referjava.com

What is the argument type of a program's main() method?

A program's main() method takes an argument of the String[] type.


SOURCE : www.referjava.com

How many times may an object's finalize() method be invoked by the garbage collector?

An object's finalize() method may only be invoked once by the garbage collector.


SOURCE : www.referjava.com

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.

SOURCE : www.referjava.com

What is the range of the char type?

The range of the char type is 0 to 2^16 - 1.


SOURCE : www.referjava.com

Thursday, February 22, 2007

What is the catch or declare rule for method declarations?

If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause


SOURCE:www.referjava.com

What are order of precedence and associativity, and how are they used?

Order of precedence determines the order in which operators are evaluated in expressions. Associatity determines whether an expression is evaluated left-to-right or right-to-left


SOURCE:www.referjava.com

What restrictions are placed on the location of a package statement within a source code file?

A package statement must appear as the first line in a source code file (excluding blank lines and comments).


www.referjava.com

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.


www.referjava.com

What are wrapped classes?

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


SOURCE:www.referjava.com

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.


SOURCE:www.referjava.com

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.


SOURCE:www.referjava.com

Why do threads block on I/O?

Threads block on i/o (that is enters the waiting state) so that other threads may execute while the i/o Operation is performed.


www.referjava.com

How do I convert a numeric IP address like 192.18.97.39 into a hostname like java.sun.com? (Networking)

String hostname = InetAddress.getByName("192.18.97.39").getHostName();


SOURCE:www.referjava.com

What does it mean that a method or field is "static"?

Static variables and methods are instantiated only once per class. In other words they are class variables, not instance variables. If you change the value of a static variable in a particular object, the value of that variable changes for all instances of that class.

Static methods can be referenced with the name of the class rather than the name of a particular object of the class (though that works too). That's how library methods like System.out.println() work. out is a static field in the java.lang.System class.


SOURCE:www.referjava.com

Why isn't there operator overloading?

Because C++ has proven by example that operator overloading makes code almost impossible to maintain. In fact there very nearly wasn't even method overloading in Java, but it was thought that this was too useful for some very basic methods like print(). Note that some of the classes like DataOutputStream have unoverloaded methods like writeInt() and writeByte().


SOURCE:www.referjava.com

What are some alternatives to inheritance?

Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn't force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass).


SOURCE:www.referjava.com

Can an Interface have an inner class?

Yes public interface abc { static int i=0; void dd(); class a1 { a1() { int j; System.out.println("in interfia"); }; public static void main(String a1[]) { System.out.println("in interfia"); } } }


SOURCE:www.referjava.com

Can an Interface be final?

No


SOURCE:www.referjava.com

Why is not recommended to have instance variables in Interface?

By Default, All data members and methods in an Interface are public. Having public variables in a class that will be implementing it will be violation of the Encapsulation principal


SOURCE: www.referjava.com

Wednesday, February 21, 2007

Difference between JRE And JVM AND JDK ?

The "JDK" is the Java Development Kit. I.e., the JDK is bundle of software that you can use to develop Java based software. The "JRE" is the Java Runtime Environment. I.e., the JRE is an implementation of the Java Virtual Machine which actually executes Java programs. Typically, each JDK contains one (or more) JRE's along with the various development tools like the Java source compilers, bundling and deployment tools, debuggers, development libraries, etc.


SOURCE: www.referjava.com

What is the diffrence between inner class and nested class?

When a class is defined within a scope od another class, then it becomes inner class.

If the access modifier of the inner class is static, then it becomes nested class.


SOURCE: www.referjava.com

What is the difference between an if statement and a switch statement?

The if statement is used to select among two alternatives. It uses a boolean expression to decide which alternative should be executed. The switch statement is used to select among multiple alternatives. It uses an int expression to determine which alternative should be executed.


SOURCE: www.referjava.com

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.


SOURCE: www.referjava.com

How does a try statement determine which catch clause should be used to handle an exception?

When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exception is executed. The remaining catch clauses are ignored.


SOURCE: www.referjava.com

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.



SOURCE: www.referjava.com

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.


SOURCE: www.referjava.com

What is the difference between the prefix and postfix forms of the ++ operator?

The prefix form performs the increment operation and returns the value of the increment operation. The postfix form returns the current value all of the expression and then performs the increment operation on that value.


SOURCE: www.referjava.com

What is numeric promotion?

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 numerical promotion, 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



SOURCE: www.referjava.com

Can an abstract class be final?

An abstract class may not be declared as final


SOURCE: www.referjava.com

Which arithmetic operations can result in the throwing of an ArithmeticException?

Integer / and % can result in the throwing of an ArithmeticException


www.referjava.com

What happens if an exception is not caught?

An uncaught exception results in the uncaughtException() method of the thread's ThreadGroup being invoked, which eventually results in the termination of the program in which it is thrown.


www.referjava.com

How can a dead thread be restarted?

A dead thread cannot be restarted.


www.referjava.com

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.


www.referjava.com

What is a compilation unit?

A compilation unit is a Java source code file.


www.referjava.com

Sunday, February 18, 2007

How can I use a variable that contains HTML?

If you have a variable like this:

example="This is a text ";

Use this in the output jsp:

bean:write property="example" filter="false"

www.referjava.com

Saturday, February 17, 2007

When converting older Java software written for JDK1.0 to run on a newer JVM, are there any issues I should be aware of?

While there have been significant improvements to the Java platform over the years in the terms of graphics, networking, performance, and other API enhancements, older software can't take advantage of these so many developers find themselves faced with the task of upgrading software. Or, as often happens, a machine running an earlier JVM for some critical application is upgraded, and a newer release is installed. How can you guarantee that there won't be any problems with your older software? Or is it safe to assume that all versions of Java are guaranteed to be backwards compatible?

It's never safe to make any assumption when it comes to JVMs. There are just too many vendors, and too many versions to keep track of. Beyond vendor incompatibilities though, there are some issues to be careful of when moving from JDK1.02 to JDK1.1, and from JDK1.1 to Java 2.

Firstly, and this is the most important, be mindful of deprecated methods. A method that has been marked as deprecated means that Sun no longer recommends using it and that an alternate mechanism should be used if at all possible. Please see an earlier FAQ on this topic located here. Remember also that if you want your new programs to run on older JDK1.0 machines, you must continue to use the deprecated methods and not newer ones that JDK1.0 is not aware of.

Secondly, there are many minor changes to the JDK tools, and JVMs, that will cause problems with older software. Generally this happens because of minor flaws in the original source code of the application, and as the JVM has improved it has become more strict. As a general rule, you shouldn't have much of a problem, but in the documentation that ships for JDK1.2 there are quite a few areas identified where problems can arise with older code
Sun documentation on compatibility problems
For JDK1.1, please see http://java.sun.com/products/jdk/1.1/compatible/index.html

For JDK 1.2, which identifies numerous problems which Java 2 has with older code, please see
http://java.sun.com/products/jdk/1.2/compatibility.html



www.referjava.com

How do I run the garbage collector to free memory and delete unused objects?

First, you should be aware that the garbage collector works automatically, whether you request it to or not. Secondly, you cannot force the garbage collector to run.

That said, you can request the garbage collector to perform work, by invoking the System.gc() method. Once working, you may experience a short pause while the garbage collector does its work. That means you should do it at an appropriate time, such as before a big task or when the GUI is idle and waiting for input.


www.referjava.com

What is a Sun Certified Java Architect? How can I become one?

Developers who have achieved a Sun Certified Java Programmer, or Sun Certified Java Developer title may want to consider becoming a certified architect. Software architecture encompasses a broad range of technologies and techniques such as :-

object oriented analysis and design (OOAD)
Unified Modeling Language (UML)
Enterprise JavaBeans (EJBs)
large scale system design
Java 2 Enterprise Edition technologies such as CORBA/RMI
internationalization and security

www.referjava.com

What does a void return value mean? Which class is being returned?

You've probably heard of this method :-

public static void main(String args[])
before. It's invoked by the JVM when starting a Java application. Have you ever wondered why it didn't have a return statement at the end of the method? After all, don't all methods return a value?

It's possible, and actually quite common, to not return a value. If you're not going to return a value, however, you must mark your method as void. This tells the compiler there's no need to enforce a return value.


www.referjava.com

How I can I return a null value from an object constructor?

The simple answer is : no, you can't.

The explanation why is simple. You don't return any value whatsoever from an object constructor. The object has already been created - in the constructor you're just initializing the object's state. So there isn't any way to return a null value.

However, if you want to throw a spanner in the works, and stop someone using your object (which is usually the intent of returning a null value, or to indicate an error), why not throw a NullPointerException ?

public MyClass()
{
// Something might go wrong, so throw a null pointer exception
throw new NullPointerException() ;
}


www.referjava.com

How I can find the class of an object?

That's easy. Suppose you've got some objects stored in a collection, like a Vector or a List of some sort. You might want to check to see if an individual object belongs to a particular class. The instanceof operator is used in this case.

For example:-

if (obj instanceof MyClass)
{
MyClass.doSomething();
}
else
{
// handle object differently .......
}


www.referjava.com

How can I append an existing file in Java?

Appending data to a file is a fairly common task. You'll be surprised to know that there was no support for file appending in JDK1.02, and developers supporting that platform are forced to re-write the entire file to a temporary file, and then overwrite the original. As most users support either JDK1.1 or the Java 2 platform, you'll probably be able to use the following FileOutputStream constructor to append data:

public FileOutputStream(String name,
boolean append)
throws FileNotFoundException
Parameters:
name - the system-dependent file name
append - if true, then bytes will be written to the end of the file rather than the beginning
For example, to append the file 'autoexec.bat' to add a new path statement on a Wintel machine, you could do the following:

FileOutputStream appendedFile = new FileOutputStream
("c:\\autoexec.bat", true);


www.referjava.com

How do I kill a thread? The stop() method is deprecated in JDK1.2, so how do I shut it down?

The API documentation for JDK1.2 discusses an alternate mechanism for stopping threads, by having them continually poll a boolean flag to see if they should terminate of their own accord. This is an option, but if you have threads that become deadlocked or stall waiting for I/O, sometimes you'll have to kill them the hard way.

Why shouldn't you normally use the Thread.stop() method? Well, it is deprecated as of JDK1.2 because it can potentially leave the system in an unsafe state. If a thread
had a lock on an object (within a synchronized block), it might not release the object lock, causing problems at a later time. Note that this problem can affect older JVM implementations as well, JDK1.02 and JDK1.1 are not immune.

So while you shouldn't use Thread.stop() unless absolutely necessary, it is an acceptable way to kill a thread if it becomes stalled and you really need to shut it down fast.


www.referjava.com

What is an abstract class, and when should it be used?

Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods. Let's look at an example of an abstract class, and an abstract method.

Suppose we were modeling the behavior of animals, by creating a class hierachy that started with a base class called Animal. Animals are capable of doing different things like flying, digging and walking, but there are some common operations as well like eating and sleeping. Some common operations are performed by all animals, but in a different way as well. When an operation is performed in a different way, it is a good candidate for an abstract method (forcing subclasses to provide a custom implementation). Let's look at a very primitive Animal base class, which defines an abstract method for making a sound (such as a dog barking, a cow mooing, or a pig oinking).

public abstract Animal
{
public void eat(Food food)
{
// do something with food....
}

public void sleep(int hours)
{
try
{
// 1000 milliseconds * 60 seconds * 60 minutes * hours
Thread.sleep ( 1000 * 60 * 60 * hours);
}
catch (InterruptedException ie) { /* ignore */ }
}

public abstract void makeNoise();
}
Note that the abstract keyword is used to denote both an abstract method, and an abstract class. Now, any animal that wants to be instantiated (like a dog or cow) must implement the makeNoise method - otherwise it is impossible to create an instance of that class. Let's look at a Dog and Cow subclass that extends the Animal class.

public Dog extends Animal
{
public void makeNoise() { System.out.println ("Bark! Bark!"); }
}

public Cow extends Animal
{
public void makeNoise() { System.out.println ("Moo! Moo!"); }
}
Now you may be wondering why not declare an abstract class as an interface, and have the Dog and Cow implement the interface. Sure you could - but you'd also need to implement the eat and sleep methods. By using abstract classes, you can inherit the implementation of other (non-abstract) methods. You can't do that with interfaces - an interface cannot provide any method implementations.


www.referjava.com

What is a "magic number" in Java, and why does it sometimes go bad (referring to a bad magic number error when loading applets) ?

The class definition files (*.class) for Java applets are loaded over the network. Sometimes during the transmission of files, the connection may be aborted, or may be scrambled, causing class loading to fail. Sometimes when copying files over to a web server, they may become garbled or a disk error might occur. For this reason, special care is taken by the JVM and the class loader, to verify that classes are intact. One of the precautions is that every class definition contains at the beginning the magic number, a sequence of four bytes that identify a file as a Java class definition file.

For those curious to know what the magic number is, it is the hexadecimal number CAFEBABE, which is used by the class loader to see if a file is really a class definition file. Please don't ask me why it spells out cafebabe - my guess it was an attempt at humor.


www.referjava.com

I'm trying to compile a Java source file, and get the error message "bad command or filename". What did I do wrong?

This is a VERY frequently asked question. You need to add a path statement in your autoexec.bat file on windows to allow the javac.exe program to be found.

For example, if you installed java to the c:\java\ directory, you'd add the following to autoexec.bat

set path=%path%;c:\java\bin\

Hint: change the path to your installation dir (e.g. c:\jdk1.1.7\bin)
Remember to rerun the autoexec.bat file or reboot before trying to compile again, or the path setting will not be acted upon.


www.referjava.com

Thursday, February 15, 2007

How do I execute or run an XML file?

You can't and you don't. XML itself is not a programming language, so XML files don't ‘run’ or ‘execute’. XML is a markup specification language and XML files are just data: they sit there until you run a program which displays them (like a browser) or does some work with them (like a converter which writes the data in another format, or a database which reads the data), or modifies them (like an editor).

If you want to view or display an XML file, open it with an XML editor or an XML browser.

The water is muddied by XSL (both XSLT and XSL:FO) which use XML syntax to implement a declarative programming language. In these cases it is arguable that you can ‘execute’ XML code, by running a processing application like Saxon, which compiles the directives specified in XSLT files into Java bytecode to process XML.

www.referjava.com

Can I use JavaScript, ActiveX, etc in XML files?

This will depend on what facilities the browser makers implement. XML is about describing information; scripting languages and languages for embedded functionality are software which enables the information to be manipulated at the user's end, so these languages do not normally have any place in an XML file itself, but in stylesheets like XSL and CSS.

XML itself provides a way to define the markup needed to implement scripting languages: as a neutral standard it neither encourages not discourages their use, and does not favour one language over another, so it is possible to use XML markup to store the program code, from where it can be retrieved by (for example) XSLT and re-expressed in a HTML script element.

Server-side script embedding, like PHP or ASP, can be used with the relevant server to modify the XML code on the fly, as the document is served, just as they can with HTML. Authors should be aware, however, that embedding server-side scripting may mean the file as stored is not valid XML: it only becomes valid when processed and served, so care must be taken when using validating editors or other software to handle or manage such files. A better solution may be to use an XML serving solution like Cocoon, AxKit, or PropelX.

www.referjava.com

Can I do mathematics using XML?

Yes, if the document type you use provides for math, and your users' browsers are capable of rendering it. The mathematics-using community has developed the MathML Recommendation at the W3C, which is a native XML application suitable for embedding in other DTDs and Schemas.

It is also possible to make XML fragments from other DTDs, such as ISO 12083 Math, or OpenMath, or one of your own making. Browsers which display math embedded in SGML have existed for many years (eg DynaText, Panorama, Multidoc Pro), and mainstream browsers are now rendering MathML (eg Mozilla, Netscape). David Carlisle has produced a set of stylesheets for rendering MathML in browsers. It is also possible to use XSLT to convert XML math markup to for print (PDF) rendering, or to use XSL:FO.

www.referjava.com

How do I create my own document type?

Document types usually need a formal description, either a DTD or a Schema. Whilst it is possible to process well-formed XML documents without any such description, trying to create them without one is asking for trouble. A DTD or Schema is used with an XML editor or API interface to guide and control the construction of the document, making sure the right elements go in the right places.

Creating your own document type therefore begins with an analysis of the class of documents you want to describe: reports, invoices, letters, configuration files, credit-card verification requests, or whatever. Once you have the structure correct, you write code to express this formally, using DTD or Schema syntax.

www.referjava.com

Is there an XML version of HTML?

Yes, the W3C recommends using XHTML which is ‘a reformulation of HTML 4 in XML 1.0’. This specification defines HTML as an XML application, and provides three DTDs corresponding to the ones defined by HTML 4.* (Strict, Transitional, and Frameset).

The semantics of the elements and their attributes are as defined in the W3C Recommendation for HTML 4. These semantics provide the foundation for future extensibility of XHTML. Compatibility with existing HTML browsers is possible by following a small set of guidelines (see the W3C site).

www.referjava.com

If XML is just a subset of SGML, can I use XML files directly with existing SGML tools?

Yes, provided you use up-to-date SGML software which knows about the WebSGML Adaptations TC to ISO 8879 (the features needed to support XML, such as the variant form for EMPTY elements; some aspects of the SGML Declaration such as NAMECASE GENERAL NO; multiple attribute token list declarations, etc).

An alternative is to use an SGML DTD to let you create a fully-normalised SGML file, but one which does not use empty elements; and then remove the DocType Declaration so it becomes a well-formed DTDless XML file. Most SGML tools now handle XML files well, and provide an option switch between the two standards

www.referjava.com

Should I use XML instead of HTML?

Yes, if you need robustness, accuracy, and persistence. XML allows authors and providers to design their own document markup instead of being limited by HTML. Document types can be explicitly tailored to an application, so the cumbersome fudging and poodlefaking that has to take place with HTML becomes a thing of the past: your markup can always say what it means (trivial example: next Monday).

Information content can be richer and easier to use, because the descriptive and hypertext linking abilities of XML are much greater than those available in HTML.

XML can provide more and better facilities for browser presentation and performance, using XSLT and CSS stylesheets;

It removes many of the underlying complexities of SGML-format HTML (which led to them being ignored and broken) in favor of a more flexible model, so writing programs to handle XML is much easier than doing the same for all the old broken HTML.

Information becomes more accessible and reusable, because the more flexible markup of XML can be used by any XML software instead of being restricted to specific manufacturers as has become the case with HTML.

XML files can be used outside the Web as well, in existing document-handling environments (eg publishing).

If your information is transient, or completely static and unreferenced, or very short and simple, and unlikely to need updating, HTML may be all you need.

www.referjava.com

Who is responsible for XML?

XML is a project of the World Wide Web Consortium (W3C), and the development of the specification is supervised by an XML Working Group. A Special Interest Group of co-opted contributors and experts from various fields contributed comments and reviews by email.

XML is a public format: it is not a proprietary development of any company, although the membership of the WG and the SIG represented companies as well as industrial research and academic institutions. The v1.0 specification was accepted by the W3C as a Recommendation on Feb 10, 1998.

www.referjava.com

Why is XML such an important development?

It removes two constraints which were holding back Web developments:

dependence on a single, inflexible document type (HTML) which was being much abused for tasks it was never designed for;

the complexity of full SGML, whose syntax allows many powerful but hard-to-program options.

XML allows the flexible development of user-defined document types. It provides a robust, non-proprietary, persistent, and verifiable file format for the storage and transmission of text and data both on and off the Web; and it removes the more complex options of SGML, making it easier to program for.

www.referjava.com

Aren't XML, SGML, and HTML all the same thing?

Not quite; SGML is the mother tongue, and has been used for describing thousands of different document types in many fields of human activity, from transcriptions of ancient Irish manuscripts to the technical documentation for stealth bombers, and from patients' clinical records to musical notation. SGML is very large and complex, however, and probably overkill for most common office desktop applications.

XML is an abbreviated version of SGML, to make it easier to use over the Web, to make it easier for you to define your own document types, and to make it easier for programmers to write programs to handle them. It omits all the complex and less-used options of SGML in return for the benefits of being easier to write applications for, easier to understand, and more suited to delivery and interoperability over the Web. But it is still SGML, and XML files may still be processed in the same way as any other SGML file (see the question on XML software).

HTML is just one of many SGML or XML applications—the one most frequently used on the Web.

Technical readers may find it more useful to think of XML as being SGML−− rather than HTML++.


SOURCE : www.referjava.com

Tuesday, February 13, 2007

How can I read the status code of a HTTP request?

If you use the URL.openStream() method, there's no way to determine whether a request was successful or not. The only alternative is to use the URL.openConnection() method, which returns a URLConnection instance. The URLConnection is an abstract class, meaning that it provides a template of methods which other classes will implement. Even though the URL.openConnection() method returns a URLConnection instance, it is actually returning a concrete implementation of that class.

When a request is made for a resource using the Hypertext Transfer Protocol, the implementation of URLConnection that is returned is a java.net.HttpURLConnection. This class defines additional methods, one of which allow you to access the response status code. To find out the status of a request, you need to cast the URLConnection to a HttpURLConnection, and invoke the int HttpUrlConnection.getResponseCode() method.

URL url = new URL ( some_url );
URLConnection connection = url.openConnection();

connection.connect();

// Cast to a HttpURLConnection
if ( connection instanceof HttpURLConnection)
{
HttpURLConnection httpConnection = (HttpURLConnection) connection;

int code = httpConnection.getResponseCode();

// do something with code .....
}
else
{
System.err.println ("error - not a http request!");
}


SOURCE : www.referjava.com

How can I create an event handling mechanism in Java? I'm used to ActiveX controls, which fire asynchronous events (i.e. when a control is finished a

The most common mechanism for this is the callback, where one class calls the method of another to notify it of an action or event. The class to be notified defines methods that will respond to specific events, such as when a mouse is clicked, dragged, or released. The AWT makes heavy use of this, with Listener interfaces. A class implements the event handling methods of a listener, and can then be registered with a component that generates these types of events. Classes that are event sources provide methods which register a listener, and at a later time when the event is generated, will invoke listener methods. The Abstract Windowing Toolkit (AWT) and Swing APIs would be a good place to start, to see if this suits your needs.


SOURCE : www.referjava.com

How can I poll a remote server, to see if it is still available? I'd like to check to see if the server has crashed, and if so, record the time.

If your application is a TCP server, the easiest way to do this is for a client to connect to it, using the java.net.Socket class. When the Socket is connected, if the server is down an IOException will be thrown, indicating that the server is not accepting connections.

However, this may not be a sufficient test for mission critical applications. What if the server has stalled, and will accept connections but not respond to them? In this situation, you'll need to write a valid request to the server (using the appropriate network protocol, such as HTTP or FTP). It doesn't matter what type of request is made, or what data is really returned (unless it is an error message). The only purpose of the request is to see if the server will response, and is still available for use.


SOURCE : www.referjava.com

Who created Java?

Java is still a relatively new language, so it is quite amusing to some to think that Java has a "history" behind it. One of the most frequent questions I've been getting lately though is about the origins of Java.

Java was created by engineers working at Sun Microsystems. The figure that stands out most of all is James Gosling, widely regarded as the "father" of Java. James and his team were working on a language whose original name was Oak. Oak was designed for embedded devices, such as mobile phones. The first publicly available version of Java, however, was as Java applets, in the original HotJava browser. From there, Java grew to what it is today.


SOURCE : www.referjava.com

How do I pass a primitive data type by reference? For example, how do I make an int passed to a function modifiable.

Java passes all primitive data types by value. This means that a copy is made, so that it cannot be modified. When passing Java objects, you're passing an object reference, which makes it possible to modify the object's member variables. If you want to pass a primitive data type by reference, you need to wrap it in an object.

The easiest of all is to pass it as an array (or even a Vector). Your array only needs to contain a single element, but wrapping it in an array means it can be changed by a function. Here's a simple example of it in action.

public static void increment(int[] array, int amount)
{
array[0] = array[0] + amount;
}

public static void main(String args[])
{
int[] myInt = { 1 };

increment (myInt, 5);

System.out.println ("Array contents : " + myInt[0]);
}
Of course, if you're modifying the contents of parameters passed to a method, you really should try to avoid this behavior. It increases the complexity of code, and really should be avoided. The preferred way is to return a value from a method, rather than modifying parameter values directly.


www.referjava.com

How do I debug my Java applets to see what's going wrong?

Often, when an applet behaves strangely or fails to work, the problem is hard to diagnose. Many applets behave fine under Netscape Navigator, only to fail under Internet Explorer (or vice versa). Sometimes a different Java Virtual Machine (JVM) will have less tolerance for a bug, and other times the fault lies in the actual JVM implementation.

The lack of information provided by the browser can be frustrating. However, there is a way to display a debugging console, which will provide developers with additional information. For example, an uncaught exception will generate an exception trace, telling you which method and which exception were involved. Both the later versions of Netscape Communicator and Internet Explorer support these debugging consoles.

To view the Java Console in Netscape Communicator
Load any page with an applet, and then select the following menu option
Communicator -> Tools -> Java Console


www.referjava.com

How do I get parameters from a HTML form when using servlets?

When extending javax.servlet.http.HttpServlet, you should override either of the following two methods: -

public void doGet(HttpServletRequest req,
HttpServletResponse res)
public void doPost(HttpServletRequest req,
HttpServletResponse res)
Both of these methods accept as a parameter a HttpServletRequest instance. This allows the servlet to obtain information about the browser request, including the parameters passed to the servlet. By using the String getParameter(String) method, you can request any parameter you need. If the parameter is not present, a null value will be returned.


www.referjava.com

How do I gray out components, and prevent users from using them?

Every AWT & Swing component inherits methods that will enable and disable it, from java.awt.Component. The setEnabled(boolean) method allows a component to be disabled, and later enabled. Previously, AWT components could be enabled and disabled by calling their enable() and disable() methods. However, these methods have been deprecated, and should no longer been used.

// Disable button (b)
b.setEnabled ( false );
// Enable button (b)
b.setEnabled ( true );


www.referjava.com

How do I make cookies expire after a set time period? For example, in five minutes time for security reasons

Depending on how you use the data stored in a cookie, it is often a good idea to make the cookie expire. Since anyone using the browser will have the cookie sent on their behalf, it may appear to be a legitimate user when in actual fact it is not. This often happens in places like Internet cafes, school or university computing labs, or libraries. If your cookie sends a user identifier that facilitates access to sensitive data, or allows changes to be made (for example, a web-based email service), then you should expire cookies after a small time period. If the user keeps using your servlet, you always have the option of resending the cookie with a longer duration.

To specify an expiration time, you can use the setMaxTime(int) method of javax.servlet.http.Cookie. It takes as a parameter the number of seconds before the cookie will expire. For example, for a five minute expiration, we would do the following :-

// Create a new cookie for userID from a fictitious
// method called getUserID
Cookie cookie = new Cookie ("userID", getUserID());

// Expire the cookie in five minutes (5 * 60)
cookie.setMaxTime( 300 );
When the cookie is sent back to the browser, using HttpServletResponse.addCookie(Cookie), it will only be returned by the browser until the expiration date occurs. If you'd prefer, you can also specify a negative value for setMaxTime(int), and the cookie will expire as soon as the browser exits. Note however that not everyone will shutdown their browser, and it might be available for minutes, hours even days. Finally, specifying a value of zero will expire the cookie instantly.


www.referjava.com

How do I read browser cookies from a servlet?

Reading cookies from a servlet is quite easy. You can gain access to any cookies sent by the browser from the javax.servlet.http.HttpServletRequest passed to the servlet's doGet, doPost, etc methods. HttpServletResponse offers a method, Cookies[] getCookies() which returns an array of Cookie objects. However, if no cookies are available, this value may be null, so be sure to check before accessing any array elements.

// Check for cookies
Cookie[] cookie_jar = request.getCookies();

// Check to see if any cookies exists
if (cookie_jar != null)
{
for (int i =0; i< cookies.length; i++)
{
Cookie aCookie = cookie_jar[i];
pout.println ("Name : " + aCookie.getName());
pout.println ("Value: " + aCookie.getValue());
}
}


www.referjava.com

How do I send cookies from a servlet?

HTTP is a stateless protocol, which makes tracking user actions difficult. One solution is to use a cookie, which is a small piece of data sent by a web browser every time it requests a page from a particular site. Servlets, and CGI scripts, can send cookies when a HTTP request is made - though as always, there is no guarantee the browser will accept it.

Cookies are represented by the javax.servlet.http.Cookie class. Cookie has a single constructor, which takes two strings (a key and a value).

// Create a new cookie
Cookie cookie = new Cookie ("counter", "1");
Adding a cookie to a browser is easy. Cookies are sent as part of a HTTPServletResponse, using the addCookie( Cookie ) method. You can call this method multiple times, but remember that most browsers impose a limit of ten cookies, and 4096 bytes of data per hostname.

public void doGet (HttpServletRequest request, HttpServletResponse response)
throws IOException
{
response.addCookie(new Cookie("cookie_name", "cookie_value"));
}


www.referjava.com

How do I get the length of a string?

Working with strings under Java is far easier than with other languages. Most languages represent a string as a data type, or as an array of characters. Java however treats strings as an actual object, and provides methods that make string manipulation far easier.

Strings under Java are represented by the java.lang.String class. Since the java.lang package is imported by every Java application or applet, we can refer to it just as String. To determine the length of a String, simply call the String.length() method, which returns an int value.

String aString = "this is a string. what is my length?";
int length = aString.length();

System.out.println (aString);
System.out.println (length);
TIP - Remember that the String class is zero-indexed. Even though the String is of length n, you can only access characters in the range 0..n-1


www.referjava.com

How do I minimize and restore frames and JFrames?

This question stumped me when I first took a look at it. There is no minimize or restore method in JFrame, or java.awt.Frame for that matter. However, I knew there had to be a way - as JFrames frequently need to be restored programmatically. I suspected that the problem was a difference in terminology, and after a little searching, found the answer.

JFrame inherits the setState method from java.awt.Frame. This method allows you to change the state of a window from "iconified", back to "normal". This is, in actual fact, minimize and restore - but the documentation uses different terms. To minimize or restore a window, we simply call the setState method, and pass it a state parameter to indicate whether we want to minimize or restore the window..

For example, to minimize a Frame (or subclass, such as JFrame), we pass the 'iconified' parameter

myFrame.setState ( Frame.ICONIFIED );
To restore the frame to its normal state, we call the setState method with the 'normal' parameter

myFrame.setState ( Frame.NORMAL );
To demonstrate this effect, I've written a small demonstration, which you can compile and run. In the following example, a new frame is created, and then minimized. After a short delay, it is restored again.

import java.awt.*;

public class FrameTest
{
public static void main (String args[]) throws Exception
{
// Create a test frame
Frame frame = new Frame("Hello");
frame.add ( new Label("Minimize demo") );
frame.pack();

// Show the frame
frame.setVisible (true);

// Sleep for 5 seconds, then minimize
Thread.sleep (5000);
frame.setState ( Frame.ICONIFIED );

// Sleep for 5 seconds, then restore
Thread.sleep (5000);
frame.setState ( Frame.NORMAL );

// Sleep for 5 seconds, then kill window
Thread.sleep (5000);
frame.setVisible (false);
frame.dispose();

// Terminate test
System.exit(0);
}
}


www.referjava.com

Is Java Y2K compliant? Where can I find more information?

I'd like to give a big unconditional yes, but its not quite that simple. Java is more than a language - its a platform. There are many different virtual machines, by many different vendors, running on many different hardware and software architectures. Does that present a Y2K threat? Yes.

However, work is being done to prevent problems. Sun takes its commitments very seriously - for a comprehensive list of products and their Y2K status visit

http://www.sun.com/y2000/cpl.html

The problem is - will all Java Virtual Machines be ready in time. Remember that some are third party ports, or completely re-engineered versions. So there is still the potential for problems if you use non-Sun virtual machines. If you use third party class libraries, or code, you're also running some risk. Of course, a quick test to reassure you, might be to turn your computer's clock forward till after Jan 1 2000.


www.referjava.com

What are exceptions, and when should I use them?

Exception handling is an important feature of C++ and Java. Exceptions indicate unusual error conditions that occur during the execution of an application or applet. When you call an object method, and an "exceptional" event occurs (such as being unable to access a file or network resource), the method can stop execution, and "throw" an exception. This means that it passes an object (the exception), back to the calling code. That code can then handle the event, and deal with unusual conditions.

That's the theory of exception handling. Let's look at a practical example. Suppose my application had to read some data from a file. Most times, it will be able to read the data, and continue on without any problems - but what would happen if the file didn't exist? Our program might crash, without reporting any meaningful error message. Let's see how exception handling can help.

The following code snippet shows our code for reading a line of text from a data file. Note the use the try / catch keywords. This indicates that code within this block can throw an exception, and how we will deal it.

String line;

try
{
// This line throws an IOException if file not present
FileInputStream fin = new FileInputStream ("config.ini");

// Create a data input stream for reading a line of text
DataInputStream din = new DataInputStream( fin );

// Read line of text
line = din.readLine();
}
catch (IOException ioe)
{
// Exit gracefully with an error message
System.err.println
("An error occurred while reading config file");
System.exit(0);
}
Exception handling also has other benefits. In the past, programmers would check the return value for a null object, or a special numerical code that indicated failure. But, programmers being human, this value wouldn't always be checked. This lead to strange errors at run-time, and no meaningful error messages. When an exception is specified in the throws clause of an object method, it must be caught, or the compiler will generate an error message. This forces programmers to always provide some form of catch statement (though many choose to leave their catch statement blank).

Finally, exception handling can also make code more legible. Its easy to see where error conditions are being handled, and which error conditions are explicitly being looked at. This also separates programming code for "normal" situations from that of handler code for unusual events. In small applications, the advantages of this are not noticeable, but when debugging large and complex systems, it helps to reduce complexity and track down problems.


www.referjava.com

How can I change the gray background of an applet?

Applets use a default background of gray, which isn't very visually appealing, and very infrequently matches the background of the web page on which it is loaded. So unless you repaint the background yourself in the paint() method of your applet, you'll want to change its background as soon as the applet loads.

The best place to do it will be in your init() method. This means the applet will change color once it has finished loading. To change background color, you need to invoke the setBackground(Color) method. It accepts as a parameter any valid Color.

public void init()
{
setBackground ( Color.black );
}


www.referjava.com

What does certification involve?

Passing the Sun Certified Java Programmer exam involves answering a series of multiple choice questions. Sound easy enough? There's a little more to it though - you must select ALL the right answers, without missing any or adding extra ones. Often the difference between one answer and another is subtle, and it requires a good understanding of the language and the base Java APIs. There's no reference material allowed, and to make it even tougher, a score of 70% or over is required to pass.

The second level of certification involves an additional programming task. You'll be given specifications, and have to implement the system (involving actual coding). This involves a more extensive coverage of the Java APIs, but there's often more than one way to solve a problem.


www.referjava.com

What are the Java Certification exams?

Industry certification helps to distinguish skilled software developers from the pack, and to give employers an idea of the skill level of candidates. There's a certain amount of prestige associated with certification (ask anyone who has studied for, and passed a certification exam), and its usually a good measure of skills. Like other vendors (such as Microsoft), Sun Microsystems offers certification for for its flagship - the Java language. This certification is suited to commercial Java programmers and developers.

There are two levels of Java certification available currently, and there are plans to expand into three levels in the future (in conjunction with Netscape and other vendors). Currently, Sun offers the following :-

Sun Certified Java Programmer for JDK1.05, JDK1.5 & Java 5
Sun Certified Java Developer for JDK1.04, JDK1.4 & Java 4


www.referjava.com

Sunday, February 11, 2007

How can I use a quote " character within a string?

When we use literal strings in Java, we use the quote (") character to indicate the beginning and ending of a string. For example, to declare a string called myString, we could this :-

String myString = "this is a string";
But what if we wanted to include a quote (") character WITHIN the string. We can use the \ character to indicate that we want to include a special character, and that the next character should be treated differently. \" indicates a quote character, not the termination of a string.

public static void main (String args[])
{
System.out.println ("If you need to 'quote' in Java");
System.out.println ("you can use single \' or double \" quote");
}


www.referjava.com

How do I compare two strings?

A common error that we all make from time to time is incorrect String comparison. Even once you learn how to compare strings correctly, it's extremely easy to make a mistake and use the == operator.

When we compare primitive data types, such as two ints, two chars, two doubles, etc. we can use the == operator. We can also use the == operator to compare two objects. However, when used with an object, the == operator will only check to see if they are the same objects, not if they hold the same contents.

This means that code like the following will not correctly compare to strings :

if ( string1 == string2 )
{
System.out.println ("Match found");
}
This code will only evaluate to true if string1 and string2 are the same object, not if they hold the same contents. This is an important distinction to make. Checking, for example, to see if
aString == "somevalue", will not evaluate to true even if aString holds the same contents.

To correctly compare two strings, we must use the .equals method(). This method is inherited from java.lang.Object, and can be used to compare any two strings. Here's an example of how to correctly check a String's contents :

if ( string1.equals("abcdef") )
{
System.out.println ("Match found");
}
This is a simple, and easy to remember tip that will safe you considerable time debugging applications. Remember - never use the == operator if you only want to compare the string's contents.


www.referjava.com

How do I convert from a char to an int?

If you want to get the ASCII value of a character, or just convert it into an int (say for writing to an OutputStream), you need to cast from a char to an int.

What's casting? Casting is when we explicitly convert from one primitve data type, or a class, to another. Here's a brief example.

public class char_to_int
{
public static void main(String args[])
{
char myChar = 'a';
int i = (int) myChar; // cast from a char to an int

System.out.println ("ASCII value - " + i);
}
}
In this example, we have a character ('a'), and we cast it to an integer. Printing this integer out will give us the ASCII value of 'a'.


www.referjava.com

How do I connect a Reader to an InputStream?

This is a very common question - after all, there aren't any SocketReaders, or PipedReaders. You need something to bridge the gap between a Reader, and an InputStream. That's where InputStreamReader comes into play.

InputStreamReader is a reader that can be connected to any InputStream - even filtered input streams such as DataInputStream, or BufferedInputStream. Here's an example that shows InputStreamReader in action.

// Connect a BufferedReader, to an InputStreamReader which is connected to
// an InputStream called 'in'.
BufferedReader reader = new BufferedReader ( new InputStreamReader ( in ) );

You can do the same with an OutputStream to a Writer (see OutputStreamWriter for more information).


www.referjava.com

When should I use an InputStream, and when should I use a Reader?

This can be confusing, particularly if you're already familiar with InputStream, and keep getting deprecated API warning messages. Let me simplify it for you.

If you're reading data, such as bytes of information, you are best off to use InputStreams and DataInputStream in particular.
If you're reading in text, and want to be able to call a readLine() method, its best to use Readers, and BufferedReader in particular.
So what's the difference? Well, DataInputStream's readLine() method is deprecated, because of problems with this method. Readers offer an alternative - though placing a readLine() method in a BufferedReader still seems a little odd to me. Whether its buffered or not has little to do with the fact it can read lines of text - but its easy enough to live with.


www.referjava.com

My application/applet loads images, but they aren't drawn to the screen. What's going on?

I've encountered this problem a few times in my own applications. When you load an image (using java.awt.Toolkit.getImage), the function returns immediately, and the image is loaded asynchronously. This means that sometimes an image isn't ready to be drawn, because it hasn't yet loaded. Depending on when the image is loaded, and when it is drawn, the problem can be intermittent and hard to track down.

If your application or applet MUST display the image, you can have it wait until the image is fully loaded. An animation applet, for example, may not have any useful work to do until the image(s) are loaded. To wait for images, you need to use the java.awt.MediaTracker class.

MediaTracker allows you to register an image with the tracker, and have your application or applet wait until the image is ready. Note that this isn't limited just to applets loading images over a network - from my own experience an application it can happen loading a small (<100 bytes) image from a local filesystem.

To register an image, you assign it an image number, and call the addImage method. Then you can call the waitFor(int) or waitForAll() methods.

// Pass media tracker any component (such as a canvas or an applet)
MediaTracker tracker = new MediaTracker( this );

// Add images
tracker.addImage ( myImage1, 0);
tracker.addImage ( myImage1, 1);
// Wait for images
try {
tracker.waitForAll();
} catch (InterruptedException ie) {}
Once you start the wait, your application will block until the image has loaded. Then, you can call java.awt.Graphics.drawImage to display the image to your applet or application.


www.referjava.com

Why can't my applet read or write to files?

Applets execute under the control of a web browser. Netscape and Internet Explorer impose a security restriction, that prohibits access to the local filesystem by applets. While this may cause frustration for developers, this is an important security feature for the end-user. Without it, applets would be free to modify the contents of a user's hard-drive, or to read its contents and send this information back over a network.

Digitally signed applets can request permission to access the local filesystem, but the easiest way around the problem is to read and write to remote files located on a network drive. For example, in conjunction with a CGI script or servlet, you could send HTTP requests to store and retrieve data.


SOURCE : www.referjava.com

How can I convert my Java classes to an executable .EXE file for Windows?

This is a very common question asked in the comp.lang.java newsgroup. Its often useful to have an executable application when deploying your applications to a specific platform, but remember to make your .class files available for users running Unix/Macintosh/other platforms.

Microsoft used to provide a free system development kit (SDK), for Java, which includes the jexegen tool. This will convert class files into a .EXE form. The only disadvantage is that users need a Microsoft Java Virtual Machine (JVM) installed. Microsoft no longer supports this however, and you should transition to a new Win 32 Java system. See http://java.sun.com/ for the latest version of a Java interpreter for Winodws.


SOURCE : www.referjava.com

My version of JDK won't run classes, even when they're in the current directory. What should I set my classpath to?

Remember always to include the current directory in your classpath. For example, on Windows systems, you might need to try

jre -cp .\ MyJavaApplication , or

java -cp .\ MyJavaApplication


SOURCE : www.referjava.com

I'm confused about variables and their scope. What's the difference between a member variable, and a local variable?

Simple! A member variable is a variable that belongs to an object, whereas a local variable belongs to the current scope. Hmm... Still confused?

When we define a class, we can give that class member variables. These variables are members of that class. Take, for example, the following class declaration.

public class MyClass {
int a;
int b;
}

MyClass has two member variables, a & b. When we define an object instance of MyClass it will still have two member variables, a & b. We can reference these members using the '.' character.

// Create an instance of MyClass
MyClass obj = new MyClass();

// Assign new values to a & b
obj.a = 1;
obj.b = 65536;

These variables belong to MyClass, and are known as member variables. On the other hand, if we declare variables inside of a function, we call these local variables. These variables are local to a particular function, and not publicly accessible. For example, in the following function, we have no way of accessing the obj variable outside of the main(String[]) function.

public static void main (String args[])
{
MyClass obj = new MyClass();

System.out.println ("A" + obj.a);
}


SOURCE : www.referjava.com

How do I create a new instance of an object?

To create a new instance of an object, we use the "new" keyword. This keyword creates a new instance of an object, which we can then assign to a variable, or invoke methods. For example, to create a new StringBuffer object, we would use the new keyword in the following way.

StringBuffer myBuffer = new StringBuffer (50);

Notice how we can also assign parameters (in this case, we are allocating at least fifty characters for our buffer). If we don't wish to specify any parameters, we could use the new keyword this way.

StringBuffer myBuffer = new StringBuffer ();

The new keyword expects a class name, followed by the parameters that will be passed to a constructor. When we have no parameters, we simple use empty ()'s.


SOURCE : www.referjava.com

How do I detect if command line arguments are empty?

Whenever you write Java applications, its vital that you check your command line arguments before using them. Not all users will remember to put in the correct number of parameters, and your application will terminate with an ArrayIndexOutOfBoundsException. Fortunately, its extremely easy to check!

Here's an example program, that checks that at least one parameter exists :

public class argsdemo
{
public static void main(String args[])
{
if (args.length == 0)
{
System.err.println ("No arguments!");
System.exit(0);
}
}
}
Just add a if statement before using a parameter, and then perhaps exit with a message. You can check for a specific number of parameters, and terminate if they're missing.


SOURCE : www.referjava.com

How do I use stacks in Java?

A stack is a data structure that allows data to be inserted (a 'push' operation), and removed (a 'pop' operation). Many stacks also support a read ahead (a 'peek' operation), which reads data without removing it. A stack is a LIFO-queue, meaning that the last data to be inserted will be the first data to be removed.

When we insert data into a stack, it is placed at the head of a queue. This means that when we remove data, it will be in reverse order. Adding 1,2,3,4 will return 4,3,2,1. Stacks aren't the most frequently used data structure, but they are extremely useful for certain tasks.


SOURCE : www.referjava.com

How can I throw an exception without declaring it in a 'throws' clause?

Sometimes it is useful to throw exceptions, without explicitly declaring them in the throws clause of a method's signature. Any exceptions that extends java.lang.RuntimeException don't need to be declared. This means that it is safe to throw subclasses (like NullPointException), or to create your own.

SOURCE : www.referjava.com

Is there any way to access C++ objects, and use their methods?

Yes! The Common Object Request Broker Architecture (CORBA), allows developers to create interfaces to their objects that work with any other CORBA compatible language. This means that a C++ object can have its methods invoked from Java, and vice verca.


SOURCE : www.referjava.com

How do I use hashtables?

Hashtables are an extremely useful mechanism for storing data. Hashtables work by mapping a key to a value, which is stored in an in-memory data structure. Rather than searching through all elements of the hashtable for a matching key, a hashing function analyses a key, and returns an index number. This index matches a stored value, and the data is then accessed. This is an extremely efficient data structure, and one all programmers should remember.

Hashtables are supported by Java, in the form of the java.util.Hashtable class. Hashtables accept as keys and values any Java object. You can use a String, for example, as a key, or perhaps a number such as an Integer. However, you can't use a primitive data type, so you'll need to instead use Char, Integer, Long, etc.

// Use an Integer as a wrapper for an int
Integer integer = new Integer ( i );
hash.put( integer, data);
Data is placed into a hashtable through the put method, and can be accessed using the get method. It's important to know the key that maps to a value, otherwise its difficult to get the data back. If you want to process all the elements in a hashtable, you can always ask for an Enumeration of the hashtable's keys. The get method returns an object, which can then be cast back to the original object type.

// Get all values with an enumeration of the keys
for (Enumeration e = hash.keys(); e.hasMoreElements();)
{
String str = (String) hash.get( e.nextElement() );
System.out.println (str);
}
To demonstrate hashtables, I've written a little demo that adds one hundred strings to a hashtable. Each string is indexed by an Integer, which wraps the int primitive data type. Individual elements can be returned, or the entire list can be displayed. Note that hashtables don't store keys sequentially, so there is no ordering to the list.

import java.util.*;

public class hash {
public static void main (String args[]) throws Exception {
// Start with ten, expand by ten when limit reached
Hashtable hash = new Hashtable(10,10);

for (int i = 0; i <= 100; i++)
{
Integer integer = new Integer ( i );
hash.put( integer, "Number : " + i);
}

// Get value out again
System.out.println (hash.get(new Integer(5)));

// Get value out again
System.out.println (hash.get(new Integer(21)));

System.in.read();

// Get all values
for (Enumeration e = hash.keys(); e.hasMoreElements();)
{
System.out.println (hash.get(e.nextElement()));
}
}
}


SOURCE : www.referjava.com

How do I make my frames close in response to user requests?

You need to define an event handler for the "WindowClosing" event. Under JDK1.02, you can add the following code to your Frame subclasses.

// Response to close events
public void WindowClosing(WindowEvent evt)
{
// Close application
System.exit(0);
}
If you're using JDK1.1 AWT event handlers, you can use the WindowAdapter class for a similar purpose. Here's a simple application that demonstrates the use of WindowAdapter, as an anonymous inner class.

import java.awt.*;
import java.awt.event.*;

public class Demo
{
public static void main ( String args[] )
{
// Create a frame with a button
Frame f = new Frame("Demo");

// Add a new button
f.add ( new Button("demo") );

// Resize/pack
f.pack();

// Add a window listener
f.addWindowListener ( new WindowAdapter () {
public void windowClosing ( WindowEvent evt )
{
System.exit(0);
}
});

// Show window
f.setVisible(true);
}
}


SOURCE : www.referjava.com

How can I change the cursor shape?

Any graphical component is capable of changing the mouse cursor. As the user moves the cursor over the component, the cursor will change. Setting a new cusor type is easy - every subclass of java.awt.Component has a setCursor method. Individual components, or even applets can specify their own cursor.

// Create an instance of java.awt.Cursor
Cursor c = new Cursor ( Cursor.WAIT_CURSOR );

// Create a frame to demonstrate use of setCursor method
Frame f = new Frame("Cursor demo");
f.setSize(100,100);

// Set cursor for the frame component
f.setCursor (c);

// Show frame
f.show();
There isn't a "global" cursor type, so this means that you can have different cursors for different components. But just remember - using cursors inappropriately will make it difficult for users, so don't put an hourglass wait component unless you actually want the user to wait! A full list of cursor types is available from the documentation for java.awt.Cursor.


SOURCE : www.referjava.com

How do I use really large numbers in Java?

There are many classes of applications that require support for large numbers. When primitive data types like long, and double just won't cut it, Java offers an answer in the form of the java.math package.

Whether its whole numbers or decimals you need, java.math has the solution. For whole numbers, use the BigInteger class, and for fractions use the BigDecimal class. Each allows a wide range of mathematical operations, from simple things like addition, subtraction, multiplication and division to more complex operations like logical AND, OR, NOT and powers.


SOURCE : www.referjava.com

Saturday, February 10, 2007

How do I execute other applications?

Sometimes a pure java implementation doesn't quite cut it. If you need to run other applications from within your app (you won't be able to do this from an applet), then here's what you need to do.

Step One
Obtain a java.lang.Runtime instance. The java.lang.Runtime class allows you to execute other applications, but you'll need an object reference before you can begin.

// Get runtime instance
Runtime r = Runtime.getRuntime();
Step Two
Next, you'll make a call to execute your application. The exec call returns a Process object, which gives you some control over the new process. If you just need to start something running, then you might want to discard the returned process.

// Exec my program
Process p = r.exec ("c:\\myprog\\inc");
Step Three
Now, if you want to do something with your process (perhaps kill it after a certain time period, or wait until its finished), you can use the methods of the java.lang.Process class. Check the Java API documentation for more information - there's plenty of things you can do. Suppose you wanted to wait until its terminated, and then continue with your app. Here's how you'd do it.

// Wait till its finished
p.waitFor();


SOURCE : www.referjava.com