Java Solved Qb

69
SCAD COLLEGE OF ENGINEERING & TECHNOLOGY DEPARTMENT OF INFORMATION TECHNOLOGY IT 51 JAVA PROGRAMMING III YEAR / V SEMESTER Solved Question Bank Prepared By, Prof.A.Kandasamy M.E., (Ph.D) Department of Information Technology

Transcript of Java Solved Qb

Page 1: Java Solved Qb

SCAD COLLEGE OF ENGINEERING & TECHNOLOGY

DEPARTMENT OF

INFORMATION TECHNOLOGY

IT 51

JAVA PROGRAMMING

III YEAR / V SEMESTER

Solved Question Bank

Prepared By,

Prof.A.Kandasamy M.E., (Ph.D)

Department of Information Technology

Page 2: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

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

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 3: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

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.

  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 arepublic, 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.

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 4: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

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?

 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.

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

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

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 5: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

21.What is casting?

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

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

23.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 characteristics of an object. Abstraction is one of the fundamental elements of the object model.

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

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

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

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 6: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

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

28. 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-B

1. Explain the traits of JAVA.

Hints:

Encapsulation

Inheritance

Polymorphism

Data Abstraction

Data Encapsulation

2. List the reasons to prefer JAVA language Hints:

portability

Durability

Scalability

Reliability

3.Explain in detail about Control Structures available in java.SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 7: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

Hints:

While(condition){

}

Do{

Statements

}while(condition)

For(initial value;condition;increment)

{statements}

If (condition) {statements} If (condition) {statements} else{statements}

Switch(choice)

{

Case 1:

Statements;

Break;

Case 2:

Statements;

Break;

Default:

Statements;

Break;

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 8: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

}

4.Explain method overloading with an example program

Hints:

In Java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different

The methods are said to be overloaded, and the process is referred to as method overloading. 

Method overloading is one of the ways that Java implements polymorphism.

class OverloadDemo { 

void test() { 

System.out.println("No parameters"); 

// Overload test for two integer parameters. 

void test(int a, int b) { 

System.out.println("a and b: " + a + " " + b); 

// overload test for a double parameter 

void test(double a) { 

System.out.println("Inside test(double) a: " + a); 

class Overload { 

public static void main(String args[]) { 

OverloadDemo ob = new OverloadDemo(); 

int i = 88; 

ob.test(); 

ob.test(10, 20); 

ob.test(i); // this will invoke test(double) 

ob.test(123.2); // this will invoke test(double) 

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 9: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

}

This program generates the following output:

No parameters 

a and b: 10 20 

Inside test(double) a: 88 

Inside test(double) a: 123.2

5.Explain in detail about constructor overloading with an example

Hints:

Constructors are used to assign initial values to instance variables of

the class.

A default constructor with no arguments will be called automatically

by the Java Virtual Machine (JVM).

Constructor is always called by new operator.

 Constructor are declared just like as we declare methods, except that

the constructor don't have any return type.

Constructor can be overloaded provided they should have different

arguments because JVM differentiates constructors on the basis of

arguments passed in the constructor.

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 10: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

Whenever we assign the name of the method same as  class name.

Remember this method should not have any return type. This is called

as constructor overloading. 

We have made one program on a constructor overloading, after going through it the concept of constructor overloading will get more clear.

6.Explain about String class, String constructor, and different String methods using a program.

Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.

The Java platform provides the String class to create and manipulate strings.

Creating Strings:

The most direct way to create a string is to write:

String greeting = "Hello world!";

Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case, "Hello world!'.

As with any other object, you can create String objects by using the new keyword and a constructor. The String class has eleven constructors that allow you to provide the initial value of the string using different sources, such as an array of characters:

public class StringDemo{ public static void main(String args[]){ char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'}; String helloString = new String(helloArray); System.out.println( helloString ); }

}

This would produce following result:

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 11: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

hello The String class is immutable, so that once it is created a String object

cannot be changed. If there is a necessity to make alot of modifications to Strings of characters then you should use String Buffer & String Builder Classes.

String Length:

Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object.

After the following two lines of code have been executed, len equals 17: public class StringDemo{ public static void main(String args[]){ String palindrome = "Dot saw I was Tod"; int len = palindrome.length(); System.out.println( "String Length is : " + len ); }

}

This would produce following result:

String Length is : 17

Concatenating Strings:

The String class includes a method for concatenating two strings:

string1.concat(string2);

This returns a new string that is string1 with string2 added to it at the end. You can also use the concat() method with string literals, as in:

"My name is ".concat("Zara");

Strings are more commonly concatenated with the + operator, as in:

"Hello," + " world" + "!"

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 12: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

which results in:

"Hello, world!"

Let us look at the following example:

public class StringDemo{ public static void main(String args[]){ String string1 = "saw I was "; System.out.println("Dot " + string1 + "Tod"); }

}This would produce following result:

Dot saw I was Tod

Creating Format Strings:

You have printf() and format() methods to print output with formatted numbers. The String class has an equivalent class method, format(), that returns a String object rather than a PrintStream object.

7.Explain about StringBuffer class, StringBuffer constructor, and different StringBuffer methods using a program.

Hints:

A string buffer implements a mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.

String buffers are safe for use by multiple threads. The methods are synchronized where necessary so that all the operations on any particular instance behave as if they occur in some serial order that is consistent with the order of the method calls made by each of the individual threads involved.

String buffers are used by the compiler to implement the binary string concatenation operator +. For example, the code:

x = "a" + 4 + "c"

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 13: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

is compiled to the equivalent of:

x = new StringBuffer().append("a").append(4).append("c") .toString()

which creates a new string buffer (initially empty), appends the string representation of each operand to the string buffer in turn, and then converts the contents of the string buffer to a string. Overall, this avoids creating many temporary strings.

The principal operations on a StringBuffer are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string buffer. The append method always adds these characters at the end of the buffer; the insert method adds the characters at a specified point.

For example, if z refers to a string buffer object whose current contents are "start", then the method call z.append("le") would cause the string buffer to contain "startle", whereas z.insert(4, "le") would alter the string buffer to contain "starlet".

In general, if sb refers to an instance of a StringBuffer, then sb.append(x) has the same effect as sb.insert(sb.length(), x).

8.Explain in detail about explicitly invoking  garbage collector and finalize() method?

Hints:

JAVAt handles deallocation for you automatically. The technique that

accomplishes this is called garbage collection.

It works like this: when no references to an object to an object exist,

that object is assumed to be no longer needed, and the memory

occupied by the object can be reclaimed.

There is no explicit need to destroy objects as in C++.

Garbage collection only occurs sporadically (if at all) during the

execution of your program. It will not occur simply because one or more

objects exist that are no longer used. 

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 14: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

The finalize () Method

 

Sometimes an object will need to perform some action when it is

destroyed. For example, if an object is holding some non-java

resource such as a file handle or window character font, then you

might want to make sure these resources are freed before an

object is destroyed.

By using finalization, you can define specific actions that will occur

when an object is just about to be reclaimed by the garbage

collector.

        The finalize() method has this general form:

 

            protected void finalize()

            {

            // finalization code here

            }

 

9.Explain method overloading and method overriding with give suitable example.

polymorphism translates from Greek as many forms ( poly - many morph - forms)

in OOP's it refers to method overloading is the primary way polymorphism is implemented in JavaOverloading methods

appear in the same class or a subclass have the same name but, have different parameter lists, and, can have different return types the actual method called depends on the object being passed to the

method

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 15: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

Java uses late-binding to support polymorphism; which means the decision as to which of the many methods should be used is deferred until runtime

Overriding methods late-binding also supports overriding Appear in subclasses have the same name as a superclass method have the same parameter list as a superclass method have the same return type as as a superclass method the access modifier for the overriding method may not be more

restrictive than the access modifier of the superclass method if the superclass method is public, the overriding method must

be public if the superclass method is protected, the overriding method may

be protected or public if the superclass method is package, the overriding method may

e packagage, protected, orpublic if the superclass methods is private, it is not inherited and

overriding is not an issue

10.  Explain classes and objects of java classes. 

 Class : 

Whatever we can see in this world all the things are a object. And all the objects are categorized in a special group.

That group is termed as a class. All the objects are direct interacted with its class that mean almost all the properties of the object should be matched with it's own class.

Object is the feature of a class which is used for the working on the particular properties of the class or its group. We can understand about the class and object like this : we are all the body are different - different objects of the human being class. That means all the properties of a proper person relates to the human being. Class has many other features like creation and implementation of the object, Inheritance etc.

Object : 

Objects are the basic run time entity or in other words object is a instance of a class . An object is a software bundle of variables and related methods of the special class. A object implements its behavior

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 16: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

with methods of it's classes. A method is a function (subroutine) associated with an object. 

UNIT II

PART-A

1. What 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. What do you think is the logic behind having a single base class for all classes?1. casting 2. Hierarchial and object oriented structure.

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

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

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 17: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

will refer to the same object.

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

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

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. 

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

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

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

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

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

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

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

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 18: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

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

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

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

19.   What will Math.abs() do? It simply returns the absolute value of the value supplied to the method, i.e. gives you the same value. If you supply negative value it simply removes the sign. 

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

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

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

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

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

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 19: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

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

26.Explain the different forms of Polymorphism.

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

 

o Method overloadingo Method overriding through inheritance

o Method overriding through the Java interface \\

27. 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:

1.  o Public

o Protected

o Private

o Defaults \\

 

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

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 20: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

objects, value equality means that they contain the same character sequence. For the Wrapper classes, value equality means that the primitive values are equal.

PART-B

1. How is interface used to support multiple inheritance? Explain with a program.

Hints:

Within the Java programming language, an interface is a type, just as a class is a type. Like a class, an interface defines methods. Unlike a class, an interface never implements methods; instead, classes that implement the interface implement the methods defined by the interface. A class can implement multiple interfaces.

We use an interface to define a protocol of behavior that can be implemented by any class anywhere in the class hierarchy. Interfaces are useful for the following:

Capturing similarities among unrelated classes without artificially forcing a class relationship

Declaring methods that one or more classes are expected to implement

Revealing an object's programming interface without revealing its class Modelling multiple inheritance, a feature that some object-oriented

languages support that allows a class to have more than one superclass

2.Explain in detail about creating and accessing packages with an example program.

Hints:

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 21: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

Usually a Java application is built by many developers and it is common that third party modules/classes are integrated. The end product can easily contain hundreds of classes. Class name collision is likely to happen. To avoid this a Java class can be put in a "name space". This "name space" in Java is called the package.

When we want to reference a Java class that is defined outside of the current package name space, we have to specify which package name space that class is in. So we could reference that class with something like com.yourcompany.yourapplication.yourmodule.YourClass . To avoid having to type in the package name each time when we want to reference an outside class, we can declare which package the class belongs to by using the import Java keyword at the top of the file. 

Then we can refer to that class by just using the class

name YourClass .

In rare cases it can happen that you need to reference two classes

having the same name in different packages. In those cases, you can

not use the import keyword for both classes. One of them needs to be

referenced by typing in the whole package name. 

3.Explain ‘Dynamic method dispatch’ with one example program.

Hints:

In computer science  dynamic dispatch (also known as dynamic binding) is the process of mapping a message to a specific sequence of code at runtime.

This is done to support the cases where the appropriate method can't be determined at compile time (i.e. statically).

Dynamic dispatch is only used for code invocation and not for other binding processes (such as for global variables) and the name is normally only used to describe a language feature where a runtime decision is required to determine which code to invoke.

class A {  void callme() {    System.out.println("Inside A's callme method");  }}

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 22: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

class B extends A {  void callme() {    System.out.println("Inside B's callme method");  }}

class C extends A {  void callme() {    System.out.println("Inside C's callme method");  }}

class Dispatch {  public static void main(String args[]) {    A a = new A(); // object of type A    B b = new B(); // object of type B    C c = new C(); // object of type C    A r; // obtain a reference of type A

    r = a; // r refers to an A object    r.callme(); // calls A's version of callme

    r = b; // r refers to a B object    r.callme(); // calls B's version of callme

    r = c; // r refers to a C object    r.callme(); // calls C's version of callme  }}

2. Describe Method overriding. Explain it with an example.

Hints:

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 23: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

In a class hierarchy, when a method in a subclass has the same name

and type signature as a method in its super class, then the method in

the subclass is said to override the method in the super class. When an

overridden method is called from within a subclass, it will always refer

to the version of that method defined by the subclass. The version of

the method defined by the super class will be hidden. Consider the

following:

// Method overriding. 

class A { 

int i, j; 

A(int a, int b) { 

i = a; 

j = b; 

// display i and j 

void show() { 

System.out.println("i and j: " + i + " " + j); 

}

class B extends A { 

int k; 

B(int a, int b, int c) { 

super(a, b); 

k = c; 

// display k – this overrides show() in A 

void show() { 

System.out.println("k: " + k); 

}

class Override { 

public static void main(String args[]) { 

B subOb = new B(1, 2, 3); 

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 24: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

subOb.show(); // this calls show() in B 

}

4. Explain the Object class and its methods

Hints:

Ultimate ancestor class

Equals , hashcode

5.Write a program which demonstrates Generic array list

Hints:

Declare array list

Increase or decrease the size

Access the array list

6. Explain interface with an example

Hints:

Collection of methods under one name

Program for sorting using interface

As you've already learned, objects define their interaction with the outside world through the methods that they expose. Methods form the object's interface with the outside world; the buttons on the front of your television set, for example, are the interface between you and the electrical wiring on the other side of its plastic casing. You press the "power" button to turn the television on and off.

In its most common form, an interface is a group of related methods with empty bodies. A bicycle's behavior, if specified as an interface, might appear as follows:

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 25: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

interface Bicycle {

void changeCadence(int newValue); // wheel revolutions per minute

void changeGear(int newValue);

void speedUp(int increment);

void applyBrakes(int decrement);}

To implement this interface, the name of your class would change (to a particular brand of bicycle, for example, such as ACMEBicycle), and you'd use the implementskeyword in the class declaration:

class ACMEBicycle implements Bicycle {

// remainder of this class implemented as before

}

Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.

7. Explain inner classes with an example.

Hints:

Definition of inner class

Program for demonstrating inner class

Java inner classes have feature that makes them richer and

more useful. An object of an inner class has an implicit reference

to the outer class object that instantiated it. Through this pointer,

it gains access to any variable of the outer object. Only static SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 26: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

inner classes don’t have this pointer. It is actually invisible when

we write the code, but compiler takes care of it. Inner classes are

actually a phenomenon of the compiler and not the JVM.

Inner classes may be defined with following access

modifiers : public, protected, private, or with default package

access.

The syntax for inner class is as follows:

123456

[modifiers] class OuterClassName {    code...    [modifiers] class InnerClassName {        code....    }}

UNIT III

PART A

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?

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 27: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

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.

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?

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 28: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

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), andFlyer, which has a method fly(). These types would be declared in interfaces

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

 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 {

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 29: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

   ...}   

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?

    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?

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 30: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

   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(). 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

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 31: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

enable serlializable objects to stored and re-constructed using ObjectInputStream andObjectOutputStream 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.

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.

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 32: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

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 I/OStream class hierarchy with an example program.

Hints:

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 33: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

2. Explain the ReaderStream class with an example program

Hints:

The Reader/Writer class hierarchy is character-

oriented, and the Input Stream/Output Stream class

hierarchy is byte-oriented. 

Basically there are two types of streams.Byte

streams that are used to handle stream of bytes and

character streams for handling streams of

characters.In byte streams input/output streams

are the abstract classes at the top of hierarchy,while

writer/reader are abstract classes at the top of

character streams hierarchy.

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 34: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

3. Explain the Writer Stream class hierarchy with an example program.

Hints:

Write characters to an output stream, translating characters into bytes according to a specified character encoding. Each OutputStreamWriter incorporates its own CharToByteConverter, and is thus a bridge from character streams to byte streams.

The encoding used by an OutputStreamWriter may be specified by name, by providing a CharToByteConverter, or by accepting the default encoding, which is defined by the system property file. encoding.

Each invocation of a write() method causes the encoding converter to be invoked on the given character(s). The resulting bytes are accumulated in a buffer before being written to the underlying output stream. The size of this buffer may be specified, but by default it is large enough for most purposes. Note that the characters passed to the write() methods are not buffered. For top efficiency, consider wrapping an OutputStreamWriter within a BufferedWriter so as to avoid frequent converter invocations. 

4. What are the virtual functions? Explain their needs using a suitable example .What are the rules associated with virtual functions?

In object-oriented programming, a virtual function or virtual

method is a function or method whose behaviour can be

overridden within an inheriting class by a function with the

same signature to provide the polymorphic behavior.

Therefore according to definition, every non-static method in JAVA is

by default virtual method except final and private methods. The

methods which cannot be inherited for polymorphic behavior is not a

virtual method.5. What are abstract classes? Give an example (with the program) to

illustrate the use of abstract classes.

Hints: SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 35: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

You can require that certain methods be overridden by

subclasses by specifying the abstract type modifier.

These methods are sometimes referred to as subclasser

responsibility because they have no implementation specified in

the superclass.

Thus, a subclass must override them—it cannot simply use the

version defined in the superclass. To declare an abstract method,

use this general form:

abstract type name(parameter-list);

As you can see, no method body is present. Any class that contains one

or more abstract methods must also be declared abstract. To declare a

class abstract, you simply use the abstract keyword in front of

the class keyword at the beginning of the class declaration. There can

be no objects of an abstract class. That is, an abstract class cannot be

directly instantiated with the new operator. Such objects would be

useless, because an abstract class is not fully defined. Also, you cannot

declare abstract constructors, or abstract static methods. Any subclass

of an abstract class must either implement all of the abstract methods

in the superclass, or be itself declared abstract. 

Here is a simple example of a class with an abstract method, followed

by a class which implements that method:

// A Simple demonstration of abstract. 

abstract class A { 

abstract void callme(); 

// concrete methods are still allowed in abstract classes 

void callmetoo() { 

System.out.println("This is a concrete method."); 

}

class B extends A { 

void callme() { 

System.out.println("B's implementation of callme."); 

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 36: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

}

class AbstractDemo { 

public static void main(String args[]) { 

B b = new B(); 

b.callme(); 

b.callmetoo(); 

}6. Explain about Code Reuse with program.

Hints:

Java is a oriented programming language and therefore consists of classes. This simple tutorial shows how to create a Java classes and how to reuse the code.

public class helloworld {public static String greeting_text = "Hello World";public static String greeting () {return greeting_text;}public static void main(String args[]) {System.out.println(greeting());}}

This code must be saved in a text file named helloworld.java (the name of

the text file must always be the same as the class), and then the class can

then be

compiled:

In the above example the helloWorld class is loaded as a separate object into

the new class, and then it's methods and properties can be accessed.

However, there is another way of using a class - by extending it:

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 37: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

public class helloworld_ext extends helloworld {public static void main(String args[]) {greeting_text = "And hello once more";System.out.println(greeting());}}

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.

 2. What are the two types of Exceptions?    Checked Exceptions and Unchecked Exceptions.

 

3. What is the base class of all exceptions?      java.lang.Throwable

 

 4.What is the difference between Exception and Error in java?      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.

 

5.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{} 

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 38: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

 

6.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?      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?      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?      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. 

 

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 39: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

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.

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

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 40: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

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. 

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 41: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

               throw new NullPointerException(\"thrownException\");

 

20.Why do I get a run-time Error when I add components to aJFrame/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 JScrollPaneto configure the scrolling behavior. Components that don’t implement Scrollablewill 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.

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 42: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

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 athttp://java.sun.com/products/jfc/tsc/swingdoc-archive/mixing.html. However, if it’s at all 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);  }

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 43: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

  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?

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.

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 44: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

 

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?

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?

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 45: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

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 Event handling mechanism with an example.

Hints:

You will learn how to handle events in java awt. Here, this is done

through the java.awt.*; package of java. Events are the integral part of

the java platform. You can see the concepts related to the event

handling through this example and used methods through which you

can implement the event driven application.

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 46: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

This example shows you how to handle events

in java.awt.*; package. AwtEvent is the main class of the program

which extends from the Frame class implements

the ActionListener interface.

This program starts to run from the main method in which the object

for the AwtEvent class has been created. The constructor of the

AwtEvent class creates two buttons with adding

the addActionListener()method to it. The constructor also initializes a

label with text "Roseindia.net".

When you click on the button then the actionPerformed() method is

called which receives the generated event. This method shows the text

of the source of the event on the label.

Here is the code of the program : 

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

public class AwtEvent extends Frame implements ActionListener{  Label lbl;  public static void main(String argv[]){  AwtEvent t = new AwtEvent();  }    public AwtEvent(){

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 47: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

  super("Event in Java awt");  setLayout(new BorderLayout());  try{  Button button = new Button("INSERT_AN_URL_HERE");  button.addActionListener(this);  add(button, BorderLayout.NORTH);  Button button1 = new Button("INSERT_A_FILENAME_HERE");  button1.addActionListener(this);  add(button1, BorderLayout.SOUTH);  lbl = new Label("Roseindia.net");  add(lbl, BorderLayout.CENTER);  addWindowListener(new WindowAdapter(){  public void windowClosing(WindowEvent we){  System.exit(0);  }  });  }  catch (Exception e){}  setSize(400,400);  setVisible(true);  }    public void actionPerformed(ActionEvent e){  Button bt = (Button)e.getSource();  String str = bt.getLabel();  lbl.setText(str);  }}

2. Describe about ‘Key Event’ and ‘Mouse Event’.

Hints:

Event source

Key event: Event generated from keyboard

Mouse event: Event generated from Mouse

Listener interface used to listen the event and

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 48: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

Take necessary action.

3. Explain about Template and its types with example.

Hints:

We use the same class for different data types.

We use the same method for different data type

Parameters.

mport java.util.*;class TestTemplate{

public static void main(String args[]){    LinkedList list = new LinkedList();

    list.add("b");    list.add("f");    //list.add(new Integer(5));    list.add("c");    System.out.println(list);

    LinkedList<String> stringList = new LinkedList<String>();    stringList.add("b");    stringList.add("f");    // stringList.add(new Integer(5)); syntax error    stringList.add("a");    stringList.add("c");

    //LinkedList<int> intList = new LinkedList<int>(); syntax error

    System.out.println(stringList);

    // lets show iterators

    Iterator it1 = list.iterator();    System.out.print("[");    while (it1.hasNext())

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 49: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

    {    String s = (String) it1.next(); // note cast necessary    System.out.print(s+" ");    }    System.out.println("]");

    Iterator<String> it2 = stringList.iterator();    System.out.print("[");        while (it2.hasNext())    {        String s = it2.next();         System.out.print(s+" ");    }    System.out.println("]");

}

}

UNIT V

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

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 50: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

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 }

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

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

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

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

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

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 51: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

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

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

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

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

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

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

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

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

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

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 52: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

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

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

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

 

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

 

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 53: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

 

 

 

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

 

 

27.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 acquire an object\'s lock, it enters the waiting state until the lock becomesavailable.

 28.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.What is Runnable interface ? Are there any other ways to make a java program as multithred java program?  

Hints:  

There are two ways to create new kinds of threads:

 Define a new class that extends the Thread class

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 54: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

1. Define a new class that implements the Runnable interface, and pass an object of that class to a Thread\'s constructor.

2. 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() {

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  

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

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 55: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

Hints:

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.

 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.

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 56: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

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

 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;

}

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 57: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

 

}

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

 Hints:

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.

 

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();

SCAD COLLEGE OF ENGG & TECH DEPT OF IT

Page 58: Java Solved Qb

IT 51 – JAVA PROGRAMMING SOLVED QUESTION BANK

Thread.State e = t.getState();

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

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

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

}  

}

}      

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 );

}

}

SCAD COLLEGE OF ENGG & TECH DEPT OF IT