J2EE |
||
|
Abstraction: Showing the essential and hiding the non-Essential is known as Abstraction.
Encapsulation: The Wrapping up of data and functions into a single unit is known as Encapsulation. 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 accessed via the interface of the object.
Inheritance: is the Process by which the Obj of one class acquires the properties of Obj’s another Class. A reference variable of a Super Class can be assign to any Sub class derived from the Super class. Inheritance is the method of creating the new class based on already existing class , the new class derived is called Sub class which has all the features of existing class and its own, i.e sub class. Adv: Reusability of code , accessibility of variables and methods of the Base class by the Derived class.
Polymorphism: The ability to take more that one form, it supports Method Overloading & Method Overriding.
Method overloading: When a method in a class having the same method name with different arguments (diff Parameters or Signatures) is said to be Method Overloading. This is Compile time Polymorphism. Using one identifier to refer to multiple items in the same scope.
Method Overriding: When a method in a Class having same method name with same arguments is said to be Method overriding. This is Run time Polymorphism. Providing a different implementation of a method in a subclass of the class that originally defined the method. 1. In Over loading there is a relationship between the methods available in the same class ,where as in Over riding there is relationship between the Super class method and Sub class method. 2. Overloading does not block the Inheritance from the Super class , Where as in Overriding blocks Inheritance from the Super Class. 3. In Overloading separate methods share the same name, where as in Overriding Sub class method replaces the Super Class. 4. Overloading must have different method Signatures , Where as Overriding methods must have same Signatures.
Dynamic dispatch: is a mechanism by which a call to Overridden function is resolved at runtime rather than at Compile time , and this is how Java implements Run time Polymorphism.
Dynamic Binding: Means the code associated with the given procedure call is not known until the time of call the call at run time. (it is associated with Inheritance & Polymorphism).
Bite code: Is a optimized set of instructions designed to be executed by Java-run time system, which is called the Java Virtual machine (JVM), i.e. in its standard form, the JVM is an Interpreter for byte code. JIT- is a compiler for Byte code, The JIT-Complier is part of the JVM, it complies byte code into executable code in real time, piece-by-piece on demand basis.
Final classes : String, Integer , Color, Math Abstract class : Generic servlet, Number class
variable:An
item of data named by an identifier.Each variable has a type,such as
class variable :A data item associated with a particular class as a whole--not with particular instances of the class. Class variables are defined in class definitions. Also called a static field. See also instance variable. instance variable :Any item of data that is associated with a particular object. Each instance of a class has its own copy of the instance variables defined in the class. Also called a field. See also class variable. local variable :A data item known within a block, but inaccessible to code outside the block. For example, any variable defined within a method is a local variable and can't be used outside the method. class method :A method that is invoked without reference to a particular object. Class methods affect the class as a whole, not a particular instance of the class. Also called a static method. also instance method. instance method :Any method that is invoked with respect to an instance of a class. Also called simply a method. See also class method.
Interface: Interfaces can be used to implement the Inheritance relationship between the non-related classes that do not belongs to the same hierarchy, i.e. any Class and any where in hierarchy. Using Interface, you can specify what a class must do but not how it does. 1).A class can implement more than one Interface. 2).An Interface can extend one or more interfaces, by using the keyword extends. 3).All the data members in the interface are public, static and Final by default. 4).An Interface method can have only Public, default and Abstract modifiers. 5).An Interface is loaded in memory only when it is needed for the first time. 6).A Class, which implements an Interface, needs to provide the implementation of all the methods in that Interface. 7) If the Implementation for all the methods declared in the Interface are not provided , the 8lass itself has to declare abstract, other wise the Class will not compile. 9) If a class Implements two interface and both the Intfs have identical method declaration, it is totally valid. 10) If a class implements tow interfaces both have identical method name and argument list, but different return types, the code will not compile. 11)An Interface can’t be instantiated. Intf Are designed to support dynamic method resolution at run time. 12) An interface can not be native, static, synchronize, final, protected or private. 13) The Interface fields can’t be Private or Protected. 14) A Transient variables and Volatile variables can not be members of Interface. 15) The extends keyword should not used after the Implements keyword, the Extends must 16) always come before the Implements keyword. 17)A top level Interface can not be declared as static or final. 18) If an Interface species an exception list for a method, then the class implementing the interface need not declare the method with the exception list. 19) If an Interface can’t specify an exception list for a method, the class can’t throw an exception. 20) If an Interface does not specify the exception list for a method, he class can not throw any exception list. The general form of Interface is Access interface name { return-type method-name1(parameter-list); type final-varname1=value; } ----------------------- Marker Interfaces : Serializable, Clonable, Remote, EventListener,
Java.lang is the Package of all classes and is automatically imported into all Java Program Interfaces: Clonable , Comparable, Runnable Abstract Class: Abstract classes can be used to implement the inheritance relationship between the classes that belongs same hierarchy. 1).Classes and methods can be declared as abstract. 2).Abstract class can extend only one Class. 3).If a Class is declared as abstract , no instance of that class can be created. 4).If a method is declared as abstract, the sub class gives the implementation of that class. 5).Even if a single method is declared as abstract in a Class , the class itself can be declared as abstract. 6).Abstract class have at least one abstract method and others may be concrete. 7).In abstract Class the keyword abstract must be used for method. 8).Abstract classes have sub classes. 9).Combination of modifiers Final and Abstract is illegal in java.
Abstract Class means - Which has more than one abstract method which doesn’t have method body but at least one of its methods need to be implemented in derived Class.
The general form of abstract class is : abstract type name (parameter list);
The
Difference Between Interfaces And Abstract class ?
1).All the methods declared in the Interface are Abstract, where as abstract class must have atleast one abstract method and others may be concrete. 2).In abstract class keyword abstract must be used for method, where as in Interface we need not use the keyword for methods. 3).Abstract class must have Sub class, where as Interface can’t have sub classes. 4).An abstract class can extend only one class, where as an Interface can extend more than one.
What are access specifiers and access modifiers ?
Accesss specifiers Access modifiers Public Public Protected Abstract Private Final Static Volatile Constant Synchronized Transient Native
Public : The Variables and methods can be access any where and any package. Protected : The Variables and methods can be access same Class, same Package & sub class. Private : The variable and methods can be access in same class only.
Same class - Public, Protected, and Private Same-package & subclass - Public, Protected Same Package & non-sub classes - Public, Protected Different package & Sub classes - Public, Protected Different package & non- sub classes - Public
Identifiers : are the Variables that are declared under particular Datatype.
Literals: are the values assigned to the Identifiers.
Static : access modifier. Signa: Variable-Static int b; Method- static void meth(int x) 1)When a member is declared as Static, it can be accessed before any objects of its class are created and without reference to any object. Eg : main(),it must call before any object exit. 2)Static can be applied to Inner classes, Variables and Methods. 3)Local variables can’t be declared as static. 4)A static method can access only static Variables. and they can’t refer to this or super in any way. 5)Static methods can’t be abstract. 6)A static method may be called without creating any instance of the class. 7)Only one instance of static variable will exit any amount of class instances.
Final : access modifier 1)All the Variables, methods and classes can be declared as Final. 2)Classes declared as final class can’t be sub classed. 3)Method ‘s declared as final can’t be over ridden. 4)If a Variable is declared as final, the value contained in the Variable can’t be changed. 5)Static final variable must be assigned in to a value in static initialized block.
Transient : access modifier 1)Transient can be applied only to class level variables. 2)Local variables can’t be declared as transient. 3)During serialization, Object’s transient variables are not serialized. 4)Transient variables may not be final or static. But the complies allows the declaration and no compile time error is generated.
Volatile: access modifier 1)Volatile applies to only variables. 2)Volatile can applied to static variables. 3)Volatile can not be applied to final variables. 4)Transient and volatile can not come together. 5)Volatile is used in multi-processor environments.
Native : access modifier 1)Native applies to only to methods. 2)Native can be applied to static methods also. 3)Native methods can not be abstract. 4)Native methods can throw exceptions. 5)Native method is like an abstract method. The implementation of the abstract class and native method exist some where else, other than the class in which the method is declared.
Synchronized : access modifier 1)Synchronized keyword can be applied to methods or parts of the methods only. 2)Synchronize keyword is used to control the access to critical code in multi-threaded programming.
Declaration of access specifier and access modifiers
Class - Public, Abstract, Final Inner Class - Public, Protected, Private, Final, Static, Anonymous - Public, Protected, Private, Static Variable - Public, Protected, Private, Final, Static, Transient, Volatile, Native Method - Public, Protected, Private, Final, Abstract, Static, Native, Synchronized Constructor - Public, Protected, Private Free-floating code block - Static, Synchronized
Package : A Package is a collection of Classes Interfaces that provides a high-level layer of access protection and name space management.
Finalize( ) method: 1)All the objects have Finalize() method, this method is inherited from the Object class. 2)Finalize() is used to release the system resources other than memory(such as file handles& network connec’s. 3)Finalize( ) is used just before an object is destroyed and can be called prior to garbage collection. 4)Finalize() is called only once for an Object. If any exception is thrown in the finalize() the object is still eligible for garbage collection. 5)Finalize() can be called explicitly. And can be overloaded, but only original method will be called by Ga-collect. 6)Finalize( ) may only be invoked once by the Garbage Collector when the Object is unreachable. 7)The signature finalize( ) : protected void finalize() throws Throwable { }
Constructor( ) : 1)A constructor method is special kind of method that determines how an object is initialized when created. 2)Constructor has the same name as class name. 3)Constructor does not have return type. 4)Constructor cannot be over ridden and can be over loaded. 5)Default constructor is automatically generated by compiler if class does not have once. 6)If explicit constructor is there in the class the default constructor is not generated. 7)If a sub class has a default constructor and super class has explicit constructor the code will not compile.
Object : Object is a Super class for all the classes. The methods in Object class as follows. Object clone( ) final void notify( ) Int hashCode( ) Boolean equals( ) final void notify( ) Void finalize( ) String toString( ) Final Class getClass( ) final void wait( ) Class : The Class class is used to represent the classes and interfaces that are loaded by the JAVA Program.
Character : A class whose instances can hold a single character value. This class also defines handy methods that can manipulate or inspect single-character data.
constructors
and methods provided by the
String:
String is Immutable and String Is a final class. The
One accessor method that you
can use with both strings and string buffers is the toString( ) equals( ) indexOff( ) LowerCase( ) charAt( ) compareTo( ) lastIndexOff( ) UpperCase( ) getChars( ) subString( ) trim( ) getBytes( ) concat( ) valueOf( ) toCharArray( ) replace( ) ValueOf( ) : converts data from its internal formate into human readable formate.
String Buffer
: Is Mutable , The
In addition to
The methods in StringBuffer Class:- length( ) append( ) replace( ) charAt( ) and setCharAt( ) capacity( ) insert( ) substring( ) getChars( ) ensureCapacity( ) reverse( ) setLength( ) delete( )
Wraper Classes : are the classes that allow primitive types to be accessed as Objects. These classes are similar to primitive data types but starting with capital letter. Number Byte Boolean Double Short Character Float Integer Long primitive Datatypes in Java : According to Java in a Nutshell, 5th ed boolean, byte, char, short, long float, double, int.
Float class : The Float and Double provides the methods isInfinite( ) and isNaN( ). isInfinite( ) : returns true if the value being tested is infinetly large or small. isNaN( ) : returns true if the value being tested is not a number.
Character class : defines forDigit( ) digit( ) . ForDigit( ) : returns the digit character associated with the value of num. digit( ) : returns the integer value associated with the specified character (which is presumably) according to the specified radix.
String Tokenizer : provide parsing process in which it identifies the delimiters provided by the user, by default delimiters are spaces, tab, new line etc., and separates them from the tokens. Tokens are those which are separated by delimiters.
Observable Class: 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. Observer interface : is implemented by objects that observe Observable objects.
Instanceof( ) :is used to check to see if an object can be cast into a specified type with out throwing a cast class exception.
IsInstanceof( ) : determines if the specified Object is assignment-compatible with the object represented by this class. This method is dynamic equivalent of the Java language instanceof operator. The method returns true if the specified Object argument is non-null and can be cast to the reference type represented by this Class object without raising a ClassCastException. It returns false otherwise.
Garbage
Collection
: When an object is no longer referred to by any variable, java automatically reclaims
memory used by that object. This is
known as garbage collection.
this() : can be used to invoke a constructor of the same class. super() :can be used to invoke a super class constructor.
Inner
class
: classes defined in other classes, including those defined in methods are called
inner classes. An inner class can have
any accessibility including private. Anonymous class : Anonymous class is a class defined inside a method without a name and is instantiated and declared in the same place and cannot have explicit constructors. What is reflection API? How are they implemented Reflection package is used mainlyfor the purpose of getting the class name. by useing the getName method we can get name of the class for particular application. Reflection is a feature of the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program.
What is heap in Java JAVA is fully Object oriented language. It has two phases first one is Compilation phase and second one is interpratation phase. The Compilation phase convert the java file to class file (byte code is only readable format of JVM) than Intepratation phase interorate the class file line by line and give the proper result.
main( ) : is the method where Java application Begins. String args[ ] : receives any command line argument during runtime. System : is a predefined Class that provides access to the System. Out : is output stream connected to console. Println :displays the output.
Downcasting : is the casting from a general to a more specific type, i.e casting down the hierarchy. Doing a cast from a base class to more specific Class, the cast does;t convert the Object, just asserts it actually is a more specific extended Object.
Upcasting : byte can take Integer values.
Collections
Collections : A collection allows a group of objects to be treated as a single unit. collection define a set of core Interfaces as follows.
Collection Map Hash Map class Hash Table class
Set Hash set List Array List Sorted set Tree set Vector List Linked List Sorted map Tree Map class Collection Interface : The CI is the root of collection hierarchy and is used for common functionality across all collections. There is no direct implementation of Collection Interface.
Set Interface: extends Collection Interface. The Class Hash set implements Set Interface. 1.Is used to represent the group of unique elements. 2.Set stores elements in an unordered way but does not contain duplicate elements.
Sorted set : extends Set Interface. The class Tree Set implements Sorted set Interface. 1.It provides the extra functionality of keeping the elements sorted. 2.It represents the collection consisting of Unique, sorted elements in ascending order.
List : extends Collection Interface. The classes Array List, Vector List & Linked List implements List Interface. 1.Represents the sequence of numbers in a fixed order. 2.But may contain duplicate elements. 3.Elements can be inserted or retrieved by their position in the List using Zero based index. 4.List stores elements in an ordered way.
Map Interface:basic Interface.The classesHash Map & Hash Table implements Map interface. 1.Used to represent the mapping of unique keys to values. 2.By using the key value we can retrive the values. Two basic operations are get( ) & put( ) .
Sorted Map : extends Map Interface. The Class Tree Map implements Sorted Map Interface. 1.Maintain the values of key order. 2.The entries are maintained in ascending order.
Collection classes: Abstract Collection
Abstract List Abstract Set Abstract Map <
Abstract Array List Hash Set Tree Set Hash Map Tree Map Sequential List
Linked List
List Map | | Abstract List Dictonary| | Vector HashTable | | Stack Properities HashSet : Implements Set Interface. HashSet hs=new HashSet( ); The elements are not stored in sorted order. hs.add(“m”);
TreeSet : Implements Sorted set Interface. TreeSet ts=new TreeSet( ); 1.The elements are stored in sorted ascending order. ts.add(“H”); 2.Access and retrieval times are quit fast, when storing a large amount of data.
Vector : Implements List Interface. 1.Vector implements dynamic array. Vector v = new vector( ); 2.Vector is a growable object. V1.addElement(new Integer(1)); 3.Vector is Synchronized, it can’t allow special characters and null values. 4.All vector starts with intial capacity, after it is reached next time if we want to store object in vector, the vector automatically allocates space for that Object plus extra room for additional Objects.
ArrayList : Implements List Interface. 1.Array can dynamically increase or decrease size. ArrayList a1=new ArrayList( ); 2.Array List are ment for Random ascessing. A1.add(“a”); 3.Array List are created with intial size, when the size is increased, the collection is automatically enlarged. When an Objects are removed, the array may be shrunk.
Linked List : Implements List Interface. 1.Inserting or removing elements in the middle of the array. LinkedList l1=new LinkedList( ); 2.Linked list are meant for Sequential accessing. L1.add(“R”); 3.Stores Objects in a separate link.
Map Classes: Abstract Map; Hash Map ; Tree Map Hash Map : Implements Map Interface. Hashmap() , Hashmap(Map m), Hashmap(int capacity) 1.The Elements may not in Order. 2.Hash Map is not synchronized and permits null values 3.Hash Map is not serialized. Hashmap hm = new HashMap( ); 4.Hash Map supports Iterators. hm.put(“Hari”,new Double(11.9));
Hash Table : Implements Map Interface. 1.Hash Table is synchronized and does not permit null values. 2.Hash Table is Serialized. Hashtable ht = new Hashtable( ); 3.Stores key/value pairs in Hash Table. ht.put(“Prasadi”,new Double(74.6)); A Hash Table stores information by using a mechanism called hashing. In hashing the informational content of a key is used to determine a unique value, called its Hash Code. The Hash Code is then used as the index at which the data associated with the key is stored. The Transformation of the key into its Hash Code is performed automatically- we never see the Hash Code. Also the code can’t directly index into h c.
Tree Map : Implements Sorted Set Interface. TreeMap tm=new TreeMap( ); 1.The elements are stored in sorted ascending order. tm.put( “Prasad”,new Double(74.6)); 2.Using key value we can retrieve the data. 3.Provides an efficient means of storing key/value pairs in sorted order and allows rapid retrivals.
Iterator: Each of collection class provided an iterator( ). By using this iterator Object, we can access each element in the collection – one at a time. We can remove() ; Hashnext( ) – go next; if it returns false –end of list.
Iterarator Enumerator Iterator itr = a1.iterator( ); Enumerator vEnum = v.element( ); While(itr.hashNext( )) System.out.println(“Elements in Vector :”); { while(vEnum.hasMoreElements( ) ) Object element = itr.next( ); System.out.println(vEnum.nextElement( ) + “ “); System.out.println(element + “ “); } Collections 1.Introduction 2.Legacy Collections 1. The Enumeration Interface 2. Vector 3. Stack 4. Hashtable 5. Properties 3.Java 2 Collections 1. The Interfaces of the collections framework 2. Classes in the collections framework 3. ArrayList & HashSet 4. TreeSet & Maps Introduction :
1.Does your class need a way to easily search through thousands of items quickly? • Does it need an ordered sequence of elements and the ability to rapidly insert and remove elements in the middle of the sequence?• Does it need an array like structure with random-access ability that can grow at runtime?
List Map | | Abstract List Dictonary| | Vector HashTable | | Stack Properities
The Enumeration Interface :
1.enumerate (obtain one at a time) the elements in a collection of objects. specifies two methods : boolean hasMoreElements() : Returns true when there are still more elements to extract, and false when all of the elements have been enumerated. Object nextElement() : Returns the next object in the enumeration as a generic Object reference.
VECTOR : 1.Vector implements dynamic array. Vector v = new vector( ); 2.Vector is a growable object. V1.addElement(new Integer(1)); 3.Vector is Synchronized, it can’t allow special characters and null values. 4.Vector is a variable-length array of object references. 5.Vectors are created with an initial size. 6.When this size is exceeded, the vector is automatically enlarged. 7.When objects are removed, the vector may be shrunk.
Constructors : Vector() : Default constructor with initial size 10. Vector(int size) : Vector whose initial capacity is specified by size. Vector(int size,int incr) :Vector whose initialize capacity is specified by size and whose increment is specified by incr. Methods : final void addElement(Object element) : The object specified by element is added to the vector. final Object elementAt(int index) : Returns the element at the location specified by index. final boolean removeElement(Object element) : Removes element from the vector final boolean isEmpty() : Returns true if the vector is empty, false otherwise. final int size() : Returns the number of elements currently in the vector. final boolean contains(Object element) : Returns true if element is contained by the vector and false if it is not.
STACK : •Stack is a subclass of Vector that implements a standard last-in, first-out stack Constructor : Stack() Creates an empty stack.
Methods : Object push(Object item) : Pushes an item onto the top of this stack. Object pop() : Removes the object at the top of this stack and returns that object as the value of this function. An EmptyStackException is thrown if it is called on empty stack. boolean empty() : Tests if this stack is empty. Object peek() : Looks at the object at the top of this stack without removing it from the stack. int search(Object o) : Determine if an object exists on the stack and returns the number of pops that would be required to bring it to the top of the stack.
HashTable : 1.Hash Table is synchronized and does not permit null values. 2.Hash Table is Serialized. Hashtable ht = new Hashtable( ); 3.Stores key/value pairs in Hash Table. ht.put(“Prasadi”,new Double(74.6)); 4.Hashtable is a concrete implementation of a Dictionary. 5.Dictionary is an abstract class that represents a key/value storage repository. 6.A Hashtable instance can be used store arbitrary objects which are indexed by any other arbitrary object. 7.A Hashtable stores information using a mechanism called hashing. 8.When using a Hashtable, you specify an object that is used as a key and the value (data) that you want linked to that key.
Constructors : Hashtable() Hashtable(int size)
Methods : Object put(Object key,Object value) : Inserts a key and a value into the hashtable. Object get(Object key) : Returns the object that contains the value associated with key.
boolean contains(Object value) : Returns true if the given value is available in the hashtable. If not, returns false. boolean containsKey(Object key) : Returns true if the given key is available in the hashtable. If not, returns false. Enumeration elements() : Returns an enumeration of the values contained in the hashtable. int size() : Returns the number of entries in the hashtable.
Properties
1.Properties is a subclass of Hashtable 2.Used to maintain lists of values in which the key is a String and the value is also a String 3. Constructors Properties() Properties(Properties propDefault) : Creates an object that uses propDefault for its default value. Methods : String getProperty(String key) : Returns the value associated with key.
Strng getProperty(String key, String defaultProperty) : Returns the value associated with key. defaultProperty is returned if key is neither in the list nor in the default property list . Enumeration propertyNames() : Returns an enumeration of the keys. This includes those keys found in the default property list.
The Interfaces in Collections Framework
Collection Map Iterator
Set List SortedMap ListIterator | SortedSet
Collection : 1.A collection allows a group of objects to be treated as a single unit. 2.The Java collections library forms a framework for collection classes. 3.The CI is the root of collection hierarchy and is used for common functionality across all collections. 4.There is no direct implementation of Collection Interface. 5.Two fundamental interfaces for containers: 6.Collection boolean add(Object element) : Inserts element into a collection
Set Interface: extends Collection Interface. The Class Hash set implements Set Interface. 1.Is used to represent the group of unique elements. 2.Set stores elements in an unordered way but does not contain duplicate elements. 3.identical to Collection interface, but doesn’t accept duplicates.
Sorted set : extends Set Interface. The class Tree Set implements Sorted set Interface. 1.It provides the extra functionality of keeping the elements sorted. 2.It represents the collection consisting of Unique, sorted elements in ascending order. 3.expose the comparison object for sorting.
List Interface :1.ordered collection – Elements are added into a particular position. 2.Represents the sequence of numbers in a fixed order. 3.But may contain duplicate elements. 4.Elements can be inserted or retrieved by their position in the List using Zero based index.
boolean put(Object key, Object value) : Inserts given value into map with key Object get(Object key) : Reads value for the given key.
Tree Map Class: Implements Sorted Set Interface. 1. The elements are stored in sorted ascending order. 2. Using key value we can retrieve the data. 3. Provides an efficient means of storing key/value pairs in sorted order and allows rapid retrivals.
TreeMap tm=new TreeMap( ); tm.put( “Prasad”,new Double(74.6));
The Classes in Collections Framework
Abstract Collection
Abstract List Abstract Set Abstract Map
Abstract Array List Hash Set Tree Set Hash Map Tree Map Sequential
Linked List
ArrayLsist
HashSet
HashSet(int initialCapacity) HashSet(int initialCapacity,float loadFactor) loadFactor is a measure of how full the hashtable is allowed to get before its capacity is automatically increased Use Hashset if you don’t care about the ordering of the elements in the collection
TreeSet
HashMap
2. The Elements may not in Order. 3. Hash Map is not synchronized and permits null values 4. Hash Map is not serialized.
TreeMap
How are memory leaks possible in Java If any object variable is still pointing to some object which is of no use, then JVM will not garbage collect that object and object will remain in memory creating memory leak
What are the differences between EJB and Java beans the main difference is Ejb componenets are distributed which means develop once and run anywhere. java beans are not distributed. which means the beans cannot be shared .
What would happen if you say this = null this will give a compilation error as follows cannot assign value to final variable this
Will there be a performance penalty if you make a method synchronized? If so, can you make any design changes to improve the performance yes.the performance will be down if we use synchronization. one can minimise the penalty by including garbage collection algorithm, which reduces the cost of collecting large numbers of short- lived objects. and also by using Improved thread synchronization for invoking the synchronized methods.the invoking will be faster.
How would you implement a thread pool public class ThreadPool extends java.lang.Object implements ThreadPoolInt This class is an generic implementation of a thread pool, which takes the following input a) Size of the pool to be constructed b) Name of the class which implements Runnable (which has a visible default constructor) and constructs a thread pool with active threads that are waiting for activation. once the threads have finished processing they come back and wait once again in the pool. This thread pool engine can be locked i.e. if some internal operation is performed on the pool then it is preferable that the thread engine be locked. Locking ensures that no new threads are issued by the engine. However, the currently executing threads are allowed to continue till they come back to the passivePool
How does serialization work Its like FIFO method (first in first out)
How does garbage collection work There are several basic strategies for garbage collection: reference counting, mark-sweep, mark-compact, and copying. In addition, some algorithms can do their job incrementally (the entire heap need not be collected at once, resulting in shorter collection pauses), and some can run while the user program runs (concurrent collectors). Others must perform an entire collection at once while the user program is suspended (so-called stop-the-world collectors). Finally, there are hybrid collectors, such as the generational collector employed by the 1.2 and later JDKs, which use different collection algorithms on different areas of the heap
How would you pass a java integer by reference to another function Passing by reference is impossible in JAVA but Java support the object reference so. Object is the only way to pass the integer by refrence. What is the sweep and paint algorithm The painting algorithm takes as input a source image and a list of brush sizes. sweep algo is that it computes the arrangement of n lines in the plane ... a correct algorithm,
Can a method be static and synchronized no a static mettod can't be synchronised
Do multiple inheritance in Java Its not possible directly. That means this feature is not provided by Java, but it can be achieved with the help of Interface. By implementing more than one interface.
What is data encapsulation? What does it buy you The most common example I can think of is a javabean. Encapsulation may be used by creating 'get' and 'set' methods in a class which are used to access the fields of the object. Typically the fields are made private while the get and set methods are public. dEncapsulation can be used to validate the data that is to be stored, to do calculations on data that is stored in a field or fields, or for use in introspection (often the case when using javabeans in Struts, for instance).
What is reflection API? How are they implemented Reflection package is used mainlyfor the purpose of getting the class name. by using the getName method we can get name of the class for particular application . Reflection is a feature of the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. What are the primitive types in Java According to Java in a Nutshell, 5th ed boolean, byte, char, short, long float, double, int Is there a separate stack for each thread in Java No What is heap in Java JAVA is fully Object oriented language. It has two phases first one is Compilation phase and second one is interpratation phase. The Compilation phase convert the java file to class file (byte code is only readable format of JVM) than Intepratation phase interorate the class file line by line and give the proper result.
In Java, how are objects / values passed around In Java Object are passed by reference and Primitive data is always pass by value Do primitive types have a class representation Primitive data type has a wrapper class to present. Like for int - Integer , for byte Byte, for long Long etc ...
How all can you free memory With the help of finalize() method. If a programmer really wants to explicitly request a garbage collection at some point, System.gc() or Runtime.gc() can be invoked, which will fire off a garbage collection at that time. Does java do reference counting It is more likely that the JVMs you encounter in the real world will use a tracing algorithm in their garbage-collected heaps What does a static inner class mean? How is it different from any other static member A static inner class behaves like any ``outer'' class. It may contain methods and fields. It is not necessarily the case that an instance of the outer class exists even when we have created an instance of the inner class. Similarly, instantiating the outer class does not create any instances of the inner class. The methods of a static inner class may access all the members (fields or methods) of the inner class but they can access only static members (fields or methods) of the outer class. Thus, f can access the field x, but it cannot access the field y.
How do you declare constant values in java Using Final keyword we can declare the constant values How all can you instantiate final members Final member can be instantiate only at the time of declaration. null
How is serialization implemented in Java A particular class has to implement an Interface java.io.Serializable for implementing serialization. When you have an object passed to a method and when the object is reassigned to a different one, then is the original reference lost No Reference is not lost. Java always passes the object by reference, now two references is pointing to the same object. What are the different kinds of exceptions? How do you catch a Runtime exception There are 2 types of exceptions. 1. Checked exception 2. Unchecked exception. Checked exception is catched at the compile time while unchecked exception is checked at run time. 1.Checked Exceptions : Environmental error that cannot necessarily be detected by testing; e.g. disk full, broken socket, database unavailable, etc. 2. Unchecked exception. Errors : Virtual machine error: class not found, out of memory, no such method, illegal access to private field, etc. Runtime Exceptions :Programming errors that should be detected in testing: index out of bounds, null pointer, illegal argument, etc. Checked exceptions must be handled at compile time. Runtime exceptions do not need to be. Errors often cannot be
What are the differences between JIT and HotSpot The Hotspot VM is a collection of techniques, the most significant of which is called "adaptive optimization. The original JVMs interpreted bytecodes one at a time. Second-generation JVMs added a JIT compiler, which compiles each method to native code upon first execution, then executes the native code. Thereafter, whenever the method is called, the native code is executed. The adaptive optimization technique used by Hotspot is a hybrid approach, one that combines bytecode interpretation and run-time compilation to native code. Hotspot, unlike a regular JIT compiling VM, doesn't do "premature optimization"
What is a memory footprint? How can you specify the lower and upper limits of the RAM used by the JVM? What happens when the JVM needs more memory? when JVM needs more memory then it does the garbage collection, and sweeps all the memory which is not being used.
What are the disadvantages of reference counting in garbage collection? An advantage of this scheme is that it can run in small chunks of time closely interwoven with the execution of the program. This characteristic makes it particularly suitable for real-time environments where the program can't be interrupted for very long. A disadvantage of reference counting is that it does not detect cycles. A cycle is two or more objects that refer to one another, for example, a parent object that has a reference to its child object, which has a reference back to its parent. These objects will never have a reference count of zero even though they may be unreachable by the roots of the executing program. Another disadvantage is the overhead of incrementing and decrementing the reference count each time. Because of these disadvantages, reference counting currently is out of favor.
Is it advisable to depend on finalize for all cleanups The purpose of finalization is to give an opportunity to an unreachable object to perform any clean up before the object is garbage collected, and it is advisable.
can we declare multiple main() methods in multiple classes. ie can we have each main method in its class in our program? YES
|
||
| NEXT |