Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts
An ArrayList is ordered collection (also known as a sequence). It means that the user of controls where each element is inserted. This class is very similar to the Vector class, excepting that it is not synchronized. It must be synchronized externally.
An ArrayList is better than Array to use when you have no knowledge in advance about elements number. ArrayList are slower than Arrays. So, if you need efficiency try to use Arrays if possible.
Short Overview on main features of ArrayList:

  • - The add operation runs O(n) time.
  • - The isEmpty, size, iterator, set, get and listIterator operations require the same amount of time, independently of element you access.
  • - Only Objects can be added to an ArrayList
  • - Implements all methods from the List interface
  • - Permits null elements
An ArrayList could be a good choice if you need very flexible Array type of collection with limited functionality.
One small remark for those who needs faster ArrayList. ArrayLists internally implemented as an Array. So when run an "add" command a new Array will be created with n+1 dimension. All "older" elements will be copied to first n elements and last n+1 one will filled with the value which you provide with add() method. To avoid that internal re-copying of Arrays you should use ensureCapacity(int requestCapacity) method - it will create an array only once.
If you have higher requirements on number of accessible methods for your Array like collection instead of ArrayList you have better choice - LinkedList.
LinkedList is much more flexible and lets you insert, add and remove elements from both sides of your collection - it can be used as queue and even double-ended queue!
Internally a LinkedList does not use arrays, it is much more modern! LinkedList is a sequence of nodes, which are double linked. Each node contains header, where actually objects are stored, and two links or pointers to next or previous node. A LinkedList looks like a chain, consisting of people who hold each other's hand. You can insert people or node into that chain or remove. Linked lists permit node insert/remove operation at any point in the list in constant time.
LinkedList is actually luxury extension of an ArrayList: it gives you many methods which you usually implement yourself around of different type of collections.
For example if you need to add new element to the end of an ArrayList you have to look at the size of the collection and then add that new element at n+1 place. In LinkedList you do it directly by addLast(E e) method.
Another example. Depending on your expectations you can chose either getFirst/getLast or  peekFirst/peekLast methods. Last "peek" methods are completelly new sort of methods and introduced in Java 1.6.
They slightly differs from set/get methods - they do not throw any kind of exceptions if this list is empty, return just null.
New "poll" methods - pollFirst and pollLast combine two methods: get and remove an element from your collection. For example pollFirst() method gets and removes the first element from this list. This method does throw any kind of exception like IndexOutOfBoundsException in case of ArrayList, instead it just returns null (if this list is empty).
Because the LinkedList implements queue interface you can pop and push new elements from/into your collection.
If you created capacity restricted collection you can "examine" the result of an operation by using offerFirst/offerLast methods. They are also new (since Java 1.6) and return boolean result on the operations instead of throwing IllegalStateException as addFirst/addLast methods do. In case if possible to insert an element at the beginning/end of collection you you get "true" result.

Vector is similar to ArrayList with the difference that it is synchronized. It offers some other benefits like it has an initial capacity and an incremental capacity. So if your vector has a capacity of 10 and incremental capacity of 10, then when you are adding the 11th element a new Vector would be created with 20 elements and the 11 elements would be copied to the new Vector. So addition of 12th to 20th elements would not require creation of new vector
Hashtable
Hashtable is basically a datastructure to retain values of key-value pair.

  • It didn’t allow null for both key and value. You will get NullPointerException if you add null value.
  • It is synchronized. So it comes with its cost. Only one thread can access in one time



HashMap
Like Hashtable it also accepts key value pair.
  • It allows null for both key and value
  • It is unsynchronized. So come up with better performance

HashSet
HashSet does not allow duplicate values. It provides add method rather put method. You also use its contain method to check whether the object is already available in HashSet. HashSet can be used where you want to maintain a unique list.

Collection is the root interface in collection hierarchy,groups multiple elements into a single unit, it allows duplicate & non-duplicate elements  which may be ordered or unordered.
Collections is a class which extends Object class & it consists exclusively static methods .It is a member of Java Collections Framework.Collections are used to store,retrieve, manipulate, and communicate aggregate data

Collection is the interface. which can be implemented List,set,Queue.This interface contain only instance methods.
Collections is the class .This class contain utility methods such as all algorithm oriented methods.This class contain only static methods.
Other nonabstract methods can access a method that you declare as abstract.
But first, let's look at when to use normal class definitions and when to use interfaces. Then I'll tackle abstract classes.
Class vs. interface
Some say you should define all classes in terms of interfaces, but I think recommendation seems a bit extreme. I use interfaces when I see that something in my design will change frequently.
For example, the Strategy pattern lets you swap new algorithms and processes into your program without altering the objects that use them. A media player might know how to play CDs, MP3s, and wav files. Of course, you don't want to hardcode those playback algorithms into the player; that will make it difficult to add a new format like AVI. Furthermore, your code will be littered with useless case statements. And to add insult to injury, you will need to update those case statements each time you add a new algorithm. All in all, this is not a very object-oriented way to program.
With the Strategy pattern, you can simply encapsulate the algorithm behind an object. If you do that, you can provide new media plug-ins at any time. Let's call the plug-in class MediaStrategy. That object would have one method: playStream(Stream s). So to add a new algorithm, we simply extend our algorithm class. Now, when the program encounters the new media type, it simply delegates the playing of the stream to our media strategy. Of course, you'll need some plumbing to properly instantiate the algorithm strategies you will need.
This is an excellent place to use an interface. We've used the Strategy pattern, which clearly indicates a place in the design that will change. Thus, you should define the strategy as an interface. You should generally favor interfaces over inheritance when you want an object to have a certain type; in this case, MediaStrategy. Relying on inheritance for type identity is dangerous; it locks you into a particular inheritance hierarchy. Java doesn't allow multiple inheritance, so you can't extend something that gives you a useful implementation or more type identity.
Interface vs. abstract class
Choosing interfaces and abstract classes is not an either/or proposition. If you need to change your design, make it an interface. However, you may have abstract classes that provide some default behavior. Abstract classes are excellent candidates inside of application frameworks.
Abstract classes let you define some behaviors; they force your subclasses to provide others. For example, if you have an application framework, an abstract class may provide default services such as event and message handling. Those services allow your application to plug in to your application framework. However, there is some application-specific functionality that only your application can perform. Such functionality might include startup and shutdown tasks, which are often application-dependent. So instead of trying to define that behavior itself, the abstract base class can declare abstract shutdown and startup methods. The base class knows that it needs those methods, but an abstract class lets your class admit that it doesn't know how to perform those actions; it only knows that it must initiate the actions. When it is time to start up, the abstract class can call the startup method. When the base class calls this method, Java calls the method defined by the child class.

Hi friends this is the stuff for Object oriented programming concepts and the OOAD concepts based on previous year papers and the various faq's. Hope this will help in your placements...

OOPS

1. Name some pure object oriented languages.
Ø Smalltalk,
Ø Java,
Ø Eiffel,
Ø Sather.
2. What do you mean by the words ‗Abstraction‘, ‗Separation‘, ‘Composition‘, and ‗Generalization‘?
Abstraction:
Simplifying the description of a real world entity to its essentials.
Separation:
Treating what an entity does and how it does it independently of each other.
Composition:
Building complex whole components by assembling simpler parts in one of the two ways, Association and aggregation.
Generalization:
Identifying common elements in an entity.
3. What is information hiding?
Information hiding is a mechanism that separates the implementation of the class from its user.
4. Differentiate between the message and method.
Message Method
Objects communicate by sending messages Provides response to a message.
to each other.
A message is sent to invoke a method. It is an implementation of an
operation.
5. What is the interface of a class?
The interface of the class is the view provided to the outside world, which hides its internal structure and behaviour.
6. What is an adaptor class or Wrapper class?
A class that has no functionality of its own. Its member functions hide the use of a third party software component or an object with the non-compatible interface or a non- object- oriented implementation.
7. What is a node class?
A node class is a class that,
Ø relies on the base class for services and implementation,
Ø provides a wider interface to te users than its base class,
Ø relies primarily on virtual functions in its public interface
Ø depends on all its direct and indirect base class
Ø can be understood only in the context of the base class
Ø can be used as base for further derivation
Ø can be used to create objects.
A node class is a class that has added new services or functionality beyond the services inherited from its base class.
8. What is an orthogonal base class?
If two base classes have no overlapping methods or data they are said to be independent of, or orthogonal to each other. Orthogonal in the sense means that two classes operate in different dimensions and do not interfere with each other in any way. The same derived class may inherit such classes with no difficulty.
9. What is a container class? What are the types of container classes?
A container class is a class that is used to hold objects in memory or external storage. A container class acts as a generic holder. A container class has a predefined behavior and a well-known interface. A container class is a supporting class whose purpose is to hide the topology used for maintaining the list of objects in memory. When a container class contains a group of mixed objects, the container is called a heterogeneous container; when the container is holding a group of objects that are all the same, the container is called a homogeneous container.
10. What is a protocol class?
An abstract class is a protocol class if:
Ø it neither contains nor inherits from classes that contain member data, non-virtual functions, or private (or protected) members of any kind.
Ø it has a non-inline virtual destructor defined with an empty implementation,
Ø all member functions other than the destructor including inherited functions, are declared pure virtual functions and left undefined.
11. What is a mixin class?
A class that provides some but not all of the implementation for a virtual base class is often called mixin. Derivation done just for the purpose of redefining the virtual functions in the base classes is often called mixin inheritance. Mixin classes typically don't share common bases.
12. What is a concrete class?
A concrete class is used to define a useful object that can be instantiated as an automatic variable on the program stack. The implementation of a concrete class is defined. The concrete class is not intended to be a base class and no attempt to minimize dependency on other classes in the implementation or behavior of the class.
13. What is the handle class?
A handle is a class that maintains a pointer to an object that is programmatically accessible through the public interface of the handle class.
In case of abstract classes, unless one manipulates the objects of these classes through pointers and references, the benefits of the virtual functions are lost. User code may become dependent on details of implementation classes because an abstract type cannot be allocated statistically or on the stack without its size being known. Using pointers or references implies that the burden of memory management falls on the user. Another limitation of abstract class object is of fixed size. Classes however are used to represent concepts that require varying amounts of storage to implement them.
A popular technique for dealing with these issues is to separate what is used as a single object in two parts: a handle providing the user interface and a representation holding all or most of the object's state. The connection between the handle and the representation is typically a pointer in the handle. Often, handles have a bit more data than the simple representation pointer, but not much more. Hence the layout of the handle is typically stable, even when the representation changes and also that handles are small enough to move around relatively freely so that the user needn‘t use the pointers and the references.
14. What is an action class?
The simplest and most obvious way to specify an action in C++ is to write a function. However, if the action has to be delayed, has to be transmitted 'elsewhere' before being performed, requires its own data, has to be combined with other actions, etc then it often becomes attractive to provide the action in the form of a class that can execute the desired action and provide other services as well. Manipulators used with iostreams is an obvious example.
A common form of action class is a simple class containing just one virtual function.
class Action{
public:
virtual int do_it( int )=0;
virtual ~Action( );
}
Given this, we can write code say a member that can store actions for later execution without using pointers to functions, without knowing anything about the objects involved, and without even knowing the name of the operation it invokes. For example:
class write_file : public Action{
File& f;
public:
int do_it(int){
return fwrite( ).suceed( );
}
};
class error_message: public Action{
response_box db(message.cstr( ),"Continue","Cancel","Retry");
switch (db.getresponse( )) {
case 0: return 0;
case 1: abort();
case 2: current_operation.redo( );return 1;
}
};
A user of the Action class will be completely isolated from any knowledge of derived classes such as write_file and error_message.
15. What are seed classes?
In C++, you design classes to fulfill certain goals. Usually you start with a sketchy idea of class requirements, filling in more and more details as the project matures. Often you wind up with two classes that have certain similarities. To avoid duplicating code in these classes, you should split up the classes at this point, relegating the common features to a parent and making separate derived classes for the different parts. Classes that are made only for the purpose of sharing code in derived classes are called seed classes.
16. What is an accessor?
An accessor is a class operation that does not modify the state of an object. The accessor functions need to be declared as const operations
17. What is an inspector?
Messages that return the value of an attribute are called inspector.
18. What is a modifier?
A modifier, also called a modifying function is a member function that changes the value of at least one data member. In other words, an operation that modifies the state of an object. Modifiers are also known as ‗mutators‘.
19. What is a predicate?
A predicate is a function that returns a bool value.
20. What is a facilitator?
A facilitator causes an object to perform some action or service.
21. State the "Rule of minimality" and its corollary?
The rule of minimality states that unless a behavior is needed, it shouldn't be part of the ADT.
Corollary of the rule of minimality: If the function or operator can be defined such that, it is not a member. This practice makes a non-member function or operator generally independent of changes to the class's implementation.
22. What is reflexive association?
The 'is-a' is called a reflexive association because the reflexive association permits classes to bear the is-a association not only with their super-classes but also with themselves. It differs from a 'specializes-from' as 'specializes-from' is usually used to describe the association between a super-class and a sub-class. For example:
Printer is-a printer.
23. What is slicing?
Slicing means that the data added by a subclass are discarded when an object of the subclass is passed or returned by value or from a function expecting a base class object.
Consider the following class declaration:
class base{
...
base& operator =(const base&);
base (const base&);
}
void fun( ){
base e=m;
e=m;
}
As base copy functions don't know anything about the derived only the base part of the derived is copied. This is commonly referred to as slicing. One reason to pass objects of classes in a hierarchy is to avoid slicing. Other reasons are to preserve polymorphic behavior and to gain efficiency.
24. What is a Null object?
It is an object of some class whose purpose is to indicate that a real object of that class does not exist. One common use for a null object is a return value from a member function that is supposed to return an object with some specified properties but cannot find such an object.
25. Define precondition and post-condition to a member function.
Precondition:
A precondition is a condition that must be true on entry to a member function. A class is used correctly if preconditions are never false. An operation is not responsible for doing anything sensible if its precondition fails to hold.
For example, the interface invariants of stack class say nothing about pushing yet another element on a stack that is already full. We say that isful() is a precondition of the push operation.
Post-condition:
A post-condition is a condition that must be true on exit from a member function if the precondition was valid on entry to that function. A class is implemented correctly if post-conditions are never false.
For example, after pushing an element on the stack, we know that isempty() must necessarily hold. This is a post-condition of the push operation.
26. What is class invariant?
A class invariant is a condition that defines all valid states for an object. It is a logical condition to ensure the correct working of a class. Class invariants must hold when an object is created, and they must be preserved under all operations of the class. In particular all class invariants are both preconditions and post-conditions for all operations or member functions of the class.
27. What are the conditions that have to be met for a condition to be an invariant of the class?
Ø The condition should hold at the end of every constructor.
Ø The condition should hold at the end of every mutator(non-const) operation.
28. What are proxy objects?
Objects that points to other objects are called proxy objects or surrogates. Its an object that provides the same interface as its server object but does not have any functionality. During a method invocation, it routes data to the true server object and sends back the return value to the object. template class Array2D{
public:
class Array1D{
public:
T& operator[] (int index);
const T& operator[] (int index) const;
...
};
Array1D operator[] (int index);
const Array1D operator[] (int index) const;
...
};
The following then becomes legal:
Array2Ddata(10,20);
........
cout<B, B=>c then A=>c.
A. Salesman, B. Employee, C. Person.
Note:
All the other relationships satisfy all the properties like Structural properties, Interface properties, Behaviour properties.
12. Differentiate Aggregation and containment?
Aggregation is the relationship between the whole and a part. We can add/subtract some properties in the part (slave) side. It won't affect the whole part.
Best example is Car, which contains the wheels and some extra parts. Even though the parts are not there we can call it as car.
But, in the case of containment the whole part is affected when the part within that got affected. The human body is an apt example for this relationship. When the whole body dies the parts (heart etc) are died.
13. Can link and Association applied interchangeably?
No, You cannot apply the link and Association interchangeably. Since link is used represent the relationship between the two objects.
But Association is used represent the relationship between the two classes.
14. List out some of the object-oriented methodologies.
Ø Object Oriented Development (OOD) (Booch 1991,1994).
Ø Object Oriented Analysis and Design (OOA/D) (Coad and Yourdon 1991).
Ø Object Modelling Techniques (OMT) (Rumbaugh 1991).
Ø Object Oriented Software Engineering (Objectory) (Jacobson 1992).
Ø Object Oriented Analysis (OO (Shlaer and Mellor 1992).
Ø The Fusion Method (Coleman 1991).
15. What is meant by "method-wars"?
Before 1994 there were different methodologies like Rumbaugh, Booch, Jacobson, Meyer etc who followed their own notations to model the systems. The developers were in a dilemma to choose the method which best accomplishes their needs. This particular time-span was called as "method-wars".
16. Whether unified method and unified modeling language are same or different?
Unified method is convergence of the Rumbaugh and Booch. Unified modeling lang. is the fusion of Rumbaugh, Booch and Jacobson as well as Betrand Meyer (whose contribution is "sequence diagram"). Its' the superset of all the methodologies.
17. Who were the three famous amigos and what was their contribution to the object community?
The Three amigos namely,
Ø James Rumbaugh (OMT): A veteran in analysis who came up with an idea about the objects and their Relationships (in particular Associations).
Ø Grady Booch: A veteran in design who came up with an idea about partitioning of systems into subsystems.
Ø Ivar Jacobson (Objectory): The father of USECASES, who described about the user and system interaction.
17. Differentiate the class representation of Booch,Rumbaugh and UML?
If you look at the class representaiton of Rumbaugh and UML, It is some what similar and both are very easy to draw.
Representation:
OMT
ClassName
+Public Attribute;#protected Attribute;-private Attribute;
+Public Method();#Protected Method();-private Method();
UML.
ClassName<>
+Public Attribute;#protected Attribute;-private Attribute;classattribute;
+Public Method();#Protected Method();-private Method();classmethod();
Booch:
In this method classes are represented as "Clouds" which are not very easy to draw as for as the developer's view is concern.
Representation:
18. What is an USECASE?why it is needed?
A Use Case is a description of a set of sequence of actions that a system
performs that yields an observable rsult of value to a particular action.
Simply, in SSAD process <=> In OOAD USECASE. It is represented elliptically.
Representation:
19. Who is an Actor?
An Actor is someone or something that must interact with the system.In addition to that an Actor initiates the process (that is USECASE).
It is represesnted as a stickman like this.
Representation:
20. What is guard condition?
Guard condition is one which acts as a firewall. The access from a particular object can be made only when the particular condition is met.
For Example,
here the object on the customer acccess the ATM facility only when the guard condition is met.
21. Differentiate the following notations?
I:
II:
In the above I represention Student Class sends message to Course Class
but in the case of second , the data is transfered from student Class to Course Class
22. USECASE is an implementaion independent notation. How will the designer give the implementaion details of a particular USECASE to the programmer?
This can be accompllished by specifying the relationship called "refinement" that talkes about the two different abstraction of the same thing.
For example,
In the above example calculate Pay is an USECASE. It is refined in terms of giving the implementation details. This kind of connection is related by means of ―refinement‖.
23. Suppose a class acts an Actor in the problem domain,how can i represent it in the
static model?
In this senario you can use ―stereotype‖.since stereotype is just a string that gives extra semantic to the particular entity/model element.
It is given with in the << >>.
Class<< Actor>>
Attributes
MemberFunctions
24. Why does the function arguments are called as "signatures"?
The arguments distinguishes functions with the same name (functional polymorphism). The name alone does not necessarily identify a unique function. However, the name and its arguments (signatures) will uniquely identify a function.
In real life we see suppose,in class there are two guys with same name.but they can be easily identified by their signatures.The same concept is applied here.
For example:
class person
{
public:
char getsex();
void setsex(char);
void setsex(int);
};
In this example we can see that there is a function setsex() with same name but with different signature.


Reblog this post [with Zemanta]

Java (programming language)Image via Wikipedia

hi friends these are some faq's on java programming as per collected from various years and companies papers . hope this will you in your preparations..


Note: All the programs are tested under JDK
1.3 Java compiler.
1. class ArrayCopy{
public static void main(String[] args){
int ia1[] = { 1, 2 };
int ia2[] = (int[])ia1.clone();
System.out.print((ia1 == ia2) + " ");
ia1[1]++;
System.out.println(ia2[1]);
}
}
Answer:
false 2
Explanation:
The clone function creates a new object with a copy of the original object. The == operator compares for checking if the both refer to the same object and returns false (a boolean value) because they are different objects. When concatenated with a string it prints ‗false‘ instead of 0.
Since ia1 and ia2 are two different array objects the change in the values stored in ia1 array object doesn‘t affect the object ia2.
2. import javautil.StringTokenizer;
class STTest {
public static void main(String args[]) {
String s = "9 23 45.4 56.7";
StringTokenizer st = new StringTokenizer(s);
while (st.hasMoreTokens())
System.out.println(st.nextToken());
}
}
Answer: 9
23
45.4
56.7
Explanation:
The StringTokenizer parses the given string to return the individual tokens. Here the String ‗s‘ has four white-spaces that act as a separators, resulting in the printing of those individual tokens.
3. class ConvertTest {
public static void main (String args[]){
String str;
str = "25";
int i = Integer.valueOf(str).intValue();
System.out.println(i);
str = "25.6";
double d = Double.valueOf(str).doubleValue();
System.out.println(d);
}
}
Answer:
25 25.6
Explanation:
This program just explains how the static member funntions of the classes Integer and Double can be used to convert the string values that have numbers to the get primitive data-type values.
4. class StaticTest {
public static void main(String[] args) {
int i = getX();
}
public int getX() {
return 3;
}
}
Answer:
Compiler Error : Cannot access a non-static member
Explanation:
The static method, main(), belongs to the class. However,getX() belongs to an object in the class. The compiler doesn't know on which object it's invoking the getX() method.There are a couple of ways around this problem. You could declare that getX() as static; that is:
public static int getX()
Alternately, you can instantiate an object in the StaticTest class in the main() method and invoke that object's getX() method, like this:
public static void main(String[] args) {
StaticTest st = new StaticTest();
int i = st.getX();
}
5. class Test {
public static void main(String[] args) {
String s1 = new String("Hello World");
String s2 = new String("Hello World");
if (s1 == s2)
System.out.println("The strings are the same.");
else
System.out.println("The strings are different.");
}
}
Answer:
The strings are different.
Explanation:
When used on objects, == tests whether the two objects are the same object, not whether they have the same value.
To compare two objects for equality, rather than identity, you should use the equals() method.
6. class Test {
public static void main(String[] args) {
String s1 = "Hello World";
String s2 = "Hello World";
if (s1 == s2)
System.out.println("The strings are the same");
else
System.out.println("The strings are different");
}
}
Answer:
The strings are the same.
Explanation:
Note that these two are string literals and not Strings. The compiler recognizes that the two string literals have the same value and it performs a simple optimization of only creating one String object. Thus s1 and s2 both refer to the same object and are therefore equal. The Java Language Specification requires this behavior. However, not all compilers get this right so in practice this behavior here is implementation dependent.
7. public class works{
public static int some;
static {
some = 100;
System.out.println("Inside static");
}
public static void main( String args[] ) {
new works();
System.out.println( "Inside main" );
}
works() {
System.out.println( "some = " + some );
}
}
Answer:
Inside static
some = 100
Inside main
Explanation:
Static blocks are executed before the invocation of main(). So at first the ―Inside static‖ is printed. After that the main function is called. It creates the object of the same type. So it leads to the printing of ‗some = 100‘. Finally the println inside the main() is executed to print ‗Inside main‘.
8. public class func{
int g(){
System.out.println("inside g");
int h(){
System.out.println("inside h");
return 1;
}
return 0;
}
public static void main(String[] args){
int c;
c=g();
}
Answer:
error : ";" expected at - int h()
Explanation:
Java doesn‘t allow function declared within a function declaration (nested functions). Hence the error.
9. When an exceptional condition causes an exception to be thrown, that exception is an object derived, either directly, or indirectly from the class Exception: True or False?
Answer:
False.
Explanation:
When an exceptional condition causes an exception to be thrown, that exception is an object derived, either directly, or indirectly from the class Throwable
10. class Test {
public static void main(String[] args) {
Button b;
b.setText("Hello");
}
}
Answer:
Runtime Error : NullPointerException
Explanation:
A NullPointerException is thrown when the system tries to access a object that points to a null value (objects are initalised to null).
This code tries to call setText() on ‗b‘. ‗b‘ does not refrence any object, so the exception is thrown. You must allocate space for the reference to point to an object like this:
Button b = new Button("hello");
// Or
Button b;
b = new Button();
b.setText("hello");
This creates a reference (‗b‘) of type Button, then asssigns it to a new instance of Button (new Button("hello")).
11. class Test {
void Test() {
System.out.println("Testing") ;
}
public static void main(String argv[]) {
Test ex = new Test() ;
}
}
Answer:
Compiler Error : ‗void‘ before Test()
Explanation:
Constructor doesn‘t have any return type; so even void shouldn't be specified as return type.
12. class Test {
int some=10 ;
void Test() {
this(some++) ;
}
void Test(int i) {
System.out.println(some);
}
public static void main( String argv[] ) {
new Test();
}
}
Answer:
Compiler Error : Cannot use ‗this‘ inside the constructor
Explanation:
‗this‘ is a special one that it refers to the same object. But ‗this‘ can be used only after creation of the object. It can‘t be used within a constructor. This leads to the issue of the error.
16. class Test {
public int some;
public static void main(String argv[]) {
int i = new Test().some;
System.out.println(i) ;
}
}
Answer:
0
Explanation:
All member variables are initialised during creation of the object. In the statement:
int i = new Test().some;
a new object of type ‗Test‘ is created and the value of member ‗j‘ in that object is referenced (the object created is not assigned to any reference) unig the ‗.‘ (dot) operator.
13. What does this code do?
int f = 1+ (int)(Math.random()*6);
This code always assigns an integer to variable f in the range between 1 and 6.
14. All programs can be written in terms of three types of control structures: What are those three?
Sequence,selection and repetition.
15. Is !(x=y) in Java ?
In the case that x and y are of float or double, the value of x or y could be NaN and the results would be different in that case.
16. What are peer "classes"?
Peer classes exist mainly for the convenience of the people who wrote the Java environment. They help in translating between the AWT user interface and the native (Windows, OpenWindows, Mac etc.) interfaces. Unless you're porting Java to a new platform you shouldn't have to use them.
17. What are concrete classes?
The classes from which objects are instantiated are called concrete classes (as opposed to abstract classes from which objects cannot be created).
18. Which methods in Java are implcitly treated as final methods?
Methods that are declared static and that are declared as private.
19. Java's finally block provides a mechanism that allows your method to clean up after itself regardless of what happens within the try block. True or False?
True.
20. Explain why you should place exception handlers furthermost from the root of the exception hierarchy tree first in the list of exception handlers.
An exception hander designed to handle a specialized "leaf" object may be preempted by another handler whose exception object type is closer to the root of the exception hierarchy tree if the second exception handler appears earlier in the list of exception handlers.
21. What method of which class would you use to extract the message from an exception object?
The getMessage() method of the Throwable class.
22. What are"deprecated APIs"?
A deprecated API is a object or method that is not recommended to be used and is an indication that it may be removed from the API list in future. The programs that use such APIs still work fine but not recommended to be used for this reason.


Reblog this post [with Zemanta]