Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
25 views

New Java

Uploaded by

spmsarada
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

New Java

Uploaded by

spmsarada
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 15

What is a transient variable?

A transient variable is a variable that may not be serialized.

How are Observer and Observable used in Java Programming?

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.

What is synchronization and why is it important in Java Programming?

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

What are synchronized methods and synchronized statements in Java Programming?

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.

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

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

Can a lock be acquired on a class in Java Programming?

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

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

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

What is the preferred size of a component in Java Programming?


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

What state does a thread enter when it terminates its processing in Java Programming?

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

What is the Collections API in Java Programming?

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

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.

What is the Vector class in Java Programming?

The Vector class in Java Programming provides the capability to implement a


growable array of objects

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

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

If a method is declared as protected, where may the method be accessed in Java


Programming?

A protected method may only be accessed by classes or interfaces of the same


package or by subclasses of the class in which it is declared

What is an Iterator interface in Java Programming?

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

How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters in
Java Programming?
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

What is the difference between yielding and sleeping in Java Programming?

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

Is sizeof a keyword in Java Programming?

The sizeof operator is not a keyword in Java Programming.

What are wrapped classes in Java Programming?

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

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

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

What is a native method in Java Programming?

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

How can you write a loop indefinitely in Java Programming?

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

Can an anonymous class be declared as implementing an interface and extending a class in


Java Programming?

An anonymous class may implement an interface or extend a superclass, but may


not be declared to do both.

What is the purpose of finalization in Java Programming?

The purpose of finalization is to give an unreachable object the opportunity to


perform any cleanup processing before the object is garbage collected.

Which class is the superclass for every class in Java Programming?


Object class is the superclass for every class in Java Programming

What invokes a thread’s run() method in Java Programming?

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

What is the difference between the Boolean & operator and the && operator in Java
Programming?

If an expression involving the Boolean & operator is evaluated, both operands are evaluated.
Then the & operator is applied to the operand. When an expression involving the &&
operator is evaluated, the first operand is evaluated. If the first operand returns a value of
true then the second operand is evaluated. The && operator is then applied to the first and
second operands. If the first operand evaluates to false, the evaluation of the second operand
is skipped.
Operator & has no chance to skip both sides evaluation and && operator does. If asked why,
give details as above.

What is the Properties class in Java Programming?

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

Which Container method is used to cause a container to be laid out and redisplayed in Java
Programming?

validate();
Container method is used to cause a container to be laid out and redisplayed in Java
Programming.

What is the purpose of the Runtime class in Java Programming?

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

What is the purpose of the System class in Java Programming?

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

What is the purpose of the finally clause of a try-catch-finally statement in Java


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

What is the Locale class in Java Programming?

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

What must a class do to implement an interface in Java Programming?

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

What is the purpose of the wait(), notify(), and notifyAll() methods in Java Programming?

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

What is an abstract method in Java Programming?

An abstract method is a method whose implementation is deferred to a subclass in


Java Programming.

What are the high-level thread states in Java Programming?

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

What is the difference between a static and a non-static inner class in Java Programming?

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
instance

What is an object’s lock and which object’s have locks in Java Programming?

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.

When can an object reference be cast to an interface reference in Java Programming?

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


the referenced interface.
What do heavy weight components mean in Java Programming?

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

What are peerless components in Java Programming?

The peerless components are called light weight components.

Which package has light weight components in Java Programming?

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

What is the difference between the Font and FontMetrics classes in Java Programming?

The FontMetrics class is used to define implementation-specific properties, such as


ascent and descent, of a Font object.

What happens when a thread cannot acquire a lock on an object in Java Programming?

If a thread attempts to execute a synchronized method or synchronized statement


and is unable to acquire an object’s lock, it enters the waiting state until the lock
becomes available

What is the difference between the Reader/Writer class hierarchy and the
InputStream/OutputStream class hierarchy in Java Programming?

The Reader/Writer class hierarchy is character-oriented, and the


InputStream/OutputStream class hierarchy is byte-oriented.

What classes of exceptions may be caught by a catch clause in Java Programming?

A catch clause can catch any exception that may be assigned to the Throwable
type. This includes the Error and Exception types.
If a class is declared without any access modifiers, where may the class be accessed in Java
Programming?

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

What is the Map interface in Java Programming?

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

Does a class inherit the constructors of its superclass in Java Programming?

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

Name primitive Java types?

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

Which class should you use to obtain design information about an object in Java
Programming?

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

What is the difference between static and non-static variables in Java Programming?

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

What is the difference between the paint() and repaint() methods in Java Programming?

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

What is the purpose of the File class in Java Programming?

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

How does multithreading take place on a computer with a single CPU in Java
Programming?
The operating system’s task scheduler allocates execution time to multiple tasks.
By quickly switching between executing tasks, it creates the impression that tasks
execute sequentially.

What restrictions are placed on method overloading in Java Programming?

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

What is casting in Java Programming?

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

What class allows you to read objects directly from a stream in Java Programming?

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

How are this() and super() used with constructors in Java Programming?

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

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

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

What an I/O filter in Java Programming?

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

What is the Set interface in Java Programming?


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

Is Java a super set of JavaScript?

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

Give the difference between the println method and sqrt method?

Println method operates on the object system.out and has the value which should
be printed namely y. sqrt method is a static method. It does not operate on any
object. It has the number stored in x for which the square toot should be found out.

Explain the reason behind ending a program with a System.exit (0)?

The reason behind ending a program with System.exit (0) involves technicalities.
When main method exits the new thread automatically does not end. The
appearance of this thread is because of dialog box functionality. System.exit ends
all the methods.

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

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

Stream st = new Stream(new FileOutputStream("output.txt")); System.setErr(st);


System.setOut(st);

What's the difference between an interface and an abstract class?

An abstract class may contain code in method bodies, which is not allowed in an
interface. With abstract classes, you have to inherit your class from it and Java does
not allow multiple inheritance. On the other hand, you can implement multiple
interfaces in your class.

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


Synchronized blocks place locks for shorter periods than synchronized methods.

Explain the usage of the keyword transient?

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

How can you force garbage collection?

You can't force GC, but could request it by calling System.gc(). JVM does not
guarantee that GC will be started immediately.

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

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

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

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

What's the difference between the methods sleep() and wait()

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

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

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

What's the difference between constructors and other methods?

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

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

Use this() syntax.


Explain the usage of Java packages.

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

If a class is located in a package, what do you need to change in the OS


environment to be able to use it?

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

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

What's the difference between J2SDK 1.5 and J2SDK 5.0?

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

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

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

Does it matter in what order catch statements for FileNotFoundException


and IOExceptipon are written?

Yes, it does. The FileNoFoundException is inherited from the IOException.


Exception's subclasses have to be caught first.

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


this method?

It's possible if these variables are final.

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

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

A single ampersand here would lead to a NullPointerException.

What's the main difference between a Vector and an ArrayList


Java Vector class is internally synchronized and ArrayList is not.

When should the method invokeLater()be used?

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

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

Use the following syntax: super.myMethod(); To call a constructor of the superclass,


just write super(); in the first line of the subclass's constructor.

What's the difference between a queue and a stack?


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

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

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

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

Garbage collection.

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


Object cloning.
If you're overriding the method equals() of an object, which other method
you might also consider?

hashCode()

You are planning to do an indexed search in a list of objects. Which of the


two Java collections should you use:
ArrayList or LinkedList?

ArrayList

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

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

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

Use object pooling and weak object references.


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

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

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

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

Can you have virtual functions in Java?

Yes, all functions in Java are virtual by default. This is actually a pseudo trick
question because the word "virtual" is not part of the naming convention in Java (as
it is in C++, C-sharp and VB.NET), so this would be a foreign concept for someone
who has only coded in Java. Virtual functions or virtual methods are functions or
methods that will be redefined in derived classes.

What is more advisable to create a thread, by implementing a Runnable


interface or by extending Thread class?

Strategically speaking, threads created by implementing Runnable interface are


more advisable. If you create a thread by extending a thread class, you cannot
extend any other class. If you create a thread by implementing Runnable interface,
you save a space for your class to extend another class now or in future.

What is NullPointerException and how to handle it?

When an object is not initialized, the default value is null. When the following things
happen, the NullPointerException is thrown:
--Calling the instance method of a null object.
--Accessing or modifying the field of a null object.
--Taking the length of a null as if it were an array.
--Accessing or modifying the slots of null as if it were an array.
--Throwing null as if it were a Throwable value.
The NullPointerException is a runtime exception. The best practice is to catch such
exception even if it is not required by language design.

An application needs to load a library before it starts to run, how to


code??

One option is to use a static block to load a library before anything is called. For
example,
class Test {
static {
System.loadLibrary("path-to-library-file");
}
....
}
When you call new Test(), the static block will be called first before any initialization
happens. Note that the static block position may matter.

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

The class System has a variable out that represents the standard output, and the
variable err that represents the standard error device. By default, they both point at
the system console. This how the standard output could be re-directed:
Stream st = new Stream(new FileOutputStream("output.txt")); System.setErr(st);
System.setOut(st);

What's the difference between an interface and an abstract class?

An abstract class may contain code in method bodies, which is not allowed in an
interface. With abstract classes, you have to inherit your class from it and Java does
not allow multiple inheritance. On the other hand, you can implement multiple
interfaces in your class.

What do you understand by Synchronization?

Synchronization is a process of controlling the access of shared resources by the


multiple threads in such a manner that only one thread can access one resource at
a time. In non synchronized multithreaded application, it is possible for one thread
to modify a shared object while another thread is in the process of using or
updating the object's value.
Synchronization prevents such type of data corruption.
E.g. Synchronizing a function:
public synchronized void Method1 () {
// Appropriate method-related code.
}
E.g. Synchronizing a block of code inside a function:
public myFunction (){
synchronized (this) {
// Synchronized code here.
}
}

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

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

How many methods in the Serializable interface?


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

How many methods in the Externalizable interface?

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

What is the difference between Serializalble and Externalizable interface?

When you use Serializable interface, your class is serialized automatically by


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

You might also like