Tuesday, June 11, 2013

why we use abstract class?

Abstarct classes are meant for 'abstracting'.
means if some classes are having common behaviour, instead of writing evry time the same thing in each class, write that in one class and ask the other classes to use it[by making the classes as subclasses to the abstract class].
this is nothing but inheritance.
To summarise: 


Use abstract classes when you want default behaviour for some classes
Use interfaces when you want different behaviour different classes.

hope this helps you

Wednesday, June 5, 2013

JAVA Good blogs URL

1) http://javawithrealtimeexamples.blogspot.in

2) http://javatotalconcepts.blogspot.in/

3) http://javaedutech.blogspot.in/

java interview quetions and answers

1) Why pointeres are eliminated from java.?
Ans)     1.  Pointers lead to confusion for a programmer.
             2. Pointers may crash a program easily, for example , when we add two pointers,

                 the program  crashers immediately. 
             3. Pointers break security. Using pointers, harmful programs like Virus and 
                 other  hacking    programs can be developed. Because of the 
                 above reasons, pointers have been eliminated from java.

2) What is the difference between a function and a method.?
Ans). 

         A method is a function that is written in a class. We do not have functions in java;
         instead we have methods. This means whenever a function is written in java,it 
         should be written inside the class only. But if we take C++, we can write the funtions
         inside as well as outside the class . So in C++, they are called member funcitons and
         not  methods.

3) Which part of JVM will allocate the memory for a java program.?
Ans). 

          Class loader subsystem of JVM will allocate the necessary memory needed by the
          java program.

4). Which algorithm is used by garbage collector to remove the unused variables or
      objects from memory.?
Ans). Garbage collector uses many algorithems but the most commonly used algorithm

          is mark and sweep.
 

5). How can you call the garbage collector.?
Ans). Garbage collector is automatically invoked when the program is being run. 

           It can be also called by calling gc() method of Runtime class or System
           class in Java.

6) What is JIT Compiler ?
Ans). JIT compiler is the part of JVM which increases the speed of execution of a 

         Java program.

7)What is an API document ?
Ans). An API document is a .html file that contains description of all the features of a

         softwar, a product, or a technology. API document is helpful for the user to understand
         how to use the software or technology.

8) What is the difference between #include and import statement.?
Ans). #include directive makes the compiler go to the C/C++ standard library and copy 

         the code from the header files into the program. As a result, the program size
         increases, thus wasting memory and procssor’s time. import statement makes the
        JVM go to the  Java standard library, execute the code  there , and substitute the
         result into the  program.  Here, no code is copied and hence  no waste  of memory 
         or processor’s time.  so import is an efficient mechanism than  #include.

9)What is the difference between print( ) and println( ) method ?
Ans). Both methods are used to display the results on the monitor . print( ) method displays

         the result and then retains the cursor in the same line, next to the end of the result.
         println( ) displays the result and then throws the cursor to the next line.

10)What happens if String args[] is not written in main( ) method ?
Ans). When main( ) method is written without String args[] as:
          Public static void main( )
          The code will compile but JVM cannot run the code beause it cannot recognize the

          main( ) as the method from were it should start execution of the Java program. 
          Remember JVM always looks for main( ) method with string type array as parameter.

11) What is the difference between float and double?
Ans). Float can represent up to 7 digits accurately after decimal point, where as double can represent up
to 15 digits accurately after decimal point.
12)What is a Unicode system ?
Ans). Unicode system is an encoding standard that provides a unique number for every character, no
matter what the platform, program, orlanguage is. Unicode uses 2 bytes to represent a single character.
13) How are positive and negative numbers represented internally ?
Ans). Positive numbers are represented in binary using 1’s complement notation and negative numbers
are represented by using 2’s complement notation.
14) What is the difference between >> and >>> ?
Ans). Both bitwise right shift operator( >> ) and bitwise zero fill right shift operator( >>> ) are used to
shift the bits towards right. The difference is that >> will protect the sign bit whereas the >>> operator
will not protect the sign bit. It always fills 0 in the sign bit.
15) What are control statements ?
Ans). Control statements are the statements which alter the flow of execution and provide better control
to the programmer on the flow of execution. They are useful to write better and complex programs.
16) Out of do..while and while - - which loop is efficient ?
Ans). In a do..while loop, the statements are executed without testing the condition , the first time. From
the second time only the condition is observed. This means that the programmer does not have control
right from the beginning of its execution. In a while loop, the condition is tested first and then only the
statements are executed. This means it provides better control right from the beginnig. Hence, while loop
is move efficient than do.. while loop.
17) What is a collection ?
Ans). A collection represents a group of elements like integer values or objects. Examples for
collections are arrays and java.util_classes (stack, LinkedList, ;Vector, etc).
18)Why goto statements are not available in Java ?
Ans). Goto statements lead to confusion for a programmer. Especially in a large program, if several
goto statements are used, the programmer would be preplexed while understanding the flow from where
to where the control is jumping.
19) What is the difference between return and System.exit(0) ?
Ans). Return statement is used inside a method to come out of it. System.exit( 0) is used in any method
to come of the program.
20) What is the difference between System.out.exit(0) and System.exit(1) ?
Ans). System.exit(0) terminates the program normally. Whereas System.exit(1) terminates the program
because of some error encountered in the program.
21) What is the difference between System.out ,System.err and System.in?
Ans). System.out and System.err both represent the monitor by default and hence can be used to send
data or results to the monitor. But System.out is used to display normal messages and results whereas
System.err is used to display error messages and System.in represents InputStream object, which by
default represents standard input device, ie, keyboard.
22) On which memory, arrays are created in Java?
Ans). Arrays are created on dynamic memory by JVM. There is no question of static memory in Java;
every thing( variables, array, object etc.) is created on dynamic memory only.


23) Can you call the main( ) method of a class from another class ?
Ans). Yes , we can call the main( ) method of a class from another class using Classname.main( ) . At
the time of calling the main( ) method, we should pass a string type array to it.
24) Is String a class or data type ?
Ans). String is a class in java.lang package. But in Java, all classes are also considered as data types. So
we can take String as a data type also.
25) Can we call a class as a data type ?
Ans). Yes, a class is also called ‘ user-defined’ data type. This is because a use can dreate a class.
26) What is object reference ?
Ans). Object reference is a unique hexadecimal number representing the memory address of the object.
It is useful to access the members of the object.
27) What is difference between == and equals() while comparing strings ? which one is
reliable ?
Ans). = = operator compares the references of the sting objects. It does not compare the contents of the
objects. equals( ) method compares the contents. While comparing the strings, equals( ) method should
be used as it yields the correct result.
28) What is a string constant pool ?
Ans). Sring constant pool is a separate block of memory where the string objects are held by JVM. If a
sting object is created directly, using assignment operator as: String s1 = “Hello”,then it is stored in
string constant pool.
29) Explain the difference between the following two statements:
1. String s=”Hello”
2. String s = new String(“Hello”);
Ans). In the first statement, assignment operator is used to assign the string literal to the String variale
s. In this case, JVM first of all checks whether the same object is already available in the string constant
pol. If it is available , then it creates another reference to it. If the same object is not available , then it
creates another object with the content “ Hello “ and stores it into the string constant pool.
In the second statement, new operator is used to create the string object, in this case, JVM always creates
a new object without looking in the string constant pool.
30) What is the difference between String and StringBuffer classes?
Ans). String class objects are immutable and hence their contents cannot be modified. StringBuffer class
objects are mutable, so they can be modified. Moreover the methods that directly manipulate data of the
object are not available in String class. Such methods are available in StringBuffer class.
31) Are there any other classes whose objects are immutalbe ?
Ans). Yes, classes like Character, Byte, Integer, Float, Double, Long..called ‘wrapper classes’ are
created as ‘immutable’.Classes like Class, BigInteger, Big Decimal are also immutable.
32) What is the difference between StringBuffer and StringBuilder classes?
Ans). StringBuffer class is synchronized and StringBuilder is not. When the programmer wants to use
several threads, he should use StringBuffer as it gives reliable results . If only one thread is used.
StringBuilder is preferred, as it improves execution time.
33) What is object oriented approach ?
Ans). Object oriented programming approach is a programming methodology to design computer
programs using classes and objects.
34) What is the difference between a class and an object ?
Ans). A class is a model for creating objects and does not exist physically. An object is any thing that
exists physically.Both the classes and objects contain variables and methods.
35) What is encapsulation ?
Ans). Encapsulation is a mechanism where the data(varialbes) and the code(methods) that act on the
data will bind together. For ex,if we take a class, we write the variables and methods inside the class.
Thus, class is binding them together. So class is an example for encapsultion.
36) What is abstraction ?
Ans). Hiding the unnecessary data from the user and expose only needed data is of interest to the user.
A good example for abstraction is a car. Any car will have some parts like engine, radiator, mechanical
and electrical equipment etc. The user of the ca r (driver) should know how to drive the car and does not
require any knowledge of these parts. For example driver is never bothered about how the engine is
designed and the internal parts of the engine. This is why, the car manufacturers hide these parts from
the driver in a separate panel, generally at the front.
Example in java:
Class Bank
{
Private int accno;
Private String name;
Private float balance;
Private float profit;
Private float loan;
Public void desplay_to _clerk()
{
System.out.println(“Accno= “+accno);
System.out.println(“Name=” +name);
System.out.println(“Balance=”+balance);
}
}
37) What is Inheritance ?
Ans). It creates new classes from existing classes, so that the new classes will acquire all the features of
the existing classes is called inheritance. (or) Acquiring the all properties from base class to child class .
38) What is Polymorphism ?
Ans). The word ‘Polymorphism’ came from two Greek words ‘poly’ meaning ‘many’ and ‘morphs’
meaning ‘forms’ . Thus, polymorphism represents the ability to assume several different forms. In
programming, we can use a single variable to refer to objects of different types and thus, using that
variable we can call the methods of the different objects. Thus a method call can perform different tasks
depending on the type of the object.
39) What is the difference between object oriented programming launguages and object
based programming languages ?
Ans). Object oriented programming languages follow all the features of Object Oriented Programming
System(OOPS). Smalltalk, Simula-67,C++, Java are examples for OOPS languages.
Object based programming languages follow all the features of OOPS except Inheritance. For example,
JavaScript and VBScript will come under object based programming languages.
40) What is hash code ?
Ans). Hash code is unique identification number alloted to the objects by the JVM. This hash code
number is also called reference number which is created based on the location of the object in memory,
and is unique for all objects, except for String objects.
41)How can you find the hash code of an object ?
Ans). The hashCode( ) method of ‘Object’ class in java.lang.package is useful to find the hash code of
an object.
42) Can you declare a class as ‘private’ ?
Ans). No, if we declare a class as private , then it is not available to java compiler and hence a compile
time error occurs, But inner classes can be declared as private.
43) When is a constructor called, before or after creating the object ?
Ans). A Constructor is called concurrently when the object creation is going on. JVM first allocates
memory for the object and then executes the constructor to initialize the instance variables. By the time,
object creation is completed, the constructor execution is also completed.
44) What is the difference between default constructor and parameterized constructor?


Default constructor: Parameter constructor:
Default constructor is useful to initialize all objects with same data. Parameterized constructor is useful to initialize each object with different data.
Default constructor does not have any parameters. Parameterized constructor will have 1 or more parameteres
When data is not passed at the time of creating an object, default constructor is called. When data is passed at the time of creating an object parameterized constructor is called.

45) What is the difference between a constructor and a method ?


Constructors: Methods:
A constructor is used to initialize the instance variables of a class. A mehtod is used for any general purpose processing or calcultaions.
A constructor’s name and class name should be same. A mehtod’s name and class name can be same or different.
A constructor is called at the time of creating object. A method can be called after creating the object.
A constructor is called only once per object. A method can be called several times on the object.



46) What is constructor overloading ?
Ans). Writing two or more constructors with the same name but with difference in the parameters is
called constructor overloading. Such constructors are useful to perform different tasks.
47) What are instance methods ?
Ans). Instance methods are the methods which act on the instance variables of the class. To call the
instance methods , we should use the form; objectname.methodname( ).
Ex: double x = obj.sum( );
48) What are static methods ?
Ans). Static methods are the methods which do not act upon the instance variables of a class. Static
methods are declared as ‘static’.
49) What is the difference between instance variables and class variables(static
variables) ?
Ans). 1. An Instance variable is a variable whose separate copy is availabe to each object. A class
variable is a variable whose single copy in memory is shared by all objects.
2. Instance variables are created in the objects on heap memory. Class variables are stored on method
area.
50) Why instance Variables are not available to static methods ?
Ans). After executing static methods, JVM creates the objects. So the instance variables of the objects
are not available to static methods.
51) Is it possible to compile and run a Java program without writing main( ) method ?
Ans). Yes , it is possible by using a static block in the Java program.
52) How are objects are passed to methods in Java ?
Ans). Premitive data types, objects, even object references – every thing is passed to methods using
‘pass by value’ or ‘call by value’ concept. This means their bit by bit copy is passes to the methods.
53) What are factory methods ?
Ans). A factory methods is a method that creates and returns an object to the class to which it
belongs. A single factory method replaces several constructors in the class by accepting different options
from the user, while creating the object.
54) In how many ways can you create an object in Java ?
Ans). There are four ways of creating objects in Java:
1. Using new operator
Employee obj = new Employee( );
Here , we are creating Employee class object ‘obj’ using new operator.
2. Using factory methods:
Number Format obj = NumberFormat. getNumberInstance( );
Here, we are creating NumberFormat object using the factory method getNumberInstance( )
3. Using newInstance( ) method. Here we should follow tow steps, as:
(a) First, store the class name ‘Employee’ as a string into an object. For this purpose, factory
metod forName( ) of the class ‘Class’ will be useful:
Class c = Class.forName(“Employee”);
We should note that there is a class with the name ‘Class’ in java.lang package.
(b) Next, create another object to the class whose name is in the object c. For this purpose , we
need newInstance( ) method of the class ‘Class’ as:
Employee obj = ( Employee)c.newInstance( );
4. By cloning an already available object, we can create another object. Creating exact copy of an
existing object is called ‘cloning’.
Employee obj1 = new Employee ( );
Employee obj2 = (Employee)obj1.clone( );
Earlier, we created obj2 by cloning the Employee object obj1.clone( ) method of Object class is
used to clone object.We should note that there is a class by the name ‘Object’ in java.lang
package.
55) What is object graph ?
Ans). Object graph is a graph showing relationship between different objects in memory.
56) What is anonymous inner class ?
Ans). It is an inner class whose name is not written in the outer class and for which only one object is
created.
57) What is Inheritance ?
Ans). Deriving new classes from existing classes such that the new classes acquire all the features of
existing classes is called inheritance.
58) Why super class members are available to sub class ?
Ans). Because, the sub class object contains a copy of super class object.
59) What is the advantage of inheritance ?
Ans). In inheritance a programmer reuses the super class code without rewriting it, in creation of sub
classes So, developing the classes becomes very easy. Hence, the programmer’s productivity is increased.
60) Why multiple inheritance is not available in Java ?
Ans). Multiple inheritance is not available in Java for the following reasons:
1. It leads to confusion for a Java program.
2. The programmer can achieve multiple inheritance by using interfaces.
3. The programmer can achieve multiple inheritance by repeatedly using single inheritance.
61) How many types of inheritance are there ?
Ans). There are two types of inheritances single and multiple. All other types are mere combinations
of these two.However, Java supports only single inheritance.
62) What is coercion ?
Ans). Coercion is the automatic conversion between different data types done by the compiler.
63) What is conversion ?
Ans). Conversion is an explicit change in the data type specified by the operator.
64) What is method signature ?
Ans). Method signature represents the method name along with method parmeters.
65) What is method overloading ?
Ans). Writing two or more methods in the same class in such a way that each mehtod has same name
but with different method signatures – is called method overloading.
66) What is method overriding ?
Ans). Writing two or more methods in super and sub classes such that the methods have same name
and same signature is called method overriding.
67) What is the difference between method overloading and method overriding ?


MethodOverloading: Method Overriding:
Writing two or more methods with the same name but with different signatures is called method overloading. Writing two or more methods with the same name and same signatures is called method overriding.
Method overloading is done in the same class. Method overriding is done in super and sub classes.
In method overloading, method return type can be same or different. In method overriding method return type should also be same.
JVM decides which method is called depending on the difference in the method signatures. JVM decides which method is called depending on the data type (class) of the object used to call the method.
Method overloading is done when the programmer wants to extend the already available features. Method overriding is done when the programmer wants to provide a different implementation(body) for the same feature.
Method overloading is code refinement. Same method is refined to perform a different task. Method overriding is code replacement. The sub class method overrides(replaces) the super class method.
68) Can you override private methods ?
Ans). No, private methods are not available in the sub classes, so they cannot be overriden.
69) Can we take private methods and final methods as same ?
Ans). Yes. The Java compiler assigns the value for the private methods at the time of compilation. Also
private methods can not be modified at run time. This is the same cases with final methods also. Neither
the private methods nor the final methods can be overriden . So, private methods can be taken as final
methods.
70) What is final ?
Ans). ‘final’ keyword is used in two ways:
 It is used to declare constants as:
Final double PI = 3.14159; // PI is constant
It is used to prevent inheritance as:
 Final class A // sub class to A cannot be created.
71) What is the difference between dynamic polymorphism and static polymorphism ?
Ans). Dynamic polymorphism is the polymorphism existed at runtime. Here, Java compiler does not
understand which method is called at compilation time. Only JVM decides which method is called at
runtime. Method overloading and method overriding using instance methods are the examples for
dynamic polymorphism.
Static polymorphism is the polymorphism exhibited at compile time. Here, Java compiler knows which
method is called. Method overloading and method overriding using static methods; method overriding
using private or final methods are examples for static polymorphism.
72) What is difference between primitive data types and advanced data types ?
Ans). Primitive data types represent single values. Advanced data types represent a group of values.
Also methods are not available to handle the primitive data types. In case of advanced data types,
methods are available to perform various operations.
73) What is implicit casting ?
Ans). Automatic casting done by the Java compiler internally is called implicit casting . Implicit
casting is done to converty a lower data type into a higher data type.
74) What is explicit casting ?
Ans). The cating done by the programmer is called explicit cating. Explicit casting is compulsory while
converting from a higher data type to a lower data type.
75) What is generalization and specialization ?
Ans). Generalization ia a phenomenon wher a sub class is prompted to a super class, and hence
becomes more general. Generalization needs widening or up-casting. Specialization is phenomenon
where a super class is narrowed down to a sub class. Specialization needs narrowing or down-casting.
76) What is widening and narrowing ?
Ans). Converting lower data type into a higher data type is called widening and converting a higher
data type into a lower type is called narrowing. Widening is safe and hence even if the programmer does
not use cast operator, the Java compiler does not flag any error. Narrowing is unsafe and hence the
programmer should explicitly use cast operator in narrowing.
77) Which method is used in cloning ?
Ans). clone( ) method of Object class is used in cloning.
78) What do you call the interface without any members ?
Ans). An interface without any members is called marking interface or tagging interface. It marks the
class objects for a special purpose. For example, Clonable(java.lang) and Serializable(java.io) are two
marking interfaces. Clonable interface indicates that a particular class objects are cloneable while
Serializable interface indicates that a particular class objects are serializable.
79) What is abstract method ?
Ans). An abstract method is a method without method body. An abstract method is written when the
same method has to perform difference tasks depending on the object calling it.
80) What is abstract class ?
Ans). An abstract class is a class that contains 0 or more abstract methods.
81) How can you force your programmers to implement only the features of your class ?
Ans). By writing an abstract class or an interface.
82) Can you declare a class as abstract and final also ?
Ans). No, abstract class needs sub classes. final key word represents sub classes which can not be
created. So, both are quite contradictory and cannot be used for the same class.
83) What is an interface ?
Ans). An interface is a specification of method prototypes, All the methods of the interface are public
and abstract.
84) Why the methods of interface are public and abstract by default ?
Ans). Interface methods are public since they should be available to third party vendors to provide
implementation. They are abstract because their implementation is left for third party vendors.
85) Can you implement one interface from another ?
Ans). No, we can’t implementing an interface means writing body for the methods. This can not be
done again in an interface, since none of the methods of the interface can have body.
86) Can you write a class within an interfae ?
Ans). Yes, it is possible to write a class within an interface.
87)Explain about interfaces ?
Ans). * An interface is a specification of method prototypes, before we proceed furthur, written in the
interface without mehtod bodies.
*An interface will have 0 or more abstract methods which are all public and abstract by default.
* An interface can have variables which are public static and final by default. This means all the
variables of the interface are constants.
88) What is the difference between an abstract class and an interface ?


Abstract class Interface
An abstract class is written when there are some common features shared by all the objects. An interface is written when all the features are implemented differently in different objects.
When an abstract class is written, it is the duty of the programmer to provide sub classes to it.
An interface is written when the programmer wants to leave the implementation to the third party vendors.
An abstract class contains some abstract methods and also some concrete methods.
An interface contains only abstract methods.
An abstract class contain instance variables also. An interface can not contain instance variables. It contains only constants.
All the abstract methods of the abstract class should be implemented in its sub classes.
All the (abstract) methods of the interface should be implemented in its implementation classes.
Abstract class is declared by using the keyword abstract.
Interface is declared using the keyword interface.
89)A programmer is writing the following statements in a program:
1. import java.awt.*;
2. import java.awt.event.*;
Should he write both the statements in his program or the first onw is enough ?
Ans). event is a sub package of java.awt package. But, when a package is imported, its sub packages are
not automatically imported into a program. So, for every package or sub package, a separate import
statement should be written. Hence if the programmer wants the classes and interfaces of both the
java.awt and java.awt.event packages, then he should both the preceding statements in his program.
90) How can you call the garbage collector ?
Ans). We can call garbage collector of JVM to delete any unused variables and unreferenced objects
from memory using gc( ) method. This gc( ) method appears in both Runtime and System classes of
java.lang package. For example, we can call it as:
System.gc( );
Runtime.getRuntime( ).gc( );
91) What is the difference between the following two statements.
1. import pack.Addition;
2. import pack.*;
Ans) . In statement 1, only the Addition class of the package pack is imported into the program and in
statement 2, all the classes and interfaces of the package pack are available to the program.
If a programmer wants to import only one class of a package say BufferedReader of java.io package,
we can write import java.io.BufferedReader;
92) What is the differentiate between .ear, .jar and .war files.?
Ans). These files are simply zipped file using java jar tool. These files are created for different purposes.
Here is the description of these files:
.jar files: These files are with the .jar extenstion. The .jar files contains the libraries, resources and
accessories files like property files.
.war files: These files are with the .war extension. The war file contains the web application that can be
deployed on the any servlet/jsp container. The .war file contains jsp, html, javascript and other files for
necessary for the development of web applications.
.ear files: The .ear file contains the EJB modules of the application.
93) What is CLASSPATH ?
Ans) . The CLASSPATH is an environment variable that tells the Java compiler where to look for class
files to import. CLASSPATH is generally set to a directory or a JAR(Java Archive)file.
94) What is a JAR file ?
Ans) A Java Archive file (JAR) is a file that contains compressed version of several .class files, audio
files, image files or directories. JAR file is useful to bundle up several files related to a project and use
them easily.
95) What is the scope of default acess specifier ?
Ans). Default members are available within the same package, but not outside of the package. So their
scope is package scope.
96)What happens if main( ) method is written without String args[ ] ?
Ans). The code compiles but JVM cannot run it, as it cannot see the main( ) method with String args[ ].
97). What are checked exceptions ?
Ans). The exceptions that are checked at compilation-time by the Java compiler are called ‘checked
exceptions’. The exceptions that are checked by the JVM are called ‘unchecked exceptions’.
98). What is Throwable ?
Ans). Throwable is a class that represents all errors and exceptions which may occur in Java.
99). Which is the super class for all exceptions ?
Ans). Exception is the super class of all exceptions in Java.
100). What is the difference between an exception and an error ?
Ans). An exception is an error which can be handled. It means when an exception happens, the
programmer can do something to avoid any harm. But an error is an error which cannot be handled, it
happens and the programmer cannot do any thing.
101). What is the difference between throws and throw ?
Ans). throws clause is used when the programmer does not want to handle the exception and throw it out
of a method. throw clause is used when the programmer wants to throw an exception explicitly and wants
to handle it using catch block. Hence, throws and throw are contracictory.
102). Is it possible to re-throw exceptions ?
Ans). Yes, we can re-throw an exception from catch block to another class where it can be handled.
103). Why do we need wrapper classes ?
1. They convert primitive data types into objects and this is needed on Internet to mommunicate between
two applications.
2. The classes in java.util package handle only objects and hence wrapper classes help in this case also.
104). Which of the wrapper classes contains only one constructor ? (or) Which of the wrapper classes
does not contain a constructor with String as parameter ?
Ans). Character.
105). What is unboxing ?
Ans). Converting an object into its corresponding primitive datatype is called unboxing.
106). What happens if a string like “ Hello” is passed to parseInt ( ) method ?
Ans). Ideally a string with an integer value should be passed to parseInt ( ) method. So, on parsing
“Hello”, an exception called “NumberFormatException’ occurs since the parseInt( ) method cannot
convert the given string “Hello” into an integer value.
107).What is a collection framework ?
Ans). A collection framework is a class library to handle groups of objects. Collection framework is
implemented in java.util.package.
108). Does a collection object store copies of other objects or their references ?
Ans). A Collection object stores references of other objects.
109). Can you store a primitive data type into a collection ?
Ans). No, Collections store only objects.
110). What is the difference between Iterator and ListIterator ?
Ans). Both are useful to retreive elements from a collection. Iterator can retrieve the elements only in
forward direction. But Listener can retrieve the elements in forward and backward direction also. So
ListIterator is preferred to Iterator.
111). What is the difference between Iterator and Enumeration ?
Ans). Both are useful to retreive elements from a collection. Iterator has methods whose names are easy
to follow and Enumeration methods are difficult to remember. Also Iterator has an option to remove
elements from the collection which is not available in Enumeration. So, Iterator is preferred to
Enumeration.
112). What is the difference between a Stack and LinkedList ?
Ans). 1. A Stack is generally used for the purpose of evaluation of expression. A LinkedList is used to
store and retrieve data.
2. Insertion and deletion of elements only from the top of the Stack is possible. Insertion and
deletion of elements from any where is possible in case of a LinkedList.
113). What is the difference between ArrayList and Vector ?


ArrayList Vector
ArrayList object is not synchronized by default Vector object is synchronized by default.
Incase of a single thread, using ArrayList is faster than the Vector.
In case of multiple threads, using Vector is advisable. With a single thread, Vector becomes slow.
ArrayList increases its size every time by 50 percent (half). Vector increases its size every time by doubling it.
114). Can you synchronize the ArrayList object ?
Ans). Yes, we can use synchronizedList( ) method to synchronize the ArrayList, as:
Collections.synchronizedList(new ArrayList( ));
115). What is the load factor for a HashMap or Hashtable ?
Ans). 0.75.
116). What is the difference between HashMap and Hashtable ?
Ans).

HashMap Hashtable
HashMap object is not synchronized by default. Hashtable object is synchronized by default.
In case of a single thread, using HashMap is faster than the Hashtable.
In case of multiple threads, using Hashtable is advisable, with a single thread, Hashtable becomes slow.
HashMap allows null keys and null values to be stored.
Hashtable does not allow null keys or values.
Iterator in the HashMap is fail-fast. This means Iterator will produce exeception if concurrent updates are made to the HashMap. Enumeration for the Hashtable is not fail-fast. This
means even if concurrent updations are done to Hashtable, there will not be any incorrect results produced by the Enumeration.
117). Can you make HashMap synchronized ?
Ans). Yes, we can make HashMap object synchronized using synchronizedMap( ) method as shown here:
Collections.synchronizedMap(new HashMap( ));
118). What is the difference between a Set and a List ?


Set List
A set represents a collection of elements. Order of the elements may change in the set.
A List represents ordered collection of elements.List preserves the order of elements in which they are entered.
Set will not allow duplicate values to be stored. List will allow duplicate values.
Accessing elements by their index (position number) is not possible in case of sets.
Accessing elements by index is possible in lists.
Sets will not allow null elements. Lists allow null elements to be stored.
119). What is the difference between System.out and System.err ?
Ans). Both are used to display messages on the monitor. System.out is used to display normal messages
As:
System.out.println(“This is nayanimuralidhar”);
System.err.println(“This is an error”);
120). What is the advantage of stream concept..?
Ans). Streams are mainly useful to move data from one place to another place. This concept can be used
to receive data from an input device and send data to an output device.
121). What is the default buffer size used by any buffered class ?
Ans). 512 bytes.
122). What is serialization ?
Ans). Serialization is the process of storing object contents into a file. The class whose objects are stored
in the file should implement ‘serializable’ interface of java.io.package.
123).What type of variables cannot be serialized ?
Ans). Static and transient variables cannot be serialized.
Once the objects are stored into a file, they can be later retrieved and used as and when needed.This is
called de-serialization.
124). What is IP address ?
Ans). An IP address is a unique identification number allocated to every computer on a network or
Internet. IP address contains some bytes which identify the network and the actual computer inside the
network.
125). What is DNS ?
Ans). Domain Naming Service is a service on Internet that maps the IP address with corresponding
website names.
126). What is a socket ?
Ans). A socket is a point of conneciton between a server and a client on a network.
127). What is port number ?
Ans). Port number ia a 2 byte number which is used to identify a socket uniquely.
128). Which thread always runs in a Java program by default ?
Ans). main thread. A thread represents execution of statements. The way the statements are executed is of
two types: 1). Single tasking 2). Multi tasking.
129). Why threads are called light-weight ?
Ans). Threads are light-weight because they utilize minimum resources of the system. This means they
take less memory and less processor time.
130). What is the difference between single tasking and multitasking ?
Ans). Executing only one job at a time is called single tasking. Executing several jobs at a time is called
multi tasking. In single tasking, the processor time is wasted, but in multi tasking, we can utilize the
processor time in an optimum way.
131). How can you stop a thread in Java ?
Ans). First of all , we should create a boolean type variable which stores ‘ false’ . When the user wants to
stop the thread. We should store ‘true’into the variable. The status of the variable is checked in the run ( )
method and if it is true, the thread executes ‘return’ statement and then stops.
132). What is the difference between ‘ extends Thread’ and ‘implements Runnable’ ? Which one
is advatageous ?
Ans). extends Thread and implements Runnable – both are functionally same. But when we write extends
Thread, there is no scope to extend another class, as multiple inheritance is not supported in Java.
Class Myclass extends Thread, AnotherClass //invalid
If we write implements Runnable, then still there is scope to extend another class.
class Myclass extends AnotherClass implements Runnable //valid
This is definitely advantageous when the programmer wants to use threads and also wants to access the
features of another class.
133). Which method is executed by the thread by default ?
Ans). public void run( ) method.
134). What is Thread synchronization ?
Ans). When a thread is already acting on an object, preventing any other thread from acting on the same
object is called ‘Thread synchronization’ or ‘Thread safe’ The object on which the threads are
synchronized is called ‘synchronized object’. Thread synchronization is recommended when multiple
threads are used on the same object(in multithreading).
135). What is the difference between synchronized block and synchronized keyword ?
Ans). Synchronized block is useful to synchronized a block of statements. Synchronized keyword is
useful to synchronize an entire method.
138). What is Thread deadlock ?
Ans). When a thread has locked an object and waiting for another object to be released by another
thread.and the other thread is also waiting for the first thread to release the first object, both the threads
will continue waiting forever. This is called ‘Thread deadlock’.
139). What is the difference between the sleep( ) and wait( ) methods ?
Ans). Both the sleep( ) and wait( ) methods are used to suspend a thread execution for a specified time.
When sleep( ) is executed inside a synchronized block, the object is still under lock. When wait( ) method
is executed, it breaks the synchronized block, so that the object lock is removed and it is available.
Generally, sleep( ) is used for making a thread to wait for some time. But wait( ) is used in connection
with notify ( ) or notifyAll( ) mehtods in therad communication.
140). What is the default priority of a thread ?
Ans). When a thread is created, by default its priority will be 5.
141). What is demon thread ?
Ans). A daemon thread is a thread is a thread that executes continuously. Daemon threads are service
providers for other threads or objects. It generally provides a background procssing.
142). What is thread life cycle ?
Ans). A thread is created using new Thread( ) statement and is executed by start( ) method. The thread
enters ‘runnable’ state and when sleep( ) or wait( ) methods are used or when the thread is blocked on I/O,
it then goes into ‘not runnable’ state. From ‘not runnable’ state, the thread comes back to the ‘runnable’
state and continues running the statements. The thread dies when it comes out of run( ) mehtod . These
state thransitions of a thread are called ‘life cycle of a thread’.
143). What is the difference between a window and a frame ?
Ans). A window is a frame without any borders and title, whereas a frame contains borders and title.
144). What is event delegation model ?
Ans). Event delegation model represents that when an event is generated by the user on a component, it is
delegated to a listener interface and the listener calls a mehtod in response to the event. Finally , the event
is handled by the method.
145). Which model is used to provide actions to AWT components ?
Ans). Event delegation model.
146). What is an adapter class ?
Ans). An adapter class is an implementation class of a listener which contains all methods implemented
with empty body. For example, WindowAdapter is an adapter class of WindowListener interface.
Adapter classes reduce overhead on programming while working with listener interfaces.
147). What is anonymous inner class ?
Ans). Anonymous inner class is an inner class whose name is not mentioned, and for which only one
object is created.
148). What is the default layout in a frame ?
Ans). BorderLayout.
149). What is the default layout in an applet ?
Ans). FlowLayout.
150).What are Java Foundation classes ?
Ans). Java Foundation classes (JFC) represented a class library developed in pure Java which is an
extension to AWT.
151). Discuss about the MVC architecture in JFC/ swing ?
Ans). Model- View – Controller is a model used in swing components. Model represents the data of the
component. View represents its appearance and controller is a mediater between the model and the
view.MVC represents the separation of model of an object from its view and how it is controlled.
152). What are the various window panes available in swing ?
Ans). There are 4 window panes: Glass pane, Root pane, Layered pane, and Content pane.
153). Where are the borders available in swing ?
Ans). All borders are available in BorderFactory class in javax.swing.border package.
154). What is an applet ?
Ans). An applet represents Java byte code embedded in a web page.
155).What is applet life cycle ?
Ans). An applet is born with init( ) method and starts functioning with start( ) method. To stop the applet,
the stop( ) method is called and to terminate the applet completely from memory, the destroy( ) method is
called. Once the applet is terminated, we should reload the HTML page again to get the applet start once
again from init( ) method. This cyclic way of executing the methods is called applet life cycle.
156). Where are the applets executed ?
Ans). Applets are executed by a program called applet engine which is similar to virtual machine that
exists inside the web browser at client side.
157). What is HotJava?
Ans).Hot Java is the first applet-enabled browser developed in Java to support running of applets.
158). What is a generic type ?
Ans). A generic type represents a class or an interface that is type-safe. It can act on any data type.
159). Whai is erasure ?
Ans). Creating non-generic version of a generic type by the Java compiler is called erasure.
160). What is auto boxing ?
Ans). Auto boxing refers to creating objects and storing primitive data types automatically by the
compiler.
161). What is JDBC ?
Ans). JDBC (Java Database Connectivity) is an API that is useful to write Java programs to connect to
any database, retreive the data from the database and utilize the data in a Java program.
162). What is a database driver ?
Ans). A database driver is a set of classes and interfaces, written according to JDBC API to communicate
with a database.
163). How can you register a driver ?
Ans). To register a database driver, we can follow one of the 4 options:
- By creating an object to driver class
- By sending driver class object to DriverManager.registerDriver( ) method
- By sending the driver class name to Class.forName( ) method
- By using System class getProperty( ) method.

What is the role of the clone() method in Java?

protected Object clone() throws CloneNotSupportedException - this method is used to create a copy of an object of a class which implements Cloneable interface. By default it does field-by-field copy as the Object class doesn't have any idea in advance about the members of the particular class whose objects call this method. So, if the class has only primitive data type members then a completely new copy of the object will be created and the reference to the new object copy will be returned. But, if the class contains members of any class type then only the object references to those members are copied and hence the member references in both the original object as well as the cloned object refer to the same object.

Cloneable interface
We get CloneNotSupportedException if we try to call the clone() method on an object of a class which doesn't implement the Cloneable interface. This interface is a marker interface and the implementation of this interface simply indicates that the Object.clone() method can be called on the objects of the implementing class.

Example: how cloning works in Java?

Class A {
...
}
A objA = new A();
A objACloned = (A) objA.clone();


Now, objA != objACloned - this boolean expression will always be true as in any case a new object reference will be created for the cloned copy.

objA.getClass() == objACloned.getClass() - this boolean expression will also be always true as both the original object and the cloned object are instances of the same class (A in this case).

Initially, objA.equals(objACloned) will return true, but any changes to any primitive data type member of any of the objects will cause the expression to return false. It's interesting to note here that any changes to the members of the object referenced by a member of these objects will not cause the expression to return false. Reason being, both the copies are referring to same object as only the object references get copied and not the object themselves. This type of copy is called Shallow Copy (Read Next - Deep Copy vs Shallow Copy >> You may browse the links given in that article to go through various aspects of Cloning in Java). This can be understood easily by looking at the following memory diagram:-


               

java basics

java basics

A Java program is mostly a collection of objects talking to other objects by invoking each other's methods. Every object is of certain type, and that type is defined by a class or an interface. Most Java programs use a collection of objects of many different types.

class:
template describes the kind of state and behavior that objects of its type support.

Real time examples:
1) 
public class Dog{
   String breed;
   int age;
   String color;

   void barking(){ 
    //barking action
   }
   
   void hungry(){ 
   //hungry action
   }
   
   void sleeping(){
   //sleeping action 
   }
}
A class can contain any of the following variable types.
  • Local variables . variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.
  • Instance variables . Instance variables are variables within a class but outside any method. These variables are instantiated when the class is loaded. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.
  • Class variables . Class variables are variables declared with in a class, outside any method, with the static keyword.
A class can have any number of methods to access the value of various kind of methods. In the above example, barking(), hungry() and sleeping() are methods.

Object:
At runtime when the Java virtual machine encounters new key will, it will use the appropriate class to make an object which is an instance of that class. That objects will have its own states and have access to all of the behaviors defined in the class from which those created.

State ( instance variable ):
Each object ( instance of a class) will have its own unique set of instance variables as defined in the class. The values assigned to an objects instance variables makes up the objects state.

behavior( methods ):
Methods are where the class logic's are stored . They are where the real work gets done and data gets manipulated.

Now i can give a Real time example for Class, Object, and Object's state & behavior

If we take B.Tech graduation there are different classes exist like CSE, EEE, ECE, MEC
and so on. suppose if we take CSE class for our class example. all the students who
graduated in CSE will have different percentage of knowledge in all the subjects of CSE
and they can do software job, any govt job after completion of their course.
here

i)CSE class considered as an example for class.
i) Every student will act as an object.
ii) Percentage of knowledge in subjects is the state of those student objects
iii)Jobs they can do will act as behavior.  In performing their job their subjects knowledge get manipulated.

Some important topics need to be discussed those are

Constructors:

When discussing about classes one of the most important sub topic would be constructors. Every class has a constructor. If we do not explicitly write a constructor for a class the java compiler builds a default constructor for that class.
Each time a new object is created at least one constructor will be invoked. The main rule of constructors is that they should have the same name as the class. A class can have more than one constructor.
Example of a constructor is given below:

public class Employee{
public Employee(){
//code follows
}
public Employee(String designation){
// code follows
}
}

A constructor is a block of code that is called when a new object is created. In the constructor there is typically code to initialize the member variables of the object or to do other things that need to be done when a new object is created.

Creating an Object:

there are mainly three steps involved in creation of java object
those are
1 . loading
2.Instantiating
3.Intializing

Assume that we have a class with name "student" now we want to create object for it
the statement that will write is
st1:      student std;
st2 :     std=new student();
in statement one it will cretae a reference with std in the stack and its not the object
in statement 2 when u say actual process starts :

LOADING :
As the  student class will exist in the hard disk (secondary storage) it will be loaded into the main memory(RAM) 

INSTANTIATING: 
Once the loading is done it will allocate the memory for the non static members of the class in the heap.
 
INITIALIZING:
Once the memory is allocated then the data members will be intialized with default values
provided by JVM.
 after completing these 3 steps the address of the object will be stored in the a hash table
along with index . this index will be stored in  the reference varaible .

Example:

This example explains how to access instance variables and methods of a class:

public class Puppy{
   
   int puppyAge;

   public Puppy(String name){
      // This constructor has one parameter, name.
      System.out.println("Passed Name is :" + name ); 
   }
   public void setAge( int age ){
       puppyAge = age;
   }

   public int getAge( ){
       System.out.println("Puppy's age is :" + puppyAge ); 
       return puppyAge;
   }
   public static void main(String []args){
      /* Object creation */
      Puppy myPuppy = new Puppy( "tommy" );

      /* Call class method to set puppy's age */
      myPuppy.setAge( 2 );

      /* Call another class method to get puppy's age */
      myPuppy.getAge( );

      /* You can access instance variable as follows as well */
      System.out.println("Variable Value :" + myPuppy.puppyAge ); 
   }
} 
 
If we compile and run the above program then it would produce following result:
 
Passed Name is :tommy
Puppy's age is :2
Variable Value :2

Source file declaration rules:

As the last part of this section lets us now look into the source file declaration rules. These rules are essential when declaring classes, import statements and package statements in a source file.
  • There can be only one public class per source file.
  • A source file can have multiple non public classes.
  • The public class name should be the name of the source file as well which should be appended by .java at the end. For example : The class name is . public class Employee{} Then the source file should be as Employee.java.
  • If the class is defined inside a package, then the package statement should be the first statement in the source file.
  • If import statements are present then they must be written between the package statement and the class declaration. If there are no package statements then the import statement should be the first line in the source file.
  • Import and package statements will imply to all the classes present in the source file. It is not possible to declare different import and/or package statements to different classes in the source file.

Java naming convensions

Standard Java Naming Conventions

The below list outlines the standard Java naming conventions for each identifier type:
Packages: Names should be in lowercase. With small projects that only have a few packages it's okay to just give them simple (but meaningful!) names: 
package pokeranalyzer
package mycalculator 

In software companies and large projects where the packages might be imported into other classes, the names will normally be subdivided. Typically this will start with the company domain before being split into layers or features:

package com.mycompany.utilities
package org.bobscompany.application.userinterface 

Classes: Names should be in CamelCase. Try to use nouns because a class is normally representing something in the real world:
class Customer
class Account  

Interfaces: Names should be in CamelCase. They tend to have a name that describes an operation that a class can do:
 interface Comparable
 interface Enumerable  

Note that some programmers like to distinguish interfaces by beginning the name with an "I":
 
interface IComparable
interface IEnumerable  

Methods: Names should be in mixed case. Use verbs to describe what the method does:
void calculateTax()
string getSurname()  

Variables: Names should be in mixed case. The names should represent what the value of the variable represents:
string firstName
int orderNumber  

Only use very short names when the variables are short lived, such as in for loops

Constants: Names should be in uppercase. 

static final int DEFAULT_WIDTH
static final int MAX_HEIGHT 

Access Specifiers In Java with real time example

Definition :
- Java Access Specifiers (also known as Visibility Specifiers ) regulate access to classes, fields and methods in Java.These Specifiers determine whether a field or method in a class, can be used or invoked by another method in another class or sub-class. Access Specifiers can be used to restrict access. Access Specifiers are an integral part of object-oriented programming.

Types Of Access Specifiers :
In java we have four Access Specifiers and they are listed below.

1. public
2. private
3. protected
4. default(no specifier)

We look at these Access Specifiers in more detail.



 public specifiers :
Public Specifiers achieves the highest level of accessibility. Classes, methods, and fields declared as public can be accessed from any class in the Java program, whether these classes are in the same package or in another package.

Example :
  1. public class Demo {  // public class  
  2. public x, y, size;   // public instance variables   
  3. }

private specifiers :

Private Specifiers achieves the lowest level of accessibility.private methods and fields can only be accessed within the same class to which the methods and fields belong. private methods and fields are not visible within subclasses and are not inherited by subclasses. So, the private access specifier is opposite to the public access specifier. Using Private Specifier we can achieve encapsulation and hide data from the outside world.

Example :
  1. public class Demo {   // public class  
  2. private double x, y;   // private (encapsulated) instance variables  
  3.   
  4. public set(int x, int y) {  // setting values of private fields  
  5. this.x = x;  
  6. this.y = y;  
  7. }  
  8.   
  9. public get() {  // setting values of private fields  
  10. return Point(x, y);  
  11. }  
  12.  }  
    protected specifiers :

    Methods and fields declared as protected can only be accessed by the subclasses in other package or any class within the package of the protected members' class. The protected access specifier cannot be applied to class and interfaces.

    default(no specifier):

    When you don't set access specifier for the element, it will follow the default accessibility level. There is no default specifier keyword. Classes, variables, and methods can be default accessed.Using default specifier we can access class, method, or field which belongs to same package,but not from outside this package.

    Example :
    1. class Demo  
    2. {  
    3. int i; (Default)  
    4. }  

    Real Time Example : 
  13.                                      

How many ways of creating objects in Java?

Well... there aren't many different ways I suppose. But from an application programmer perspective here are the different possible ways of creating objects in Java:-
  • Using new operator - the most commonly used way by far. 'new' is an operator and the only operand it requires is a constructor which will be used for initializting the newly created instance. 'new' operator allocates the memory space and initializes the fields with their default values. Then it executes the code inside the specified constrcutor which normally re-writes the default values of some (or all) fields with the particular values mentioned in the constructor definition.
  • Using clone() method - Cloning (Shallow or Deep) makes a new copy of the specified object. It doesn't call the 'new' operator internally. Object.clone() is a native method which translates into instructions for allocating the memory and copying the data. Remember that even if we override the clone() method either to implement Deep Cloning or to make the clone() method as 'public' but then also we keep the line super.clone() inside the overriden definition which ultimately calls Object.clone() method only. You might wonder about what the 'new' operator actually translates into and how this approach is different from that. Okay... we all know that 'new' does three tasks - allocating the memory, initializing the fields with default values, and calling the specified constructor. Now the first task is same in both the approaches and there would probably be the same native allocator being used in both the cases. But in case of Cloning, the allocated memory is not initialized with default values and also no constructor is called in this case. Only a datacopy instruction will be executed which copies the data from the original object to the cloned object. Read more about Cloing in this article - Cloning in Java >>
Using Class.forName() and newInstance() - A calss can be dynamically loaded using the Class.formName() method. This method has two variants - one which accepts only a String type parameter which is the qualifies name of the class to be loaded and the other variant expects three parameters - the String type qualifies class name, boolean type flag to specify if the class should be initialized, and the ClassLoader name which should be used to load the class. The former variant also internally calls the three-parameter variant only by assuming the boolean flag as 'true' and the ClassLoader as returned by the getClassLoader() method. That means 'Class.forName("qualified.ClassName")' is internally translated into 'Class.forName("qualifies.ClassName", true, this.getClass().getClassLoader())'. Once the class has been loaded then a call of the method newInstance() on the loaded Class object will first check if the Class object is initialized or not and if not then it will initialize the Class object and create a new object as if the 'new' operator has been called with the default constructor of the class under consideration. Again you may argue how is this different from an explicit 'new' call and it won't take much of an effort to identify the most obvious difference between the two as the inability of this approach to call any other constructor except the default constructor. Another difference is that the newInstance() call may throw a SecurityException as well because it checks if a Security Manager is installed or not and if it finds a security manager then it checks for access to the class as wellas to the package (if any package specified in the qualified name). Either of two checks may throw a SecurityException. This step is obviously not involved with an explicit 'new' call. Another slightly different way of object creation is by using the loadClass() method of the ClassLoader class which returns a Class object of the specified class and then on the returned Class object we may call newInstance() method to create a new object. I've not put this as a completely separate way because I think Class.forName() method also internally calls this method only - either for the explcitly supplied ClassLoader or for the implcitily obtained ClassLoader as discussed above. What's the difference between the two approaches then? The only difference which I can see is that the former checks for the access to the class (and package) and hence it may throw SecurityException if a Security Manager is installed. But the latter doesn't do these checks and hence doesn't throw SecurityException. It's normally advised not to call the loadClass() method directly as almost always you can call Class.forName() by supplying the particular ClassLoader reference

Java Object oriented programming concepts with real time examples

Java Object oriented programming concepts with real time examples



OOPS Concepts are mainly 4 
 1.Abstraction
 2.Encapsulation
 3.Inheritance 
 4.Polymorphism
Abstraction:-Hiding non-essential features and showing the
essential features
              (or)
Hiding unnecessary data from the users details,is called
abstraction.
Real Time example:1.TV Remote Button 
in that number format and power buttons and other buttons
there.just we are seeing the buttons,we don't see the
button circuits.i.e buttons circuits and wires all are
hidden.so i think its good example.

Encapsulation:It is a process of binding or wrapping the data and the
codes that operates on the data into a single entity. This
keeps the data safe from outside interface and misuse. One
way to think about encapsulation is as a protective wrapper
that prevents code and data from being arbitrarily accessed
by other code defined outside the wrapper.

Real Time Example:  

1.Ink is the important component in pen but it is hiding
by some other material 
2.Medical Tablet
i.e one drug is stored in bottom layer and another drug is
stored in Upper layer these two layers are combined in
single Tablet.

Inheritance:The new classes, known as derived classes, take over (or
inherit) attribute and behavior of the pre-existing classes,
which are referred to as base classes (or Parent classes).
It is intended to help reuse existing code with little or no
modification.
Real Time Example:
1. Father and Son Relationship

Polymorphism:Single Form behaving differently in different Situations. A single 

function or single operator has different characters in different places. 

Real Time Example:
1.A girl plays a role of daughter at home and a manager at
office.
2. Person
Person in Home act is husband/son,
       in Office acts Employer.
       in Public Good Citizen. 
 
<<<<<<<<<<<<<<<<------------------------->>>>>>>>>>>>>
 

OOPS Concepts with realtime examples

1. Abstraction

Abstraction helps to hide the non essential features from the user and makes the application user friendly.

Eg. Take your mobile phone. You are having buttons and know the purpose but no need to understand how it prints number on the screen when it is pressed.

2. Encapsulation

It bundles the code into a single unit which makes the code very easy to handle.

Eg.

Take computer keyboard. All the buttons have been enclosed.

3. Inheritance

It helps to inherit the superclass properties to subclasses.

Eg. Father - Son relationship.

4. Polymorphism

A entity which behaves differntly at different places.

Eg. A person behaves as a good husband in family.
He behaves as a good employee at company.
He also behaves as a good citizen in public.