






















































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!























































Difference between Procedure Oriented and object oriented programming language?
Procedure Oriented object oriented Divided into In POP program is divided into small parts called functions.
In OOP program is divided into parts called objects.
Importance In POP importance is not given to data but to function as well as sequence of actions to be done.
In OOP importance is given to the data rather than procedures or functions because it works as a real world.
Approach
POP follows TOP Down approach
OOP follows Bottom UP approach Access Specifier POP does not have any access specifier.
OOP has access specifier named public, private, protected etc. Data Moving In POP data can move freely from function to function in the system.
In OOP object can move and communicate with each other through member functions. Expansion To add new data and function in POP is not so easy
OOP provides an easy way to add new data and function.
What are the principle concepts of OOPS? There are four principle concepts upon which object oriented design and programming rest. They are: Abstraction Polymorphism Inheritance Encapsulation (i.e. easily remembered as A-PIE).
What is Abstraction? Abstraction refers to the act of representing essential features without including the background details or explanations.
What is Encapsulation? Encapsulation is a technique used for hiding the properties and behaviors of an object and allowing outside access only as appropriate. It prevents other objects from directly altering or accessing the properties or methods of the encapsulated object.
What is the difference between abstraction and encapsulation? Abstraction focuses on the outside view of an object (i.e. the interface) Encapsulation (information hiding) prevents clients from seeing it’s inside view, where the behavior of the abstraction is implemented. Abstraction solves the problem in the design side while Encapsulation is the Implementation. Encapsulation is the deliverables of Abstraction. Encapsulation barely talks about grouping up your abstraction to suit the developer needs.
What is Inheritance? Inheritance is the process by which objects of one class acquire the properties of objects of another class. A class that is inherited is called a superclass. The class that does the inheriting is called a subclass. Inheritance is done by using the keyword extends. The two most common reasons to use inheritance are: To promote code reuse To use polymorphism
What is Polymorphism? Polymorphism is briefly described as "one interface, many implementations." Polymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts - specifically, to allow an entity such as a variable, a function, or an object to have more than one form.
How does Java implement polymorphism? (Inheritance, Overloading and Overriding are used to achieve Polymorphism in java). Polymorphism manifests itself in Java in the form of multiple methods having the same name. In some cases, multiple methods have the same name, but different formal argument lists (overloaded methods). In other cases, multiple methods have the same name, same return type, and same formal argument list (overridden methods).
Method overriding occurs when sub class declares a method that has the same type arguments as a method declared by one of its superclass. The key benefit of overriding is the ability to define behavior that’s specific to a particular subclass type. Note: The overriding method cannot have a more restrictive access modifier than the method being overridden (Ex: You can’t override a method marked public and make it protected). You cannot override a method marked final You cannot override a method marked static
What is a class?
class
A class is a specification or blue print or template of an object. Class is a logical construct; an object has physical reality. Class is a structure Binding the data with its related and corresponding functions. Class is the base for encapsulation. Class is a user defined data type in java. Class will act as the base for encapsulation and implement the concept of encapsulation through objects. Any java applications look like collection of classes but whereas c- application looks like collection of functions. Class contains variables and methods.
What is an object?
Object
Object is nothing but instance (dynamic memory allocation) of a class. The dynamic memory allocated at run time for the members [non-static variables] of the class is known as object. Object is an encapsulated form of all non-static variables and non-static methods of a particular class. The process of creating objects out of class is known as instantiation.
What are the Object Characteristics?
The three key characteristics of Object are
State Behaviour
Identity
State: Instance variables value is called object state. An object state will be changed if instance variables value is changed.
Behavior: Behaviour of an object is defined by instance methods. Behaviour of an object is depends on the messages passed to it. So an object behaviour depends on the instance methods.
Identity: Identity is the hash code of an object, it is a 32-bit integer number created randomly and assigned to an object by default by JVM. Developer can also generate hash code of an object based on the state of that object by overriding hashcode() method of java.lang.Object class. Then if state is changed, automatically hashcode will be changed.
What Object Contains? Object of any class contains only data. Apart from the data object of a class would not contains anything else. Object of a class would not contain any functionalities or logic. Thus object of a class would be representing only data and not represent logic.
What is state of the Object? The data present inside object of a class at that point of time is known as state of the object.
What is behaviour of the object? The functionalities associated with the object => Behaviour of the object. The state of the object changes from time-to-time depending up on the functionalities that are executed on that object but whereas behaviour of the object would not change.
In how many ways can you create an object in Java? 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:
Object graph is a graph showing relationship between different objects in memory.
Explain what can we use primitive data types as objects? Primitive data types like int can be handled as objects by the use of their respective wrapper classes. For example, Integer is a wrapper class for primitive data type int. We can apply different methods to a wrapper class, just like any other object.
What is mutable object and immutable object? If an object value is changeable then we can call it as Mutable object. (Ex., StringBuffer, …) If you are not allowed to change the value of an object, it is immutable object. (Ex., String, Integer, Float, …)
How many objects are created in the following piece of code? MyClass c1, c2, c3; c1 = new MyClass (); c3 = new MyClass ();
Only 2 objects are created, c1 and c3. The reference c2 is only declared and not initialized.
Explain what objects are stored in Java?
In java, each object when created gets a memory space from a heap. When an object is destroyed by a garbage collector, the space allocated to it from the heap is re-allocated to the heap and becomes available for any new objects.
Explain what can we find the actual size of an object on the heap? In java, there is no way to find out the exact size of an object of the heap.
Which of the following classes will have more memory allocated? Class A: Three methods, four variables, no object Class B: Five methods, three variables, no object Answer: - Memory isn’t allocated before creation of objects. Since for both classes, there are no objects created so no memory is allocated on heap for any class.
What is memory leak? A memory leak is where an unreferenced object that will never be used again still hangs around in memory and doesn’t get garbage collected.
I want my class to be developed in such a way that no other class (even derived class) can create its objects. Explain what can I do so? If we declare the constructor of a class as private, it will not be accessible by any other class and hence, no other class will be able to instantiate it and formation of its object will be limited to itself only.
What are the Object and Class classes used for? Which class should you use to obtain design information about an object? Differentiate between a Class and an Object? The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program. The Class class is used to obtain information about an object's design. A Class is only a definition or prototype of real life object. Whereas an object is an instance or living representation of real life object. Every object belongs to a class and every class contains one or more related objects.
What is the difference between an object and an instance? An Object May not have a class definition. eg int a[] where a is an array. An Instance should have a class definition.
eg MyClass my=new MyClass(); my is an instance.
What is the difference between instance, object, reference and a class? Class: A class is a user defined data type with set of data members & member functions Object: An Object is an instance of a class Reference: A reference is just like a pointer pointing to an object Instance: This represents the values of data members of a class at a particular time
What is a singleton class? Or What is singleton pattern? This design pattern is used by an application to ensure that at any time there is only one instance of a class created. You can achieve this by having the private constructor in the class and having a getter method which returns an object of the class and creates one for the first time if its null.
What is the purpose of the System class? The purpose of the System class is to provide access to system resources.
What is super? super is a keyword which is used to access the method or member variables from the superclass. If a method hides one of the member variables in its superclass, the method can refer to the hidden variable through the use of the super keyword. In the same way, if a method overrides one of the methods in its superclass, the method can invoke the overridden method through the use of the super keyword. Note: You can only go back one level. In the constructor, if you use super(), it must be the very first code, and you cannot access any this.xxx variables or methods to compute its parameters.
How do you prevent a method from being overridden? To prevent a specific method from being overridden in a subclass, use the final modifier on the method declaration, which means "this is the final implementation of this method", the end of its inheritance hierarchy. public final void exampleMethod() { // Method statements }
What is an Interface? An interface is a description of a set of methods that conforming implementing classes must have. Note: You can’t mark an interface as final. Interface variables must be static. An Interface cannot extend anything but another interfaces.
Can we instantiate an interface? You can’t instantiate an interface directly, but you can instantiate a class that implements an interface. Can we create an object for an interface? Yes, it is always necessary to create an object implementation for an interface. Interfaces cannot be instantiated in their own right, so you must write a class that implements the interface and fulfill all the methods defined in it.
Do interfaces have member variables? Interfaces may have member variables, but these are implicitly public, static, and final- in other words, interfaces can declare only constants, not instance variables that are available to all implementations and may be used as key references for method arguments for example.
What modifiers are allowed for methods in an Interface? Only public and abstract modifiers are allowed for methods in interfaces.
What is a marker interface? Marker interfaces are those which do not declare any required methods, but signify their compatibility with certain operations. The java.io.Serializable interface and Cloneable are typical marker interfaces. These do not contain any methods, but classes must implement this interface in order to be serialized and de-serialized.
What is an abstract class? Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Note: If even a single method is abstract, the whole class must be declared abstract. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods. You can’t mark a class as both abstract and final.
Can we instantiate an abstract class? An abstract class can never be instantiated. Its sole purpose is to be extended (subclassed).
When should I use abstract classes and when should I use interfaces? Use Interfaces when… You see that something in your design will change frequently. If various implementations only share method signatures then it is better to use Interfaces. you need some classes to use some methods which you don't want to be included in the class, then you go for the interface, which makes it easy to just implement and make use of the methods defined in the interface.
Use Abstract Class when… If various implementations are of the same kind and use common behavior or status then abstract class is better to use. When you want to provide a generalized form of abstraction and leave the implementation task with the inheriting subclass. Abstract classes are an excellent way to create planned inheritance hierarchies. They're also a good choice for nonleaf classes in class hierarchies.
When you declare a method as abstract, can other non abstract methods access it? Yes, other non abstract methods can access a method that you declare as abstract.
Super Calls the constructor of the parent class. If used, must be the first line of the constructor Calls an overridden method in the parent class
How are this() and super() used with constructors? Constructors use this to refer to another constructor in the same class with a different parameter list. Constructors use super to invoke the superclass's constructor. If a constructor uses super, it must use it in the first line; otherwise, the compiler will complain.
What are the differences between Class Methods and Instance Methods? Class Methods Instance Methods a) Class methods are methods which are declared as static. The method can be called without creating an instance of the class Instance methods on the other hand require an instance of the class to exist before they can be called, so an instance of a class needs to be created by using the new keyword. Instance methods operate on specific instances of classes. b) Class methods can only operate on class members and not on instance members as class methods are unaware of instance members. Instance methods of the class can also not be called from within a class method unless they are being called on an instance of that class. c) Class methods are methods which are declared as static. The method can be called without creating an instance of the class. Instance methods are not declared as static.
How are this() and super() used with constructors? Constructors use this to refer to another constructor in the same class with a different parameter list. Constructors use super to invoke the superclass's constructor. If a constructor uses super, it must use it in the first line; otherwise, the compiler will complain.
What are Access Specifiers? One of the techniques in object-oriented programming is encapsulation. It concerns the hiding of data in a class and making this class available only through methods. Java allows you to control access to classes, methods, and fields via so-called access specifiers..
What are Access Specifiers available in Java? Java offers four access specifiers, listed below in decreasing accessibility: Public- public classes, methods, and fields can be accessed from everywhere.
Protected- protected methods and fields can only be accessed within the same class to which the methods and fields belong, within its subclasses, and within classes of the same package. Default(no specifier)- If you do not set access to specific level, then such a class, method, or field will be accessible from inside the same package to which the class, method, or field belongs, but not from outside this package. Private- 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.
What is final modifier? The final modifier keyword makes that the programmer cannot change the value anymore. The actual meaning depends on whether it is applied to a class, a variable, or a method. final Classes- A final class cannot have subclasses. final Variables- A final variable cannot be changed once it is initialized. final Methods- A final method cannot be overridden by subclasses.
What are the uses of final method? There are two reasons for marking a method as final: Disallowing subclasses to change the meaning of the method. Increasing efficiency by allowing the compiler to turn calls to the method into inline Java code.
What is static block? Static block which exactly executed exactly once when the class is first loaded into JVM. Before going to the main method the static block will execute.
What are static variables? Variables that have only one copy per class are known as static variables. They are not attached to a particular instance of a class but rather belong to a class as a whole. They are declared by using the static keyword as a modifier. static type varIdentifier; where, the name of the variable is varIdentifier and its data type is specified by type. Note: Static variables that are not explicitly initialized in the code are automatically initialized with a default value. The default value depends on the data type of the variables.
What is the difference between static and non-static variables? A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.
How is ListIterator? ListIterator is just like Iterator, except it allows us to access the collection in either the forward or backward direction and lets us modify an element
What is the List interface? The List interface provides support for ordered collections of objects. Lists may contain duplicate elements.
What are the main implementations of the List interface? The main implementations of the List interface are as follows : ArrayList : Resizable-array implementation of the List interface. The best all-around implementation of the List interface. Vector : Synchronized resizable-array implementation of the List interface with additional "legacy methods." LinkedList : Doubly-linked list implementation of the List interface. May provide better performance than the ArrayList implementation if elements are frequently inserted or deleted within the list. Useful for queues and double-ended queues (deques).
What are the advantages of ArrayList over arrays? Some of the advantages ArrayList has over arrays are: It can grow dynamically It provides more powerful insertion and search mechanisms than arrays.
Difference between ArrayList and Vector? ArrayList Vector a) ArrayList is NOT synchronized by default. Vector List is synchronized by default. b) ArrayList can use only Iterator to access Vector list can use Iterator and the elements Enumeration Interface to access the elements. c) The ArrayList increases its array size by A Vector defaults to doubling the size 50 percent if it runs out of room. of its array if it runs out of room d) ArrayList has no default size. While vector has a default size-
How to obtain Array from an ArrayList? Array can be obtained from an ArrayList using toArray() method on ArrayList. List arrayList = new ArrayList(); arrayList.add(…
Object a[] = arrayList.toArray();
Why insertion and deletion in ArrayList is slow compared to LinkedList? ArrayList internally uses and array to store the elements, when that array gets filled by inserting elements a new array of roughly 1.5 times the size of the original array is created and all the data of old array is copied to new array. During deletion, all elements present in the array after the deleted elements have to be moved one step back to fill the space created by deletion. In linked list data is stored in nodes that have reference to the previous node and the next node so adding element is simple as creating the node an updating the next pointer on the last node and the previous pointer on the new node. Deletion in linked list is fast because it involves only updating the next pointer in the node before the deleted node and updating the previous pointer in the node after the deleted node.
Why are Iterators returned by ArrayList called Fail Fast? Because, if list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.
How do you decide when to use ArrayList and When to use LinkedList? If you need to support random access, without inserting or removing elements from any place other than the end, then ArrayList offers the optimal collection. If, however, you need to frequently add and remove elements from the middle of the list and only access the list elements sequentially, then LinkedList offers the better implementation.
What is the Set interface? The Set interface provides methods for accessing the elements of a finite mathematical set Sets do not allow duplicate elements Contains no methods other than those inherited from Collection It adds the restriction that duplicate elements are prohibited Two Set objects are equal if they contain the same elements
What are the main Implementations of the Set interface? The main implementations of the List interface are as follows: HashSet TreeSet LinkedHashSet EnumSet
What is a TreeMap? TreeMap actually implements the SortedMap interface which extends the Map interface. In a TreeMap the data will be sorted in ascending order of keys according to the natural order for the key's class, or by the comparator provided at creation time. TreeMap is based on the Red-Black tree data structure.
How do you decide when to use HashMap and when to use TreeMap? For inserting, deleting, and locating elements in a Map, the HashMap offers the best alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap is your better alternative. Depending upon the size of your collection, it may be faster to add elements to a HashMap, then convert the map to a TreeMap for sorted key traversal.
How does a Hashtable internally maintain the key-value pairs? TreeMap actually implements the SortedMap interface which extends the Map interface. In a TreeMap the data will be sorted in ascending order of keys according to the natural order for the key's class, or by the comparator provided at creation time. TreeMap is based on the Red-Black tree data structure.
What Are the different Collection Views That Maps Provide? Maps Provide Three Collection Views. Key Set - allow a map's contents to be viewed as a set of keys. Values Collection - allow a map's contents to be viewed as a set of values. Entry Set - allow a map's contents to be viewed as a set of key-value mappings.
What is a KeySet View? KeySet is a set returned by the keySet() method of the Map Interface, It is a set that contains all the keys present in the Map.
What is a Values Collection View? Values Collection View is a collection returned by the values() method of the Map Interface, It contains all the objects present as values in the map.
What is an EntrySet View? Entry Set view is a set that is returned by the entrySet() method in the map and contains Objects of type Map. Entry each of which has both Key and Value.
How do you sort an ArrayList (or any list) of user-defined objects? Create an implementation of the java.lang.Comparable interface that knows how to order your objects and pass it to java.util.Collections.sort(List, Comparator).
What is the Comparable interface? The Comparable interface is used to sort collections and arrays of objects using the Collections.sort() and java.utils.Arrays.sort() methods respectively. The objects of the class implementing the Comparable interface can be ordered. The Comparable interface in the generic form is written as follows: interface Comparable where T is the name of the type parameter.
All classes implementing the Comparable interface must implement the compareTo() method that has the return type as an integer. The signature of the compareTo() method is as follows:
int i = object1.compareTo(object2) If object1 < object2: The value of i returned will be negative. If object1 > object2: The value of i returned will be positive. If object1 = object2: The value of i returned will be zero.
What are the differences between the Comparable and Comparator interfaces? Comparable Comparato It uses the compareTo() method. It uses the compare() method. int objectOne.compareTo(objectTwo) int compare(ObjOne, ObjTwo)
It is necessary to modify the class whose A separate class can be created in order to instance is going to be sorted. sort the instances..
Only one sort sequence can be created. Many sort sequences can be created. It is frequently used by the API classes. It used by third-party classes to sort instances.
What is a Thread? In Java, "thread" means two different things: An instance of class java.lang.Thread. A thread of execution. An instance of Thread is just…an object. Like any other object in Java, it has variables and methods, and lives and dies on the heap. But a thread of execution is an individual process (a "lightweight" process) that has its own call stack. In Java, there is one thread per call stack—or, to think of it in reverse, one call stack per thread. Even if you don't create any new threads in your program, threads are back there running.