My Hindi Forum

Go Back   My Hindi Forum > New India > Young World
Home Rules Facebook Register FAQ Community

Reply
 
Thread Tools Display Modes
Old 14-01-2010, 09:22 PM   #1
javaguru
Member
 
javaguru's Avatar
 
Join Date: Dec 2009
Posts: 50
Rep Power: 15
javaguru is on a distinguished road
Cool Some latest Java Interview Questions

1. Is “abc” a primitive value? - The String literal “abc” is not a primitive value. It is a String object.

2. What restrictions are placed on the values of each case of a switch statement? -
During compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value.

3. What modifiers may be used with an interface declaration? - An interface may be declared as public or abstract.

4. Is a class a subclass of itself? - A class is a subclass of itself.

5. What is the difference between a while statement and a do statement? - A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once.

6. What modifiers can be used with a local inner class? - A local inner class may be final or abstract.

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

8. Can an exception be rethrown? - Yes, an exception can be rethrown.

9. When does the compiler supply a default constructor for a class? - The compiler supplies a default constructor for a class if no other constructors are provided.

10. If a method is declared as protected, where may the method be accessed? - A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared.

11. Which non-Unicode letter characters may be used as the first character of an identifier? - The non-Unicode letter characters $ and _ may appear as the first character of an identifier

12. What restrictions are placed on method overloading? - Two methods may not have the same name and argument list but different return types.

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

14. What is the return type of a program’s main() method? - A program’s main() method has a void return type.

15. What class of exceptions are generated by the Java run-time system? - The Java runtime system generates RuntimeException and Error exceptions.

16. What class allows you to read objects directly from a stream? - The
ObjectInputStream class supports the reading of objects from input streams.

17. What is the difference between a field variable and a local variable? - A field variable is a variable that is declared as a member of a class. A local variable is a variable that is declared local to a method.

18. How are this() and super() used with constructors? - this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.

19. What is the relationship between a method’s throws clause and the exceptions that can be thrown during the method’s execution? - A method’s throws clause must declare any checked exceptions that are not caught within the body of the method.

20. Why are the methods of the Math class static? - So they can be invoked as if they are a mathematical code library.

21. What are the legal operands of the instanceof operator? - The left operand is an object reference or null value and the right operand is a class, interface, or array type.

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

23. If an object is garbage collected, can it become reachable again? - Once an object is garbage collected, it ceases to exist. It can no longer become reachable again.
javaguru is offline   Reply With Quote
Old 14-01-2010, 09:30 PM   #2
javaguru
Member
 
javaguru's Avatar
 
Join Date: Dec 2009
Posts: 50
Rep Power: 15
javaguru is on a distinguished road
Default

24. What are E and PI? - E is the base of the natural logarithm and PI is mathematical value pi.

25. Are true and false keywords? - The values true and false are not keywords.

26. What is the difference between the File and RandomAccessFile classes? - The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.

27. What happens when you add a double value to a String? - The result is a String object.

28. What is your platform’s default character encoding? - If you are running Java on English Windows platforms, it is probably Cp1252. If you are running Java on English Solaris platforms, it is most likely 8859_1.

29. Which package is always imported by default? - The java. Lang package is always imported by default.

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

31. How can my application get to know when a HttpSession is removed? - Define a Class HttpSessionNotifier which implements HttpSessionBindingListener and implement the functionality what you need in valueUnbound() method. Create an instance of that class and put that instance in Http Session.

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

33. 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 you’re 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.

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

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

36. What does it mean that a method or class is abstract? - An abstract class cannot be instantiated. Only its subclasses can be instantiated. You indicate that a class is abstract with the abstract keyword like this : public abstract class Container

37. public abstract class Container extends Component {
Abstract classes may contain abstract methods. A method declared abstract is not actually implemented in the current class. It exists only to be overridden in subclasses. It has no body. For example,
public abstract float price();
Abstract methods may only be included in abstract classes. However, an abstract class is not required to have any abstract methods, though most of them do. Each subclass of an abstract class must override the abstract methods of its superclasses or itself be declared abstract.

38. What is a transient variable? - Transient variable is a variable that may not be serialized.

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

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

41. What state does a thread enter when it terminates its processing? - When a thread terminates its processing, it enters the dead state.

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

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

44. Is sizeof a keyword? - The sizeof operator is not a keyword.

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

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

47. What value does readLine() return when it has reached the end of a file? -The readLine() method returns null when it has reached the end of a file.

48. Can a for statement loop indefinitely? - Yes, a for statement can loop indefinitely. For example, consider the following: for(; ;

49. To what value is a variable of the String type automatically initialized? - The default value of an String type is null.

50. 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.
javaguru is offline   Reply With Quote
Old 14-01-2010, 09:34 PM   #3
javaguru
Member
 
javaguru's Avatar
 
Join Date: Dec 2009
Posts: 50
Rep Power: 15
javaguru is on a distinguished road
Default

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

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

53. What do you understand by private, protected and public? - These are accessibility modifiers. Private is the most restrictive, while public is the least restrictive. There is no real difference between protected and the default type (also known as package protected) within the context of the same package, however the protected keyword allows visibility to a derived class in a different package.

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

55. Can a method be overloaded based on different return type but same argument type ?
- No, because the methods can be called without using their return type in which case there is ambiquity for the compiler

56. What happens to a static var that is defined within a method of a class ? - Can’t do it. You’ll get a compilation error

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

58. What is the difference amongst JVM Spec, JVM Implementation, JVM Runtime ? - The JVM spec is the blueprint for the JVM generated and owned by Sun. The JVM implementation is the actual implementation of the spec by a vendor and the JVM runtime is the actual running instance of a JVM implementation

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

60. What does the “final” keyword mean in front of a variable? A method? A class? -
FINAL for a variable: value is constant. FINAL for a method: cannot be overridden. FINAL for a class: cannot be derived

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

62. Why does it take so much time to access an Applet having Swing Components the first time? - Because behind every swing component are many Java objects and resources. This takes time to create them in memory. JDK 1.3 from Sun has some improvements which may lead to faster execution of Swing applications.

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

64. Name the containers which uses Border Layout as their default layout?
: Containers which uses Border Layout as their default are: window, Frame and Dialog classes.

65. 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:
Code:
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.
}
}
javaguru is offline   Reply With Quote
Old 15-01-2010, 12:44 PM   #4
sudhir
Member
 
sudhir's Avatar
 
Join Date: Jan 2010
Location: alibagh
Posts: 108
Rep Power: 15
sudhir is on a distinguished road
Default More Jave Interview Questions

Is it necessary to override hashcode whenever equals method is overridden? why? public int hashCode() This method must be overridden in every class that overrides the equals method. Equal objects must produce the same hash code as long as they are equal, however unequal objects need not produce distinct hash codes.

Explain the servlet life cycle?

1. The web container loads the servlet class and create an instance.
2. Then it initializes the servlet instance by calling the init()
3. The service method is called to serve the requests
4. The conatiner finalizes the servlet by calling the destroy method.

What are the limitations with regard to Java Reflection in EJB?

In general Java Reflection is allowed in EJB, only those apis which inspect the private or protected variables are disallowed.

How to access a singleton class?

There should be static method which gives the instance of the singleton class. Call that static method which gives you the instance .Once you have instance you can call the methods in that class. The static method which is giving object is take care of single instance of the object.

What is the ResourceBundle class?

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

In Java collections HashMap or HashSet, to use as a key, will you prefer a mutable object or immutable object? and why do you prefer?

Hash value is used in identifying objects in Hash collections, to be 100% accurate all the time the hash value should not change. So immutable objects are a perfect solution for this.

Is there any advantage in extending Thread class rather than implementing Runnable interface?

when there is a need to run multiple threads with their own instance variables extending threads makes sensible. Wherein implementing runnable makes sense in single execution models.


what are the differences between UDP and TCP?

UDP (user datagram protocol), is a connectionless protocol.
each time you send datagrams, you also need to send the local socket descriptor and the receiving socket’s addressTCP is a connection-oriented protocol. a connection must first be established between the pair of sockets.

While one of the sockets listens for a connection request (server), the other asks for a connection (client).

Once two sockets have been connected, they can be used to transmit data in both (or either one of the) directions

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.

Int vs Integer which one is mutable and which is immutable?

int is mutable Integer is immutable

Can an interface be declared final? If yes how and if no why?

1. Interfaces cannot be declared final.

2. Interfaces are meant to be implemented,they dont have any code implemented within them.

3. They cannot be instantiated.

In java thread creation models Runnable and Thread, Which one is better why?

By implementing Runnable interface we are free to extend any other class and implement any other interfaces. This gives a strong advantage incase of Runnable interface.

What are the differences between Vector and ArrayList? Which is best to use? ArrayList is faster and also it occupies less memory space whereas vector takes more memory space.

Vector is a synchronized object, while ArrayList is not iterator that are returned by both classes are fail-fast, but the Enumeration returned by Vector are not .

Can you tell some immutable classes in java?

1. The main immutable class is String.

2. Basic numeric classes like Integer, Long, Float, BigInteger and BigDecimal are immutable classes.

Difference between interface and abstract class?

If you know the generic method which you are going to use in all subclasses then implement it in abstract class and leave remaining unknown implementation methods as just declare in the abstract class so the sub classes are going to implement based on their business logic.

More clearly :


Let’s discuss what Interfaces and Abstract Classes are all about to understand the differences between the two more clearly and completely.

Interface: Java Interfaces are equivalent to protocols. They basically represent an agreed-upon behavior to facilitate interaction between unrelated objects. For example, the buttons on a Remote Controller form the interface for outside world to interact with TV. How this interface is implemented by different vendors is not specified and you’re hardly aware of or bothered about how these buttons have been implemented to work internally. Interface is plainly a contract between the producer and the consumer. How the producer implements the exposed behavior is normally not cared by the consumer.

In Java, an Interface is normally a group of methods with empty bodies. You can have constant declarations in a Java Interface as well. A class that implements the interface agrees to the exposed behavior by implementing all the methods of the interface.

interface TVRemoteController{
void power();
void setChannel(int channelNumber);
void upChannel();
void downChannel();
void upVolume();
void downVolume();
……
}

A sample implementation of this interface by a vendor, say Sony:

public class SonyTVRemoteController implements TVRemoteController{
/*…this class can have other methods, properties as well …*/
……
void power(){
//implementation of power() method of the interface
}
void setChannel(int channelNumber){
//implementation of setChannel(int) method of the interface
}
//similarly, implementation of other methods of the interface
……
}

Implementing an interface means the class will support at least the exposed behavior. It can definitely add any number of extra behaviors/properties for its clients. That’s why few Remote Controllers have hell lot of buttons

Abstract Class: In Java, abstract class is a class which has been declared ‘abstract’. By declaring ‘abstract’ we ensure that the class can’t be instantiated. Why to have such a class then? Because, you would not be having implementation of all the methods in that class and you need to leave it to the subclass to decide how to implement them. In this case, there is no point instantiating an incomplete class.

An abstract method is a method which doesn’t have any implementation. If a class has even a single abstract method, then you got to declare the class ‘abstract’. Though, you don’t need to have at least one abstract method to declare a class abstract. You can declare a complete class as ‘abstract’ as well. This practice is seldom used. One possible reason may be that you never want your clients to instantiate your class directly even though you’ve already provided default implementation of all the methods. Strange! Yeah… it is. The designer of such a class may like to provide the default implementation of at least one method just to serve as a template (and not the actual implementation) for the client and thus making the class incomplete. So, a client first needs to subclass and implement the method(s) by overriding them. Now the subclass will be a concrete/complete class. Does it make some sense? Okay… Let me try to give another example. Think of a hypothetical situation, where you need to design a class, which will have ‘n’ methods and ‘n’ clients, where every single client wants default implementation of ‘n-1’ methods and it needs to implement only one (unique to every client) of the methods. In such a situation, you may not like to declare any of the methods ‘abstract’ as it’ll be required to be a non-complete method only for one of the clients and a complete implementation for other ‘n-1’ clients. If you declare it ‘abstract’ then every client will need to implement it and you’ll end up getting ‘n-1’ same piece of code. On the other hand, if you don’t declare ‘abstract’ then you simply need to override this method in corresponding sub class. Since, the base class is incomplete in all the ‘n’ cases. Assuming that this class will have only these many forms of usage, you’ll never require having an instance of it. That’s why you would declare it ‘abstract’.

Code:
public abstract class SampleAbstractClass{
//…fields
……
//…non-abstract methods, if any
……
//…abstract method, if any J
abstract void sampleAbstractMethod(); //… ends with ‘;’
}

public class SubClassOfSampleAbstractClass extends SampleAbstractClass{
//… fields, and non-abstract methods (if any)
……
//…implementation of the abstract method
void sampleAbstractMethod(){
……
}
}
sudhir is offline   Reply With Quote
Old 15-01-2010, 12:45 PM   #5
sudhir
Member
 
sudhir's Avatar
 
Join Date: Jan 2010
Location: alibagh
Posts: 108
Rep Power: 15
sudhir is on a distinguished road
Smile

Difference between Interfaces and Abstract Classes: From the language perspective, there are several differences, few of them are:-

•An abstract class may contain fields, which are not ‘static’ and ‘final’ as is the case with interfaces.
•It may have few (or all) implemented methods as well, whereas Interfaces can’t have any implementation code. All the methods of an interface are by default ‘abstract’. Methods/Members of an abstract class may have any visibility: public, protected, private, none (package). But, those of an interface can have only one type of visibility: public.
•An abstract class automatically inherits the Object class and thereby includes methods like clone(), equals(), etc. There is no such thing with an interface. Likewise, an abstract class can have a constructor, but an interface can’t have one…
•Another very famous difference is that Interfaces are used to implement multiple inheritance in Java as a class in Java can explicitly have only one super class, but it can implement any number of interfaces… blah blah…
From the performance perspective, the different is that Interfaces may be little slower as they require extra indirection to find the corresponding method in the actual class. Though, modern JVMs have already made that difference very little.

If you want to add a new method to an interface, then you either need to track all the classes implementing that interface or you’ll extend that interface to make a new interface having that extra method(s). In case of an abstract class, you’ll simply add the default implementation of that method and all the code will continue to work.

Many differences are listed already, but the main difference lies in the usage of the two. They are not rivals, but in most of the cases they are complimentary. We need to understand when to use what.

When to use an Interface: it asks you to start everything from scratch. You need to provide implementation of all the methods. So, you should use it to define the contract, which you’re unsure of how the different vendors/producers will implement. So, you can say that Interfaces can be used to enforce certain standards.

When to use an Abstract Class: it is used mostly when you’ve partial implementation ready with you, but not the complete. So, you may declare the incomplete methods as ‘abstract’ and leave it to the clients to implement it the way they actually want. Not all the details can be concrete at the base class level or different clients may like to implement the method differently.

<!--[if !supportEmptyParas]--><!--[endif]-->

When to use both: if you want to implement multiple inheritance where you have the luxury of providing partial implementation as well. You’ll then put all that code in an abstract class (this can be a concrete class as well… but here we assume that the class is also only partially implemented and hence an abstract class), extend that class, and implement as may interfaces as you want.

<!--[if !supportEmptyParas]-->

If you don’t know any method implementation at that time declaration then go for interface.

•Abstract class may contain some fully implemented methods, but in interface one has to implement every method.

•A class gets the ability to implement multiple interfaces but only one abstract class.

What are the differences between HashMap and Hashtable?

Both provide key-value access to data Access to the Hashtable is synchronized on the table while access to the HashMap isn’t.

Iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn’t.

If you change the map while iterating, you’ll know.

And, a third difference is that HashMap permits null values in it, while Hashtable doesn’t. Also Map allows you to iterate over keys, values, or key-value pairs; Hashtable did not provide the third option
sudhir is offline   Reply With Quote
Reply

Bookmarks

Tags
java interview questions


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off



All times are GMT +5. The time now is 06:24 PM.


Powered by: vBulletin
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
MyHindiForum.com is not responsible for the views and opinion of the posters. The posters and only posters shall be liable for any copyright infringement.