You are on page 1of 20

Assessment -1 (JAVA, J2EE, RDBMS) Ques 10 : Can an Interface have an inner class?

Explain Ans 10: Yes, an interface can have an inner class. For eg. public interface abc { static int i=0; void dd(); class a1 { a1() { int j; System.out.println("in interfia"); }; public static void main(String a1[]) { System.out.println("in interfia"); } } }

Ques 11 : What is overloading and overriding ?Explain with example. Ans 11 : Overloading is when the same method or operator can be used on many different types of data. For instance the + sign is used to add ints as well as concatenate strings. The plus sign behaves differently

depending on the type of its arguments. Therefore the plus sign is inherently overloaded. Methods can be overloaded as well..same method with different parameters is said to be method overloading.---we can perform the similar operation in different ways for different parameters. Constructors can be overloaded as well...Overloaded constructors provide multiple ways to initialize a new object overloading is call as Compile time polymorphism which refers as static polymorphism. overriding Sometimes a subclass inherits a method from a superclass that doesn't quite fit its needs. Perhaps the subclass inherited twenty methods and just one of them wasn't quite right. In that case, the subclass would override that method by redefining that method itself. This override does not affect the method as defined in the superclass. The Cat class in the following example is the subclass and the Animal class is the superclass. The Cat class overrides eat() method inherited from Animal class. public class Animal { public void eat() { System.out.println("Eat for Animal"); } } public class Cat extends Animal { public void eat() { System.out.println("Eat for Cat"); } }

Ques 12 : Define and Explain access modifiers in java

Ans 12 : Access modifiers specifies who can access them. There are four access modifiers used in java. They are public, private, protected, no modifer (declaring without an access modifer). Using no modifier is also sometimes referred as package-private or default or friendly access. Usage of these access modifiers is restricted to two levels. The two levels are class level access modifiers and member level access modifiers. I) Class level access modifiers (java classes only) Only two access modifiers is allowed, public and no modifier
y y

If a class is public, then it CAN be accessed from ANYWHERE. If a class has no modifier, then it CAN ONLY be accessed from same package.

II) Member level access modifiers (java variables and java methods) All the four public, private, protected and no modifier is allowed.
y y y

public and no modifier the same way as used in class level. private members CAN ONLY access. protected CAN be accessed from same package and a subclass existing in any package can access.

For better understanding, member level access is formulated as a table:

Same Class Same Package Subclass Other packages Access Modifiers public protected no access modifier private Y Y Y Y Y Y Y N Y Y N N Y N N N

Alternate ans.: The access to classes, constructors, methods and fields are regulated using access modifiers i.e. a class can control what information or data can be accessible by other classes. To take advantage of encapsulation, you should minimize access whenever possible. Java provides a number of access modifiers to help you set the level of access you want for classes as well as the fields, methods and constructors in your classes. A member has package or default accessibility when no accessibility modifier is specified.

Access Modifiers

1. private 2. protected 3. default 4. public public access modifier Fields, methods and constructors declared public (least restrictive) within a public class are visible to any class in the Java program, whether these classes are in the same package or in another package. private access modifier The private (most restrictive) fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. Fields, methods or constructors declared private are strictly controlled, which means they cannot be accesses by anywhere outside the enclosing class. A standard design strategy is to make all fields private and provide public getter methods for them. protected access modifier The protected fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. Fields, methods and constructors declared protected in a superclass can be accessed only by subclasses in other packages. Classes in the same package can also access protected fields, methods and constructors as well, even if they are not a subclass of the protected members class. default access modifier Java provides a default specifier which is used when no access modifier is present. Any class, field, method or constructor that has no declared access modifier is accessible only by classes in the same package. The default modifier is not used for fields and methods within an interface.

Ques 13 : Describe the wrapper classes in Java and how they are useful ? Ans 13 : Wrapper classes allow primitive data types to be accessed as objects. They are one per primitive type: Boolean, Byte, Character, Double, Float, Integer, Long and Short. Wrapper classes make the primitive type data to act as objects. Need Of Wrapper Class: Dealing with primitives as objects is easier at times. Most of the objects collection store objects and not primitive types. Many utility methods are provided by wrapper classes. To get these

advantages we need to use wrapper classes. As they are objects, they can be stored in any of the collection and pass this collection as parameters to the methods. Features of the Java wrapper Classes.

* Wrapper classes convert numeric strings into numeric values. * The way to store primitive data in an object. * The valueOf() method is available in all wrapper classes except Character * All wrapper classes have typeValue() method. This method returns the value of the object as its primitive type.

Ques14 : Whats the difference between static and dynamic class loading . Explain how can you practically do dynamic loading ? Ans 14 : Static class loading occurs when the name of the class to be loaded is known to the Java compiler, and the full name can be placed in the class file. The JVM will use the name in the class file to load the class any time prior to the first use. For example, if I have code like this: import java.util.*; public class StaticLoadTest { public static void main(String [] args) { ArrayList mylist; mylist = new ArrayList(6); } } then the JVM will probably choose to load the java.util.ArrayList class when it begins to execute line 5. The Java compiler was able to tell that I wanted java.util.ArrayList because I imported java.util and I explicitly put ArrayList into my code. Dynamic class loading is when code requests the JVM to load a class by using the class name as a String, during execution. The most common way of doing this is to use the Class.forName() method.

public class DynamicLoadTest { public static void main(String [] args) { String cname = "java.util." + "HashSet"; Object hs; Class hsc = null; try { hsc = Class.forName(cname); } catch (Exception e) { System.err.println("Unable to load class " + cname); } if (hsc != null) { hs = hsc.newInstance(); } } } This approach is called dynamic because the program can compute the class name to load on the fly. There is no way for the compiler to know what class might be requested. Dynamic class loading is very useful when your system needs to load specialized classes directed by the user, or as part of its run-time configuration.

Ques 15 : Define Synchronization and Serialization ?Explain their importance. Ans 15 : Synchronization Threads communicate primarily by sharing access to fields and the objects reference fields refer to. This form of communication is extremely efficient, but makes two kinds of errors possible: thread interference and memory consistency errors. The tool needed to prevent these errors is synchronization. Importance : Synchronization is best use with the Multi-Threading in Java, Synchronization is the capability to control the access of multiple threads to share resources. Without synchronization it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value.This often leads to an error.

Serialization

Primary purpose of java serialization is to write an object into a stream, so that it can be transported through a network and that object can be rebuilt again. When there are two different parties involved, you need a protocol to rebuild the exact same object again. Java serialization API just provides you that. Other ways you can leverage the feature of serialization is, you can use it to perform a deep copy. Importance: Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object. After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory. Most impressive is that the entire process is JVM independent, meaning an object can be serialized on one platform and deserialized on an entirely different platform. Ques 16 : Differentiate between Throw and Throws Ans 16 : Whenever we want to force an exception then we use throw keyword. the throw keyword (note the singular form) is used to force an exception. It can also pass a custom message to your exception handling module. Moreover throw keyword can also be used to pass a custom message to the exception handling module i.e. the message which we want to be printed. Ques 17 : Differences between HashList and HashMap, Set and List ? Ans 17 : Hashlist Hashlistis basically a datastructure to retain values of key-value pair.
y y

It didnt allow null for both key and value. You will get NullPointerException if you add null value. It is synchronized. So it comes with its cost. Only one thread can access in one tim?

1Hashtable<Integer,String>; cityTable = new Hashtable<Integer,String>(); 2cityTable.put(1, "Lahore"); 3cityTable.put(2, "Karachi"); 4cityTable.put(3, null); /* NullPointerEcxeption at runtime*/ 5 6System.out.println(cityTable.get(1));

7System.out.println(cityTable.get(2)); 8System.out.println(cityTable.get(3)); HashMap Like Hashtable it also accepts key value pair.
y y

It allows null for both key and value It is unsynchronized. So come up with better performance

1HashMap<Integer,String> productMap = new HashMap<Integer,String>(); 2productMap.put(1, "Keys"); 3productMap.put(2, null); Hashtable is syncronised where as HashMap is not. Hence HashMap is faster. Hasttable does not allow any null value as either key or value. However HashMap allows multiple null values and one null as a key. Set has no duplicate items and allows only one null element. List might have duplicate items and allows multiple null element. Ques 18 : Give all differences between ArrayList and Vector. Ans 18 : All the methods of Vector is synchronized. But, the methods of ArrayList is not synchronized. In general, executing a synchronized method results in costlier performance than a unsynchronized method. Keeping the difference in mind, using Vector will incur a performance hit than the ArrayList. But, when there is a certain need for thread-safe operation Vector needs to be used. ArrayList can be synchronized using the java collections framework utility class and then ArrayList itself can be used in place of Vector. When there is no need for synchronized operation and you still look for better performance Array can be used instead of ArrayList. But the development is tedious, since it doesnt provide user friendly methods. When you use Vector or ArrayList, always initialize to the largest capacity that the java program will need. Since incrementing the size is a costlier operation.

Ques 19 : Differentiate between JVM,JRE,JDK? Ans 19 : Java Virtual Machine (JVM) is an abstract computing machine. Java Runtime Environment (JRE) is an implementation of the JVM. Java Development Kit (JDK) contains JRE along with various development tools like Java libraries, Java source compilers, Java debuggers, bundling and deployment tools. JVM becomes an instance of JRE at runtime of a java program. It is widely known as a runtime interpreter. The Java virtual machine (JVM) is the cornerstone on top of which the Java technology is built upon. It is the component of the Java technology responsible for its hardware and platform independence. JVM largely helps in the abstraction of inner implementation from the programmers who make use of libraries for their programmes from JDK.

Diagram to show the relations between JVM JRE JDK

Ques 20 : What are checked exceptions and runtime exceptions . Give Example Ans 20 : A checked exception is any subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses. Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream's read() method

Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method. Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be, as they tend to be unrecoverable.

Ques 21 :Give all differences between Comparable and Comparator Interface. Ans 21 : The key difference between comparable and comparator interface is: y Comparable Interface

The comparable interface should be used when the current object is to be compared to objects of its type only. y Comparator Interface

The comparator should be used when some external class is taking your class as a parameter for some comparison operation and it doesn't know how to compare the objects and expects you to give it. In this case you can't give your class as the comparator. It has to be some other class which implements comparator interface and does the comparison.

Ques 22 : Define and Differentiate Final,Finally and Finalize ? Ans 22 : * final constant declaration.
* finally The finally block always executes when the try block exits, except System.exit(0) call. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated. * finalize() method helps in garbage collection. A method that is invoked before an object is discarded by the garbage collector, allowing it to clean up its state. Should not be used to release non-memory resources like file handles, sockets, database connections etc because Java has only a finite number of these resources and you do not know when the garbage collection is going to kick in to release these non-memory resources through the finalize() method.

The final is a keyword and used for making a member/variable as a constant which will not be modified once declared. The finally is a method and used during the exception handling to release any resource hold by try block. And the finalize method, all the resources mention will be garbage collected as soon as GC is called. The finalize and finally seems to be similar, but the difference is finally is gone execute every-time whether you call it or not, and this not similar with finalize.

Ques 23 : What is synchronization and why is it important ? Ans 23 : Synchronization is best use with the Multi-Threading in Java, Synchronization is the capability to control the access of multiple threads to share resources. Without synchronization it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value.This often leads to an error.
Example for Synchronization public synchronized void enqueue(Object item) {// Body of method goes here } public void enqueue(Object item) {synchronized (this) {//Body of method goes here } } The Java programming language provides two basic synchronization idioms: synchronized methods and synchronized statements. To make a method synchronized, simply add the synchronized keyword to its declaration: public class SynchronizedCounter { private int c = 0; public synchronized void increment() {c++;

} public synchronized void decrement() {c--; } public synchronized int value() {return c; } } If count is an instance of SynchronizedCounter, then making these methods synchronized has two effects: * First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object. * Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.

Ques 24 : Explain the impact of private constructor. Ans 24 : Private Constructors cant be access from any derived classes neither from another class. So you have to provide a public function that calls the private constructor if the object has not been initailized, or you have to return an instance to the object, if it was initialized.
This can be useful for objects that cant be instantiated.

Ques 25 : How many objects are there in this code String s1=Hello; int I =10;Float f=10.6; Short j=18;long l=1299889; String s2=new String(Hello); String s3=new String(Bye); String s4=s3; Boolean b =true;

Ans 25 : Ques 26 : Whats difference between Static and Non-Static fields of a class. Ans 26 : A static field belongs to a class. The objects of the class can not have the copy of these
fields. These fields are referred by the class name. Ex: Employee. company. Without creating an instance of a class, these fields can be accessed. A non-static field is accessed by all objects of the class. Each object has one copy of non-static field. To use non static fields, an instance of the class should be created.

Ques 27 : How many Threads are there in this code : class A1 extends Thread { public void run { System.out.println(I am Thread);} public static void main(String args){ A1 obj1 = new A1(); A1 obj2 = new A1(); A1 obj3 = new A1(); obj1.start(); obj2.start(); obj3.start(); obj1.run(); } } Ans 27 : Ques 28 : Write a program to count all words in a text file . Ans 28 :
import java.io.File; import java.util.Scanner; public class FileWordVowelCounter { public static void main(String[] args) throws Exception { Scanner in = new Scanner(new File("read.txt")); int nbWords = 0;

int nbVowels = 0; while(in.hasNext("\\S+")) { String word = in.next("\\S+"); nbVowels += getNbVowels(word); nbWords++; } System.out.println(nbWords); System.out.println(nbVowels); } public static int getNbVowels(String word) { int result = 0; char[] chars = word.toCharArray(); for(Character c : chars) { if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') { result++; }} return result; } }

Ques 29 : Write a program to make a thread using anonymous class . Ans 29 : A Class which does not have any name is known as anonymous class.
class testAno { { public static void main(String args[])

Thread t =new Thread(new runnable(){ public void run() { System.out.println("I am in Thread"); } }); t.start(); } }

Ques 30 : Describe Thread Life cycle and implement it in code . Ans 30 : Ques 31 : Give Output of following : public class Test extends Thread { Test(String a){ super(a); } public static void main(String[] args) { try{ new Test("One").start(); new Test("Two").start(); }catch(IOException e){} catch(Exception e){} } public void run(){ System.out.println("Thread Name :"+getName()); } } A: Thread Name :One B: Thread Name :Two C: Thread Name :One Thread Name :Two

D: Runtime Exception E: Compilation Fails Ans 31 : Ques 32 : What is OOPs ? Explain in detail. Ans 32 : Object Oriented Programming or OOP is the technique to create programs based on the real world. Unlike procedural programming, here in the OOP programming model programs are organized around objects and data rather than actions and logic. Objects represent some concepts or things and like any other objects in the real Objects in programming language have certain behavior, properties, type, and identity. In OOP based language the principal aim is to find out the objects to manipulate and their relation between each other. OOP offers greater flexibility and compatibility and is popular in developing larger application. Another important work in OOP is to classify objects into different types according to their properties and behavior. So OOP based software application development includes the analysis of the problem, preparing a solution, coding and finally its maintenance.

Java is a object oriented programming and to understand the functionality of OOP in Java, we first need to understand several fundamentals related to objects. These include class, method, inheritance, encapsulation, abstraction, polymorphism etc.

Class - It is the central point of OOP and that contains data and codes with behavior. In Java everything happens within class and it describes a set of objects with common behavior. The class definition describes all the properties, behavior, and identity of objects present within that class. As far as types of classes are concerned, there are predefined classes in languages like C++ and Pascal. But in Java one can define his/her own types with data and code.

Object - Objects are the basic unit of object orientation with behavior, identity. As we mentioned above, these are part of a class but are not the same. An object is expressed by the variable and methods within the objects. Again these variables and methods are distinguished from each other as instant variables, instant methods and class variable and class methods.

Methods - We know that a class can define both attributes and behaviors. Again attributes are defined by variables and behaviors are represented by methods. In other words, methods define the abilities of an object.

Inheritance - This is the mechanism of organizing and structuring software program. Though objects are distinguished from each other by some additional features but there are objects that share certain things common. In object oriented programming classes can inherit some common behavior and state from others. Inheritance in OOP allows to define a general class and later to organize some other classes simply adding some details with the old class definition. This saves work as the special class inherits all the properties of the old general class and as a programmer you only require the new features. This helps in a better data analysis, accurate coding and reduces development time.

Abstraction - The process of abstraction in Java is used to hide certain details and only show the essential features of the object. In other words, it deals with the outside view of an object (interface).

Encapsulation - This is an important programming concept that assists in separating an object's state from its behavior. This helps in hiding an object's data describing its state from any further modification by external component. In Java there are four different terms used for hiding data constructs and these are public, private, protected and package. As we know an object can associated with data with predefined classes and in any application an object can know about the data it needs to know about. So any unnecessary data are not required by an object can be hidden by this process. It can also be termed as information hiding that prohibits outsiders in seeing the inside of an object in which abstraction is implemented.

Polymorphism - It describes the ability of the object in belonging to different types with specific behavior of each type. So by using this, one object can be treated like another and in this way it can create and define multiple level of interface. Here the programmers need not have to know the exact type of object in advance and this is being implemented at runtime.

Encapsulation, Inheritance, and Polymorphism Encapsulation:Encapsulation is the mechanism that binds together code and the data it manipulates Inheritance: Inheritance is nothing but , inherit the properties of an another object Polymorphism: In general words, a compound or a substance having different forms,likewise a method behaving differently on different calls,here we have method overloading and method overriding.

Ques 33 : Explain Late Binding and Early Binding with code in Java . Ans 33: There's binding at compile-time ("early") and runtime ("late"). These are also
sometimes referred to as static and dynamic binding. And the difference is in when the address of the called function is determined for invocation. In a dynamic binding scheme, it's possible to defer this determination until it's actually required. In a sense, you're relying on the fact that the method you want will "be there" when you need it, but the real benefit is that it's possible to choose the actual code you want run at the last possible moment, making it possible to flex the behavior of your code.

Ques 34 : Differentiate between Unstructured ,Modular and Procedural Programming ? Ans 34 :


y Procedural Programming

Gives importance to algorithm rather than data. It follows Top-down structures. y Although Java is primarily concerned with the creation of classes and objects, and with the communication between objects, the definitions of methods in Java are primarily imperative/procedural. (Those of you who didn't take 151 in Scheme can probably sleep for the next few comments.) In a procedural (or imperative) language, programs are written as collections of what I term "basic actions" which are then sequenced with "control structures". Basic actions are typically of one of the following forms: Get a value from memory Store a value in memory Compute a value from other values Read a value from an input device Write a value to an output device We usually reserve and assign types to memory locations using variables. These are similar to the things you declare using let. There are a variety of control structures in imperative languages. The basic ones include o Sequencing o Conditionals o Loops o Function calls

y y y y y y y y y y

In imperative languages, instructions are often presented in sequences, and the instructions are then executed one-by-one. This corresponds to the block command in scheme. Conditionals select one of a number of options, based on a selector value. The most common conditional is the if statement. In most imperative languages, if selects between two alternative sequences of actions (or decides whether or not to execute a single alternative) based on the value of a boolean expression. Loops repeat a sequence of actions some number of times. The number of times can be fixed, or it can depend on a condition that is regularly checked. You may know loops form the do loop of scheme. Function calls are similar to those of Scheme. When you call another function, the body of that function is executed.

example : Pascal and C

Unstructured programming

Non-structured programming is the historically earliest programming paradigm capable of creating Turing-complete algorithms. It has been followed historically by procedural programming and then object-oriented programming, both of them considered as structured programming.

Unstructured programming has been heavily criticized for producing hardly-readable ("spaghetti") code and is sometimes considered a bad approach for creating major projects, but had been praised for the freedom it offers to programmers and has been compared to how Mozart wrote music. There are both high and low level programming languages that use non-structured programming. These include early versions of BASIC (such as MSX BASIC and GW-BASIC), JOSS, FOCAL, MUMPS, TELCOMP, COBOL, machine-level code, early assembler systems (without procedural metaoperators), assembler debuggers and some scripting languages such as MS-DOS batch file languag

Modular programming.

!Break a large program into smaller independent modules. Advantages. y Debug pieces independently.

y y y y y

Divide work for multiple programmers. Reuse code. Modular programming in Java. Define new classes in terms of old ones. Keep classes small.

Ques 35 : Give methods of String class that can be overridden ? Ans 35 : Ques 36 : Difference between String[] a and Stringa ? Ans 36 :