Sunday, June 17, 2012
JAVA
static
A Static method in Java is one that belongs to a class rather than an object of a class. Normal methods of a class can be invoked only by using an object of the class but a Static method can be invoked Directly.
Difference between Vector and ArrayList?
Vector is synchronized whereas arraylist is not.
THREADS
Threads are a way for a program to fork (or split) itself into two or more simultaneously (or pseudo-simultaneously) running tasks.
Threads and processes differ from one operating system to another but, in general, a thread is contained inside a process and different threads in the same process share some resources while different processes do not.
STring buffer, String Class
Java provides the StringBuffer and String classes, and the String class is used to manipulate character strings that cannot be changed. Simply stated, objects of type String are read only and immutable. The StringBuffer class is used to represent characters that can be modified.
The significant performance difference between these two classes is that StringBuffer is faster than String when performing simple concatenations. In String manipulation code, character strings are routinely concatenated. Using the String class, concatenations are typically performed as follows:
POLYMORPHISM - over loading ,over riding
polymorphism translates from Greek as many forms ( poly - many morph - forms)
in OOP's it refers to
the propensity of objects to react differently to the same method (VA pg 110)
method overloading is the primary way polymorphism is implemented in Java
Overloading methods
overloaded methods:
appear in the same class or a subclass
have the same name but,have different parameter lists, and,can have different return types
an example of an overloaded method is print() in the java.io.PrintStream class
public void print(boolean b)
public void print(char c)
public void print(char[] s)
public void print(float f)
public void print(double d)
public void print(int i)
public void print(long l)
public void print(Object obj)
public void print(String s)
the actual method called depends on the object being passed to the method
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
overriding allows a subclass to re-define a method it inherits from it's superclass
overriding methods:
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 be packagage, protected, or public
if the superclass methods is private, it is not inherited and overriding is not an issue
the throws clause of the overriding method may only include exceptions that can be thrown by the superclass method, including it's subclasses
class LBException extends Exception {}
class LBException1 extends LBException {}
In superclass:
public void testEx() throws LBException {
throw new LBException();
}
In subclass:
public void testEx() throws LBException1 {
throw new LBException1();
}
overriding is allowed as LBException1 thrown in the subclass is itself a subclass of the exception LBException thrown in the superclass method
Side effect of late-binding
it is Java's use of late-binding which allows you to declare an object as one type at compile-time but executes based on the actual type at runtime
class LB_1 {
public String retValue(String s) {
return "In LB_1 with " + s;
}
}
class LB_2 extends LB_1 {
public String retValue(String s) {
return "In LB_2 with " + s;
}
}
if you create an LB_2 object and assign it to an LB_1 object reference, it will compile ok
at runtime, if you invoke the retValue(String s) method on the LB_1 reference, the LB_2 retValue(String s) method is used, not the LB_1 method
LB_2 lb2 = new LB_2();
LB_1 lb3 = lb2; // compiles ok
System.out.println(lb3.retValue("Today"));
Output:
In LB_2 with Today
##################################################################################################
Garbage collection
The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.
Interface vs Abstract Class
An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.
Pass by reference : Pass by Value
Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed
A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.
A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.
public : Public class is visible in other packages, field is visible everywhere (class must be public too)
private : Private variables or methods may be used only by an instance of the same class that declares the variable or method, A private feature may only be accessed by the class that owns the feature.
protected : Is available to all classes in the same package and also available to all subclasses of the class that owns the protected feature.This access is provided even to subclasses that reside in a different package from the class that owns the protected feature.
default :What you get by default ie, without any access modifier (ie, public private or protected).It means that it is visible to all within a particular package.
A: Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such.
A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.
Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.
Fianl
A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant).
Over Riding
When a class defines a method using the same name, return type, and arguments as a method in its superclass, the method in the class overrides the method in the superclass.
When the method is invoked for an object of the class, it is the new definition of the method that is called, and not the method definition from superclass. Methods may be overridden to be more public, not more private.
Serialization:
Serialization is a mechanism by which you can save the state of an object by converting it to a byte stream.
eg:
The class whose instances are to be serialized should implement an interface Serializable. Then you pass the instance to the ObjectOutputStream which is connected to a fileoutputstream. This will save the object to a file.
TRY cAtch
It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method.
If I write return at the end of the try block, will the finally block still execute?
A: Yes even if you write return as the last statement in the try block and no exception occurs, the finally block will execute. The finally block will execute and then the control return.
Synchronization
With respect to multithreading, synchronization is the capability to control
the access of multiple threads to shared 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 significant errors.
Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection
This() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.
A: Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system. setDaemon method is used to create a daemon thread.
While making a JDBC connection we go through the following steps :
Step 1 : Register the database driver by using :
Class.forName(\" driver classs for that specific database\" );
Step 2 : Now create a database connection using :
Connection con = DriverManager.getConnection(url,username,password);
Step 3: Now Create a query using :
Statement stmt = Connection.Statement(\"select * from TABLE NAME\");
Step 4 : Exceute the query :
stmt.exceuteUpdate();
How does a try statement determine which catch clause should be used to handle an exception?
A:
When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exceptionis executed. The remaining catch clauses are ignored.
What method must be implemented by all threads?
A: All tasks must implement the run() method, whether they are a subclass of Thread or implement the Runnable interface.
FINAL
A final method cannot be overridden by subclasses. This is used to prevent unexpected behavior from a subclass altering a method that may be crucial to the function or consistency of the class
A final class cannot be extended. This is done for reasons of security and efficiency.
A final variable can only be initialized once,
FINALIZE
every class inherits the finalize() method from java.lang.Object
the method is called by the garbage collector when it determines no more references to the object exist
the Object finalize method performs no actions but it may be overridden by any class
normally it should be overridden to clean-up non-Java resources ie closing a file
if overridding finalize() it is good programming practice to use a try-catch-finally statement and to always call super.finalize() (JPL pg 47-48). This is a saftey measure to ensure you do not inadvertently miss closing a resource used by the objects calling class
protected void finalize() throws Throwable {
try {
close(); // close open files
} finally {
super.finalize();
}
}
any exception thrown by finalize() during garbage collection halts the finalization but is otherwise ignored
finalize() is never run more than once on any object
FINALLY: try catch finally:
The finally block always executes when the try block exits. 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.
INTERFACE:
An interface in the Java programming language is an abstract type that is used to specify an interface (in the generic sense of the term) that classes must implement. Interfaces are declared using the interface keyword, and may only contain method signature and constant declarations (variable declarations that are declared to be both static and final). An interface may never contain method definitions.
Interfaces cannot be instantiated. A class that implements an interface must implement all of the methods described in the interface, or be an abstract class. Object references in Java may be specified to be of an interface type; in which case, they must either be null, or be bound to an object that implements the interface.
One benefit of using interfaces is that they simulate multiple inheritance. All classes in Java (other than java.lang.Object, the root class of the Java type system) must have exactly one base class; multiple inheritance of classes is not allowed. Furthermore, a Java class may implement, and an interface may extend, any number of interfaces; however an interface may not implement an interface.
Difference bw STATIC and FINAL
Static variable can change their values, final variables can not be changed they are constants . Static variable it attached to their class not with the object only one copy of static variable is exists and they can be called with reference of their class only final classed can not be extended and their are not static classes.
1.Static variables (also called class variables) only exist in the class they are defined in. They are not instantiated when an instance of the class is created. In other words, the values of these variables are not a part of the state of any object. When the class is loaded, static variables are initialized to their default values if no explicit initialization expression is specified
Final variable:values of final variables cannot be changed.
2.Static methods are also known as class methods. A static method in a class can directly access other static members in the class. It cannot access instance (i.e., non-static) members of the class, as there is no notion of an object associated with a static method. However, note that a static method in a class can always use a reference of the class's type to access its members, regardless of whether these members are static or not.
Final methods:cannot be overriden.
7) What is the difference between constructor and method?
Ans: Constructor will be automatically invoked when an objected is created whereas method has to be called explicitly.
13) What are different types of access modifiers?
Ans: public: Any thing declared as public can be accessed from anywhere.
private: Any thing declared as private can’t be seen outside of its class.
protected: Any thing declared as protected can be accessed by classes in the same package and subclasses in
the other packages.
default modifier : Can be accessed only to classes in the same package.
14) What is final, finalize() and finally?
Ans: final : final keyword can be used for class, method and variables.
• A final class cannot be subclassed and it prevents other programmers from subclassing a secure class to invoke insecure methods.
• A final method can’ t be overridden
• A final variable can’t change from its initialized value.
finalize( ) : finalize( ) method is used just before an object is destroyed and can be called just prior to
garbage collection.
finally : finally, a key word used in exception handling, creates a block of code that will be executed after a
try/catch block has completed and before the code following the try/catch block. The finally block will
execute whether or not an exception is thrown.
For example, if a method opens a file upon exit, then you will not want the code that closes the file
to be bypassed by the exception-handling mechanism. This finally keyword is designed to address this
contingency.
20) What is difference between overloading and overriding?
Ans: a) In overloading, there is a relationship between methods available in the same class whereas in overriding,
there is relationship between a superclass method and subclass method.
b) Overloading does not block inheritance from the superclass whereas overriding blocks inheritance from
the superclass.
c) In overloading, separate methods share the same name whereas in overriding, subclass method replaces
the superclass.
d) Overloading must have different method signatures whereas overriding must have same signature.
22) What is the difference between this and super?
Ans: this can be used to invoke a constructor of the same class whereas super can be used to invoke a super class
constructor.
35) What is the difference between Array and vector?
Ans: Array is a set of related data type and static whereas vector is a growable array of objects and dynamic.
37) What is the difference between process and thread?
Ans: Process is a program in execution whereas thread is a separate path of execution in a program.
38) What is multithreading and what are the methods for inter-thread communication and what is the class
in which these methods are defined?
Ans: Multithreading is the mechanism in which more than one thread run independent of each other within the
process.
wait (), notify () and notifyAll() methods can be used for inter-thread communication and these methods are
in Object class.
wait( ) : When a thread executes a call to wait( ) method, it surrenders the object lock and enters into a
waiting state.
notify( ) or notifyAll( ) : To remove a thread from the waiting state, some other thread must make a call to
notify( ) or notifyAll( ) method on the same object.
class cast exception
Exception thrown in JavaLanguage during runtime when an attempt is made to cast an object reference to an incompatible type. And - which is often forgotten - this includes cases of the same Class loaded by another ClassLoader.
Abstract classes
Main article: Abstract type
An abstract class, or abstract base class (ABC), is a class that cannot be instantiated. Such a class is only meaningful if the language supports inheritance. An abstract class is designed only as a parent class from which child classes may be derived. Abstract classes are often used to represent abstract concepts or entities. The incomplete features of the abstract class are then shared by a group of subclasses which add different variations of the missing pieces.
Abstract classes are superclasses which contain abstract methods and are defined such that concrete subclasses are to extend them by implementing the methods. The behaviors defined by such a class are "generic" and much of the class will be undefined and unimplemented. Before a class derived from an abstract class can become concrete, i.e. a class that can be instantiated, it must implement particular methods for all the abstract methods of its parent classes.
When specifying an abstract class, the programmer is referring to a class which has elements that are meant to be implemented by inheritance. The abstraction of the class methods to be implemented by the subclasses is meant to simplify software development. This also enables the programmer to focus on planning and design.
__________________
An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.
An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:
abstract void moveTo(double deltaX, double deltaY);
If a class includes abstract methods, the class itself must be declared abstract, as in:
public abstract class GraphicObject {
// declare fields
// declare non-abstract methods
abstract void draw();
}
When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, the subclass must also be declared abstract.
________________________
* abstract classes can contain fields that are not static and final, and they can contain implemented methods
* Such abstract classes are similar to interfaces, except that they provide a partial implementation, leaving it to subclasses to complete the implementation. If an abstract class contains only abstract method declarations, it should be declared as an interface instead.
Q: Describe synchronization in respect to multithreading.
A: With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.
Q: Explain different way of using thread?
A: The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance..the only interface can help.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment