Top Banner
2 Marks and 16 Marks UNIT-I PART-A 1.What is a class? A class is a blueprint, or prototype, that defines the variables and the methods common to all objects of a certain kind. 2.What is a object? An object is a software bundle of variables and related methods.An instance of a class depicting the state and behavior at that particular time in real world. 3.What is a method? Encapsulation of a functionality which can be called to perform specific tasks. 4.What is encapsulation? Explain with an example. Encapsulation is the term given to the process of hiding the implementation details of the object. Once an object is encapsulated, its implementation details are not immediately accessible any more. Instead they are packaged and are only indirectly accessible via the interface of the object 5.What is inheritance? Explain with an example. Inheritance in object oriented programming means that a class of objects can inherit properties and methods from another class of objects. 6.What is polymorphism? Explain with an example. In object-oriented programming, polymorphism refers to a programming language\'s ability to process objects differently depending
42
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: IT2301 Java

2 Marks and 16 Marks

UNIT-I

PART-A

  1.What is a class?

A class is a blueprint, or prototype, that defines the variables and the methods common to all objects of a certain kind.

  2.What is a object?

An object is a software bundle of variables and related methods.An instance of a class depicting the state and behavior at that particular time in real world.

  3.What is a method?

Encapsulation of a functionality which can be called to perform specific tasks.

  4.What is encapsulation? Explain with an example.

Encapsulation is the term given to the process of hiding the implementation details of the object. Once an object is encapsulated, its implementation details are not immediately accessible any more. Instead they are packaged and are only indirectly accessible via the interface of the object

  5.What is inheritance? Explain with an example.

Inheritance in object oriented programming means that a class of objects can inherit properties and methods from another class of objects.

  6.What is polymorphism? Explain with an example.

    In object-oriented programming, polymorphism refers to a programming language\'s ability to process objects differently depending on their data type or class. More specifically, it is the ability to redefine methods for derived classes. For example, given a base class shape, polymorphism enables the programmer to define different area methods for any number of derived classes, such as circles, rectangles and triangles. No matter what shape an object is, applying the area method to it will return the correct results. Polymorphism is considered to be a requirement of any true object-oriented programming language

  7.Is multiple inheritance allowed in Java?

      No, multiple inheritance is not allowed in Java.

Page 2: IT2301 Java

  8.What is JVM?

The Java interpreter along with the runtime environment required to run the Java application in called as Java virtual machine(JVM)

  9.What are the different types of modifiers?

There are access modifiers and there are other identifiers. Access modifiers are public, protected and private. Other are final and static.

10.What are the access modifiers in Java?

There are 3 access modifiers. Public, protected and private, and the default one if no identifier is specified is called friendly, but programmer cannot specify the friendly identifier explicitly.

11.What is a wrapper class?

They are classes that wrap a primitive data type so it can be used as a object

12.What is a static variable and static method? What\'s the difference between two?

The modifier static can be used with a variable and method. When declared as static variable, there is only one variable no matter how instances are created, this variable is initialized when the class is loaded. Static method do not need a class to be instantiated to be called, also a non-static method cannot be called from static method.

13.What is garbage collection?

Garbage Collection is a thread that runs to reclaim the memory by destroying the objects that cannot be referenced anymore.

14.What is abstract class?

Abstract class is a class that needs to be extended and its methods implemented, a class has to be declared abstract if it has one or more abstract methods.

15.What is meant by final class, methods and variables?

This modifier can be applied to class, method and variable. When declared as final class the class cannot be extended. When declared as final variable, its value cannot be changed if is primitive value, if it is a reference to the object it will always refer to the same object, internal attributes of the object can be changed.

16.What is interface?

Page 3: IT2301 Java

 Interface is a contact that can be implemented by a class , it has method that need implementation.

17.What is method overloading?

Overloading is declaring multiple methods with the same name, but with different argument list.

18.What is singleton class?

Singleton class means that any given time only one instance of the class is present, in one JVM.

20.What is the difference between an array and a vector?

Number of elements in an array are fixed at the construction time, whereas the number of elements in vector can grow dynamically.

21.What is a constructor?

In Java, the class designer can guarantee initialization of every object by providing a special method called a constructor. If a class has a constructor, Java automatically calls that constructor when an object is created, before users can even get their hands on it. So initialization is guaranteed.

22.What is casting?

Conversion of one type of data to another when appropriate. Casting makes explicitly converting of data.

1. What is the difference between final, finally and finalize?

The modifier final is used on class variable and methods to specify certain behaviors explained above. And finally is used as one of the loop in the try catch blocks, It is used to hold code that needs to be executed whether or not the exception occurs in the try catch block. Java provides a method called finalize( ) that can be defined in the class. When the garbage collector is ready to release the storage ed for your object, it will first call finalize( ), and only on the next garbage-collection pass will it reclaim the objects memory. So finalize( ), gives you the ability to perform some important cleanup at the time of garbage collection.

24.What is meant by abstraction?      Abstraction defines the essential characteristics of an object that distinguish it from all other kinds of objects. Abstraction provides crisply-defined conceptual boundaries relative to the perspective of the viewer. Its the process of focussing on the essential

Page 4: IT2301 Java

characteristics of an object. Abstraction is one of the fundamental elements of the object model.

25.What is meant by Encapsulation?      Encapsulation is the process of compartmentalising the elements of an abtraction that defines the structure and behaviour. Encapsulation helps to separate the contractual interface of an abstraction and implementation.

26.What is meant by Inheritance?      Inheritance is a relationship among classes, wherein one class shares the structure or behaviour defined in another class. This is called Single Inheritance. If a class shares the structure or behaviour from multiple classes, then it is called Multiple Inheritance. Inheritance defines \"is-a\" hierarchy among classes in which one subclass inherits from one or more generalised superclasses.

27.What is meant by Polymorphism?      Polymorphism literally means taking more than one form. Polymorphism is a characteristic of being able to assign a different behavior or value in a subclass, to something that was declared in a parent class.

28.What is an Abstract Class?      Abstract class is a class that has no instances. An abstract class is written with the expectation that its concrete subclasses will add to its structure and behaviour, typically by implementing its abstract operations.

29. What is an Interface?      Interface is an outside view of a class or object which emphaizes its abstraction while hiding its structure and secrets of its behaviour.

 

PART-B1. Explain in detail about Java Buzzwords (or) Java features (or) characteristics.2. Explain in detail about Control Structures available in java.3. Explain method overloading with an example program4. Explain in detail about constructor overloading with an example5. Explain about String class, String constructor, and different String methods using

a program.6. Explain about StringBuffer class, StringBuffer constructor, and different

StringBuffer methods using a program.7. Explain in detail about explicitly invoking  garbage collector and finalize()

method?8. Explain method overloading and method overriding with give suitable example.

Page 5: IT2301 Java

9. Explain vectors and their types.10. Explain classes and objects of java classes.

 

UNIT-II

    PART-A1. What is are packages? A package is a collection of related classes and interfaces

providing access protection and namespace management. 2. What is a super class and how can you call a super class? When a class is

extended that is derived from another class there is a relationship is created, the parent class is referred to as the super class by the derived class that is the child. The derived class can make a call to the super class using the keyword super. If used in the constructor of the

3. What is meant by Binding?      Binding denotes association of a name with a class.

4. What is meant by static binding?      Static binding is a binding in which the class association is made during compile time. This is also called as Early binding.

5. What is meant by Dynamic binding?      Dynamic binding is a binding in which the class association is not made until the object is created at execution time. It is also called as Late binding.

6. 2) What do you think is the logic behind having a single base class for all classes?1. casting 2. Hierarchial and object oriented structure.

3) Why most of the Thread functionality is specified in Object Class? Basically for interthread communication.

4) What is the importance of == and equals() method with respect to String object? == is used to check whether the references are of the same object..equals() is used to check whether the contents of the objects are the same.But with respect to strings, object refernce with same content will refer to the same object.

String str1=\"Hello\";String str2=\"Hello\";

(str1==str2) and str1.equals(str2) both will be true.

Page 6: IT2301 Java

If you take the same example with Stringbuffer, the results would be different.Stringbuffer str1=\"Hello\";Stringbuffer str2=\"Hello\";

str1.equals(str2) will be true. str1==str2 will be false.

7.  Is String a Wrapper Class or not? No. String is not a Wrapper class.

8.  How will you find length of a String object? Using length() method of String class.

9.  How many objects are in the memory after the exection of following code segment? String str1 = \"ABC\";String str2 = \"XYZ\";String str1 = str1 + str2; There are 3 Objects.

10.  What is the difference between an object and object reference? An object is an instance of a class. Object reference is a pointer to the object. There can be many refernces to the same object.

11.  What will trim() method of String class do? trim() eliminate spaces from both the ends of a string.***

12.   What is the use of java.lang.Class class? The java.lang.Class class is used to represent the classes and interfaces that are loaded by a java program.

13.   What is the possible runtime exception thrown by substring() method?ArrayIndexOutOfBoundsException.

14.   What is the difference between String and Stringbuffer? Object\'s of String class is immutable and object\'s of Stringbuffer class is mutable moreover stringbuffer is faster in concatenation.

15.   What is the use of Math class? Math class provide methods for mathametical functions.

16.   Can you instantiate Math class? No. It cannot be instantited. The class is final and its constructor is private. But all the methods are static, so we can use them without instantiating the Math class.

17.   What will Math.abs() do? It simply returns the absolute value of the value supplied to the method, i.e. gives you the

Page 7: IT2301 Java

same value. If you supply negative value it simply removes the sign.

18.   What will Math.ceil() do? This method returns always double, which is not less than the supplied value. It returns next available whole number

19.  What will Math.floor() do? This method returns always double, which is not greater than the supplied value.

20.   What will Math.min() do? The min() method returns smaller value out of the supplied values.

21.  What will Math.random() do? The random() method returns random number between 0.0 and 1.0. It always returns double.

22.  How to define an Interface? In Java Interface defines the methods but does not implement them. Interface can include constants. A class that implements the interfaces is bound to implement all the methods defined in Interface.Emaple of Interface:

public interface sampleInterface {    public void functionOne();

    public long CONSTANT_ONE = 1000; }

1. Explain the Inheritance principle. Inheritance is the process by which one object acquires the properties of another object.  

24.Explain the different forms of Polymorphism.

 From a practical programming viewpoint, polymorphism exists in three distinct forms in Java:

1.   o Method overloading o Method overriding through inheritance o Method overriding through the Java interface \\

25. What are Access Specifiers available in Java?Access specifiers are keywords that determines the type of access to the member of a class. These are:

Page 8: IT2301 Java

1.   o Public o Protected o Private o Defaults \\

 

26.How is it possible 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 i.e. present in the same memory location. It is possible for two String objects to have the same value, but located in different areas of memory.

== compares references while .equals compares contents. The method public boolean equals(Object obj) is provided by the Object class and can be overridden. The default implementation returns true only if the object is compared with itself, which is equivalent to the equality operator == being used to compare aliases to the object. String, BitSet, Date, and File override the equals() method. For two String objects, value equality means that they contain the same character sequence. For the Wrapper classes, value equality means that the primitive values are equal.

 public class EqualsTest {                public static void main(String[] args) {                                String s1 = “abc”;                               String s2 = s1;                               String s5 = “abc”;                               String s3 = new String(”abc”);                               String s4 = new String(”abc”);                               System.out.println(”== comparison : ” + (s1 == s5));                               System.out.println(”== comparison : ” + (s1 == s2));                               System.out.println(”Using equals method : ” + s1.equals(s2));                               System.out.println(”== comparison : ” + s3 == s4);                               System.out.println(”Using equals method : ” + s3.equals(s4));               }}

Output== comparison : true== comparison : trueUsing equals method : true

Page 9: IT2301 Java

falseUsing equals method : true

 

PART-B

1. How is interface used to support multiple inheritance? Explain with a program.2. Describe the various levels of access protection available in packages and their

implications with an example program.3. Explain in detail about creating and accessing packages with an example program.4. Explain ‘Dynamic method dispatch’ with one example program.5.  Describe Method overriding. Explain it with an example.6. Write short notes on:

i) Upcastingii) Downcasting

7. 7.     Explain in detail about different types of Inheritance with an example program. Compare and contrast Java and C++.

UNIT-III

PART-A

1. 1.      What are different types of inner classes?

Member classes - Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables. This means a public member class acts similarly to a nested top-level class. The primary difference between member classes and nested top-level classes is that member classes have access to the specific instance of the enclosing class.

Local classes - Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement amore publicly available interface.Because local classes are not members, the modifiers public, protected, private, and static are not usable.

Anonymous classes - Anonymous inner classes extend local inner classes one level further. As anonymous classes have no name, you cannot provide a constructor.

2. What is the common usage of serialization?

Whenever an object is to be sent over the network, objects need to be serialized. Moreover if the state of an object is to be saved, objects need to be serilazed.

Page 10: IT2301 Java

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

4.What is reflection?

The ability to examine and manipulate a Java class from within itself may not sound like very much, but in other programming languages this feature simply doesn\'t exist. For example, there is no way in a Pascal, C, or C++ program to obtain information about the functions defined within that program.

5.Give an example for reflection.

import java.lang.reflect.*;    public class DumpMethods {      public static void main(String args[])      {         try {            Class c = Class.forName(args[0]);            Method m[] = c.getDeclaredMethods();            for (int i = 0; i < m.length; i++)            System.out.println(m[i].toString());         }         catch (Throwable e) {            System.err.println(e);         }      }   }

 

6.When should I use abstract classes rather than interfaces? 

Abstract classes are often used to provide methods that will be common to a range of similar subclasses, to avoid duplicating the same code in each case. Each subclass adds its own features on top of the common abstract methods.

7.Can you give an example of multiple inheritance with interfaces?  

To illustrate multiple inheritance, consider a bat, which is a mammal that flies. We might have two interfaces: Mammal, which has a method suckleInfant(Mammal), and Flyer, which has a method fly(). These types would be declared in interfaces

8.Can we create a Java class inside an interface?  

Page 11: IT2301 Java

 Yes, classes can be declared inside interfaces. This technique is sometimes used where the class is a constant type, return value or method argument in the interface. When a class is closely associated with the use of an interface it is convenient to declare it in the same compilation unit. This proximity also helps ensure that implementation changes to either are mutually compatible.

A class defined inside an interface is implicitly public static and operates as a top level class. The static modifier does not have the same effect on a nested class as it does with class variables and methods. The example below shows the definition of a StoreProcessor interface with nested StorageUnit class which is used in the two interface methods.

9.Can an interface extend an abstract class?  

 In Java an interface cannot extend an abstract class. An interface may only extend a super-interface. And an abstract class may implement an interface. It may help to think of interfaces and classes as separate lines of inheritance that only come together when a class implements an interface, the relationship cannot be reversed.

10.Can we create an object for an interface?

Yes, the most common scenario is to create an object implementation for an interface, although they can be used as a pure reference type. Interfaces cannot be instantiated in their own right, so it is usual to write a class that implements the interface and fulfils the methods defined in it.

public class Concrete implements ExampleInterface {   ...}  

11.What is a marker interface?  

 Marker interfaces are those which do not declare any required methods, but signify their compatibility with certain operations. The java.io.Serializable interface is a typical marker interface. It does not contain any methods, but classes must implement this interface in order to be serialized and de-serialized.

 12.What are different types of cloning in Java?

Ans) Java supports two type of cloning: - Deep and shallow cloning. By default shallow copy is used in Java. Object class has a method clone() which does shallow cloning.

 13.What is Shallow copy?

Page 12: IT2301 Java

    In shallow copy the object is copied without its contained objects.Shallow clone only copies the top level structure of the object not the lower levels.It is an exact bit copy of all the attributes.      

Figure 1: Original java object obj

The shallow copy is done for obj and new object obj1 is created but contained objects of obj are not copied.

Figure 2: Shallow copy object obj1

It can be seen that no new objects are created for obj1 and it is referring to the same old contained objects. If either of the containedObj contain any other object no new reference is created

14.What is difference between deep and shallow cloning?

   The differences are as follows:

Consider the class:

public class MyData{String id;Map myData;}The shallow copying of this object will have new id object and values as “” but will point to the myData of the original object. So a change in myData by either original or cloned object will be reflected in other also. But in deep copying there will be new id object and also new myData object and independent of original object but with same values.

Shallow copying is default cloning in Java which can be achieved using clone() method of Object class. For deep copying some extra logic need to be provided.

15.What are the characteristics of a shallow clone?

 If we do a = clone(b)1) Then b.equals(a)2) No method of a can modify the value of b.

16.What are the disadvantages of deep cloning?

 Disadvantages of using Serialization to achieve deep cloning –

Serialization is more expensive than using object.clone().

Page 13: IT2301 Java

Not all objects are serializable. Serialization is not simple to implement for deep cloned object.

17.Why are streams used in Java?  

 In Java streams are used to process input and output data as a sequence of bytes, which does not assume a specific character content or encoding. Byte content can be read from network sources, files and other sources, and bytes copied between multiple inputs and outputs.

Streams types can be sub-classed to add filtering, to mark a point in the stream and re-read those bytes, or to skip a number of bytes. Streams also enable serlializable objects to stored and re-constructed using ObjectInputStream and ObjectOutputStream types.

18.What does \"broken pipe\" mean?  

 A pipe is an input/output link between two programs, commonly where you use the output from one program as the input for another program. A broken pipe means that the linkage between the output and input is interrupted, the reasons vary. For example, the feeder program may throw an error and terminate unexpectedly, intermediate source or output files may not be created successfully, or key resources become unavailable during the process. You may also get problems with the amount of swap file storage or overall memory usage approaches its limits.

19.What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?

The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented.

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

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

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

Page 14: IT2301 Java

23.What is a transient variable?

A transient variable is a variable that may not be serialized. If you don\'t want some field to be serialized, you can mark that field transient or static.

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

 

PART-B

1. Explain the InputStream class hierarchy with an example program.2. Explain the OutputStream class hierarchy with an example program.3. Explain the Reader Stream class hierarchy with an example program4. Explain the Writer Stream class hierarchy with an example program.5. What are the virtual functions? Explain their needs using a suitable example.What

are the rules6. associated with virtual functions? What are the different forms of inheritance

supported in c++? Discuss on the visibility of base7. class members in privately and publicly inherited classes.8. What are abstract classes? Give an example (with the program) to illustrate the

use of abstract9. classes.

10.  Explain about Code Reuse with program.

 

UNIT-IV

PART-A

1.      Which containers use a FlowLayout as their default layout?

The Panel and Applet classes use the FlowLayout as their default layout.

4. What are the two types of Exceptions?

1.    Checked Exceptions and Unchecked Exceptions.

5.What is the base class of all exceptions?    

Page 15: IT2301 Java

java.lang.Throwable

6.What is the difference between Exception and Error in java?

1.      Exception and Error are the subclasses of the Throwable class. Exception class is used for exceptional conditions that user program should catch. Error defines exceptions that are not excepted to be caught by the user program. Example is Stack Overflow.

 

1. What is the difference between throw and throws?      throw is used to explicitly raise a exception within the program, the statement would be throw new Exception(); throws clause is used to indicate the exceptions that are not handled by the method. It must specify this behavior so the callers of the method can guard against the exceptions. throws is specified in the method signature. If multiple exceptions are not handled, then they are separated by a comma. the statement would be as follows: public void doSomething() throws IOException,MyException{}

 

1. Differentiate between Checked Exceptions and Unchecked Exceptions?      Checked Exceptions are those exceptions which should be explicitly handled by the calling method. Unhandled checked exceptions results in compilation error.

Unchecked Exceptions are those which occur at runtime and need not be explicitly handled. RuntimeException and it\'s subclasses, Error and it\'s subclasses fall under unchecked exceptions.

  7.What are User defined Exceptions?

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

  8.What is the importance of finally block in exception handling?

1.      Finally block will be executed whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement match the exception. Any time a method is about to return to the caller from inside try/catch block, via an uncaught exception or an explicit return statement, the finally block will be executed. Finally is used to free up resources like database connections, IO handles, etc.

  9.Can a catch block exist without a try block?

Page 16: IT2301 Java

1.      No. A catch block should always go with a try block.

 10.  Can a finally block exist with a try block but without a catch?      Yes. The following are the combinations try/catch or try/catch/finally or try/finally.

 

11.   What will happen to the Exception object after exception handling?      Exception object will be garbage collected.

 

12.  How does finally block differ from finalize() method?      Finally block will be executed whether or not an exception is thrown. So it is used to free resoources. finalize() is a protected method in the Object class which is called by the JVM just before an object is garbage collected.

 

13.  What are the constraints imposed by overriding on exception handling?      An overriding method in a subclass may only throw exceptions declared in the parent class or children of the exceptions declared in the parent class.\\

 

14.   What is an Exception?

An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error.

 

15. What is a Java Exception?

A Java exception is an object that describes an exceptional condition i.e., an error condition that has occurred in a piece of code. When this type of condition arises, an object representing that exception is created and thrown in the method that caused the error by the Java Runtime. That method may choose to handle the exception itself, or pass it on. Either way, at some point, the exception is caught and processed.

16. What are the different ways to generate and Exception?

There are two different ways to generate an Exception.

Page 17: IT2301 Java

1. Exceptions can be generated by the Java run-time system.

Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java language or the constraints of the Java execution environment.

1. Exceptions can be manually generated by your code.

Manually generated exceptions are typically used to report some error condition to the caller of a method.

17.Where does Exception stand in the Java tree hierarchy?

java.lang.Object java.lang.Throwable java.lang.Exception java.lang.Error

18. Is it compulsory to use the finally block?

It is always a good practice to use the finally block. The reason for using the finally block is, any unreleased resources can be released and the memory can be freed. For example while closing a connection object an exception has occurred. In finally block we can close that object. Coming to the question, you can omit the finally block when there is a catch block associated with that try block. A try block should have at least a catch or a finally block.

 

19. What is a throw in an Exception block?

“throw” is used to manually throw an exception (object) of type Throwable class or a subclass of Throwable. Simple types, such as int or char, as well as non-Throwable classes, such as String and Object, cannot be used as exceptions. The flow of execution stops immediately after the throw statement; any subsequent statements are not executed.

                throw ThrowableInstance;                ThrowableInstance must be an object of type Throwable or a subclass of Throwable.                throw new NullPointerException(\"thrownException\");

 

Page 18: IT2301 Java

20.Why do I get a run-time Error when I add components to a JFrame/JDialog/JInternalFrame/JWindow?

In Swing, top-level windows (such as JFrame or JDialog) do nothave components added directly to the window. Instead, add them to the contentpane like this:

        myWindow.getContentPane().add(component)

21.Where are the scroll bars on my JList (or JTextArea)?

Swing components don’t implement scrolling directly. Scrolling has instead been encapsulated in the JScrollPane class. To get scrollbars on a component, wrap it in a JScrollPane. Instead of:

    panel.add(component)

use

    panel.add(new JScrollPane(component));

Components that implement the Scrollable interface will interact with JScrollPane to configure the scrolling behavior. Components that don’t implement Scrollable will get the default behavior supplied by JScrollPane.

 22.How can I save space in my screens?

Look at JSplitPane, JTabbedPane, JLayeredPane, and JScrollPane. They all provide ways to let other components share space.

23.What’s the easiest way to create a dialog?

Use a JOptionPane. It builds in features useful in simple dialogs.

24.How can I prevent a window from closing?

By default, a window is hidden (but not disposed of) when it is closed. This happens after all window listeners have executed. To prevent the window from closing unless the program closes it, use this code:

        frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

 25.Can I mix Swing and AWT components?

“Yes, but…” You can mix these components, and it’s documented at http://java.sun.com/products/jfc/tsc/swingdoc-archive/mixing.html. However, if it’s at all

Page 19: IT2301 Java

possible, you’ll find it much less problematic to converteverything to Swing. (The problem is that AWT components are heavyweight, while Swing components are lightweight, and heavyweight components always appear above lightweight components; this causes difficulty for things like tabbed panes, internal frames, popup menus, etc.)

26. How do I use internal frames?

Sun has a couple of articles explaining JInternalFrame and JDesktopPane in the Swing Connection:

“Creating MDI Programs with Swing” “Internalizable/Externalizable Frames”

27.How do I use an image as the background for a JPanel?

Override the JPanel’s paintComponent() method and use it to paint the image (which you should store as an ImageIcon).  For example:

public void paintComponent(java.awt.Graphics g){  super.paintComponent(g);  int width = getWidth();  int height = getHeight();  java.awt.Color oldColor = g.getColor();  if (opaque)  {    g.setColor(getBackground());    g.fillRect(0, 0, width, height);  }  if (theImage != null)  {    g.drawImage(theImage.getImage(), 0, 0, this);  }  g.setColor(oldColor);}

28. How can I capture KeyEvents for the Tab key?

Override isManagingFocus() to return true, then all key events should be sent to your JComponent. <Christian Kaufhold>

29. How can I make a JComboBox textfield empty?

Call theComboBox.setSelectedItem(null); <Per Cederberg>

30.Why is my JList/JTree component sized improperly when I add/remove items from the Model?

Page 20: IT2301 Java

While there could be many reasons for this behavior, one possibility is that you have a JScrollPane in a GridBagLayout without a minimum size set. Try setting a reasonable value and see if your problem disappears.<Brian Sletten>

 

31.Can I save my UI designs as XML documents?

This should be added in JDK 1.4. There’s an article about this new support on The Swing Connection. Using XML serialization is much more compact than using the old Object serialization, but it isn’t appropriate for serializing everything.

 32.How do I change fonts/colors/etc. in my JOptionPane?

The easiest way is to use the JOptionPane constructor where you supply the components that are used to build the JOptionPane. Since you create the components, you can do whatever you want to them before you pass them to the JOptionPane. The constructors to use are any of the ones that take Objects. See the JOptionPane JavaDoc for details on what kinds of Objects you can pass to these constructors.

 

33.How can the Checkbox class be used to create a radio button?

By associating Checkbox objects with a CheckboxGroup

 

34.Name three subclasses of the Component class?

Box.Filler, Button, Canvas, Checkbox, Choice, Container, Label, List, Scrollbar, or TextComponent

 

35.What is the relationship between an event-listener interface and an event adapterclass?

An event-listener interface defines the methods that must be implemented by an event handler for aparticular kind of event. An event adapter provides a defaultimplementation of an event listener interface.

 

36.What interface is extended by AWT event listeners?

Page 21: IT2301 Java

All AWT event listeners extend the java.util.EventListener interface

 

37. What is the difference between a Scrollbar and a ScrollPane?

A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. AScrollPane handles itsown events and performs its own scrolling.

 

38. What is layout manager ? How does it work?

A layout manager is an object that positions and resizes the components in a Container according to some algorithm; for example, the FlowLayout layout manager lays outcomponents from left to right until it runs out of room and then continues laying out components below that row.

39. Difference between Swing and Awt?

AWT are heavy-weight componenets. Swings are light-weight components. Hence swing works faster than AWT.

 

40.Can applets communicate with each other?

At this point in time applets may communicate with other applets running in the same virtual machine. If the applets are of the same class, they can communicate via shared static variables. If the applets are of different classes, then each will need a reference to the same class with static variables. In any case the basic idea is to pass the information back and forth through a static variable.

  PART-B

1. Explain in detail about Applet Life cycle.2. Write a program to demonstrate the Life cycle of an applet. 3. Write a program to perform the following operations by using applet.

(i) Draw a Line, Rectangle(ii) Draw a oval and fill it(iii) Draw a polygon (iv) Set the background and foreground color.

4.  Explain in detail about Event handling mechanism with an example.5. Describe about ‘Key Event’ and ‘Mouse Event’.6. Explain about Template and its types with example.7. Discuss about Streams and stream classes

Page 22: IT2301 Java

8. Write notes on Formatted and Unformatted Console I/O Operations.9. Explain about File Pointers and Manipulations with example. Discuss about

manipulators and file streams with Program.10. Write on Details about File modes and File I/O.

UNIT-VPART-A

1. What invokes a thread\'s run() method? 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.

2. What is the GregorianCalendar class? The GregorianCalendar provides support for traditional Western calendars.

1. What is the SimpleTimeZone class? The SimpleTimeZone class provides support for a Gregorian calendar.

3. What is the Properties class? 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.

1. What is the purpose of the Runtime class? The purpose of the Runtime class is to provide access to the Java runtime system.

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

4. What is the purpose of the finally clause of a try-catch-finally statement? The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught. For example,

i.  try { //some statements } catch { // statements when exception is cought } finally { //statements executed whether exception occurs or not }

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

2. What must a class do to implement an interface? It must provide all of the methods in the interface and identify the interface in its implements clause.

Page 23: IT2301 Java

1. What is meant by a Thread? Thread is defined as an instantiated parallel process of a given program.

3. What is multi-threading? Multi-threading as the name suggest is the scenario where more than one threads are running.

4. What are two ways of creating a thread? Which is the best way and why? Two ways of creating threads are, one can extend from the Java.lang.Thread and can implement the rum method or the run method of a different class can be called which implements the interface Runnable, and the then implement the run() method. The latter one is mostly used as first due to Java rule of only one class inheritance, with implementing the Runnable interface that problem is sorted out.

1. What is deadlock? Deadlock is a situation when two threads are waiting on each other to release a resource. Each thread waiting for a resource which is held by the other waiting thread. In Java, this resource is usually the object lock obtained by the synchronized keyword.

5. What are the three types of priority? MAX_PRIORITY which is 10, MIN_PRIORITY which is 1, NORM_PRIORITY which is 5.

10.  What is the use of synchronizations? Every object has a lock, when a synchronized keyword is used on a piece of code the, lock must be obtained by the thread first to execute that code, other threads will not be allowed to execute that piece of code till this lock is released.

11.  What are synchronized methods and synchronized statements? Synchronized methods are methods that are used to control access to an object. For example, 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.

12.  What are different ways in which a thread can enter the waiting state? A thread can enter the waiting state by invoking its sleep() method, blocking on I/O, unsuccessfully attempting to acquire an object\'s lock, or invoking an object\'s wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method.

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

1. What\'s new with the stop(), suspend() and resume() methods in new JDK 1.2? The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.

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

Page 24: IT2301 Java

15.  What method is used to specify a container\'s layout? The setLayout() method is used to specify a container\'s layout. For example, setLayout(new FlowLayout()); will be set the layout as FlowLayout.

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

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

18.  What is Runnable interface ? Are there any other ways to make a java program as multithred java program?    

There are two ways to create new kinds of threads:

 

1. Define a new class that extends the Thread class2. Define a new class that implements the Runnable interface, and pass an object of

that class to a Thread\'s constructor. 3. An advantage of the second approach is that the new class can be a subclass of

any class, not just of the Thread class.

Here is a very simple example just to illustrate how to use the second approach to creating threads:

 

class myThread implements Runnable {

public void run() {

Page 25: IT2301 Java

System.out.println(\"I\'m running!\");

}

}

 

public class tstRunnable {

myThread my1 = new myThread();

myThread my2 = new myThread();

new Thread(my1).start();

new Thread(my2).start();

}

 

 

The Runnable interface has only one method:

public void run();

Thus, every class (thread) implements the Runnable interface, has to provide logic for run() method  

 

 

 

 

  19.How can i tell what state a thread is in ?

 

Prior to Java 5, isAlive() was commonly used to test a threads state. If isAlive() returned false the thread was either new or terminated but there was simply no way to differentiate between the two.

Page 26: IT2301 Java

 

Starting with the release of Tiger (Java 5) you can now get what state a thread is in by using the getState() method which returns an Enum of Thread.States. A thread can only be in one of the following states at a given point in time.

 

NEW  A Fresh thread that has not yet started to execute.

RUNNABLE A thread that is executing in the Java virtual machine.

BLOCKED A thread that is blocked waiting for a monitor lock.

WAITING A thread that is wating to be notified by another thread.

TIMED_WAITING A thread that is wating to be notified by another thread for a specific amount of time

TERMINATED A thread whos run method has ended.

 

The folowing code prints out all thread states.

 

public class ThreadStates{

public static void main(String[] args){

Thread t = new Thread();

Thread.State e = t.getState();

Thread.State[] ts = e.values();

for(int i = 0; i < ts.length; i++){

System.out.println(ts[i]);

}  

}

}      

Page 27: IT2301 Java

20. What methods java providing for Thread communications ? 

Java provides three methods that threads can use to communicate with each other: wait, notify, and notifyAll. These methods are defined for all Objects (not just Threads). The idea is that a method called by a thread may need to wait for some condition to be satisfied by another thread; in that case, it can call the wait method, which causes its thread to wait until another thread calls notify or notifyAll.     

 

21.What is the difference between notify and notify All methods ? 

A call to notify causes at most one thread waiting on the same object to be notified (i.e., the object that calls notify must be the same as the object that called wait). A call to notifyAll causes all threads waiting on the same object to be notified. If more than one thread is waiting on that object, there is no way to control which of them is notified by a call to notify (so it is often better to use notifyAll than notify).  

 

 

 

22.What is synchronized keyword? In what situations you will Use it? 

Synchronization is the act of serializing access to critical sections of code. We will use this keyword when we expect multiple threads to access/modify the same data. To understand synchronization we need to look into thread execution manner.

 

Threads may execute in a manner where their paths of execution are completely independent of each other. Neither thread depends upon the other for assistance. For example, one thread might execute a print job, while a second thread repaints a window. And then there are threads that require synchronization, the act of serializing access to critical sections of code, at various moments during their executions. For example, say that two threads need to send data packets over a single network connection. Each thread must be able to send its entire data packet before the other thread starts sending its data packet; otherwise, the data is scrambled. This scenario requires each thread to synchronize its access to the code that does the actual data-packet sending.

 

 

Page 28: IT2301 Java

If you feel a method is very critical for business that needs to be executed by only one thread at a time (to prevent data loss or corruption), then we need to use synchronized keyword.

 

EXAMPLE

 

Some real-world tasks are better modeled by a program that uses threads than by a normal, sequential program. For example, consider a bank whose accounts can be accessed and updated by any of a number of automatic teller machines (ATMs). Each ATM could be a separate thread, responding to deposit and withdrawal requests from different users simultaneously. Of course, it would be important to make sure that two users did not access the same account simultaneously. This is done in Java using synchronization, which can be applied to individual methods, or to sequences of statements.

 

One or more methods of a class can be declared to be synchronized. When a thread calls an object\'s synchronized method, the whole object is locked. This means that if another thread tries to call any synchronized method of the same object, the call will block until the lock is released (which happens when the original call finishes). In general, if the value of a field of an object can be changed, then all methods that read or write that field should be synchronized to prevent two threads from trying to write the field at the same time, and to prevent one thread from reading the field while another thread is in the process of writing it.

 

Here is an example of a BankAccount class that uses synchronized methods to ensure that deposits and withdrawals cannot be performed simultaneously, and to ensure that the account balance cannot be read while either a deposit or a withdrawal is in progress. (To keep the example simple, no check is done to ensure that a withdrawal does not lead to a negative balance.)

 

 

 

 

Page 29: IT2301 Java

public class BankAccount {

1. private double balance;

 

// constructor: set balance to given amount

public BankAccount( double initialDeposit ) {

balance = initialDeposit;

}

 

public synchronized double Balance( ) {

return balance;

}

 

public synchronized void Deposit( double deposit ) {

balance += deposit;

}

 

public synchronized void Withdraw( double withdrawal ) {

balance -= withdrawal;

}

 

}

 

Page 30: IT2301 Java

Note: that the BankAccount\'s constructor is not declared to be synchronized. That is because it can only be executed when the object is being created, and no other method can be called until that creation is finished.

 

There are cases where we need to synchronize a group of statements, we can do that using synchrozed statement.

 

 

Java Code Example

 

synchronized ( B ) {

if ( D > B.Balance() ) {

ReportInsuffucientFunds();

}

else {

B.Withdraw( D );

}

}

 

23.What happens when a thread cannot acquire a lock on an object?

If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquirean object\'s lock, it enters the waiting state until the lock becomesavailable.

 

 

24.What happens when a thread cannot acquire a lock on an object?

Page 31: IT2301 Java

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

 

25.What is an object\'s lock and which object\'s have locks?

An object\'s lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object onlyafter it has acquired theobject\'s lock. All objects and classes have locks. A class\'s lock is acquired on the class\'s Class object.

 

PART-B

1. Explain Exception Handling and Multiple catch statement2. Explain Multithreading programming with suitable example3. Explain method overloading and method overriding with give suitable example. 4. What are the differences between the accesses specifies private and protected? 5. What are base and derived classes? Write a program to use these classes.6. What are the different forms of inheritance? Explain with an example.7. What is class hierarchy? Explain how inheritance helps in building class

hierarchies.8. What is visibility mode? What are the different visibility modes supported by C+

+? 9. What are the differences between inheriting a class with public and private

visibility mode?

10.  What are virtual classes? Explain the need for virtual classes while building class.

11.  What are abstract classes? Explain the role of abstract class while building a class hierarchy.