Loading...

Python Question & Answers

1. What is a Python ?

Answers : Python is a General Purpose, Dynamically Typed, High Level, Compiled and Interpreted, Garbage Collected & Purely OOPS language that supports Procedural, OOPs & Functional Programming.

2. Why Should You Learn Python ?

Answers :
1. Ease to Use & Learn
2. Object-Oriented Language
3. GUI Programming
4. Dynamic Memory Allocation
5. Versatility

3. What is a Class in Python ?

Answers : A Class is group of objects that have common property. It is a template or blue print from which objects are created.

4. What is an Object in Python ?

Answers : A runtime entity that has state and behavior is known as an Object.

5. Where is Python Used ?

Answers :
1. Data Science
2. Artificial Intelligence
3. Machine Learning
4. Data Analysis
5. Web Development

6. Where is Python Features ?

Answers :
1. Easy to Read
2. Object-Oriented Language
3. Cross Platform Compatibility
4. Interpreted Language
5. Dynamically Typed Language
6. High-Level Language
7. Integrated Language
8. GUI Programming
9. Multi Purpose Programming
10. Multiple Programming Paradigms
11. Automatic Memory Management
12. Multithreading & Multiprocessing

7. What is a Encapsulation in Python ?

Answers : Encapsulation is the process of wrapping up of data and methods together into single unit.

8. What is a Abstraction in Python ?

Answers : Abstraction is the process of hiding the implementation details and showing only functionalities to the user.

9. What is a Inheritance in Python ?

Answers : Inheritance is the method by which objects of one class get the properties of objects of another class. Inheritance represent IS-A relationship.

10. What is a Polymorphism in Python ?

Answers : Polymorphism is the ability of methods to behave differently based on the object calling it.

11. What is a Public ?

Answers : Public members are visible to sub classes if those sub classes are in the same package as the super class. For a sub class outside the packages, the public members can be access. (or) A class declaration with the public keyword gives all class from all packages access to the public class.

12. What is a Private ?

Answers : Private members are visible only current class only. Private member are not visible other classes in same package.

13. What is a Protected ?

Answers : Protected members are visible to sub classes if those sub classes are in the same package as the super class. For a sub class outside the packages, the protected members can be access through inheritance.

14. Is Python compiled or interpreted ?

Answers : Python is an interpreted language. This means that the code is executed line by line rather than compiling it into Machine Code Beforehand.

15. What is a Volatile ?

Answers : The volatile modifier tells the JVM that a thread accessing variable must always reconcile its own private copy of the variable with the master copy in memory.

16. What are the rules need to follow for Volatile Keyword ?

Rules :

1. Volatile applied variable only.

2. Volatile can be applied to static variables.

3. Volatile can not be applied to final variables.

4. Volatile is used in multi-processor environment.

5. Volatile and transient cannot come together.

17. What is a Transient ?

Answers : A Transient variable is a variable that can not be serialized. The transient keyword can be used to indicate the Java Virtual Machine that the variable is not part of the persistent state of the object. Transient is a keyword. Transient can be applied only variables. Transient variable can not be seriablized.

18. What is a Native Method ?

Answers : The Native method indicates that a method is implemented in platform dependent.

19. What are the rules need to follow for Native Keyword ?

Rules :

1. Native can be applies to only methods.

2. Native can be applied to static method also.

3. Native cannot be applied abstract.

4. Native can throw exception.

5. Native method is like an abstract method.

20. What is a Synchronized ?

Answers : Synchronized is a keyword. Synchronized can be applied only methods. Synchronized method can be accessed only one thread at a time. (or) The synchronized keyword indicates that a method can be accessed by only one thread at a time.

21. What is a Strictfp ?

Answers : Strictfp is a keyword in the Java programming language that restricts floating point calculations to ensure portability. The Strictfp was introduced into Java with the Java Virtual Machine version 1.2. Strictfp applied classes and methods only. Strictfp can be applied methods and classes.

22. What is an abstract ?

Answers : An abstract is a keyword. An abstract can be applied classes and methods.

23. What is an Abstract Method ?

Answers : An Abstract Method is a method that can be declared but not implemented.

24. What is an Abstract Class ?

Answers : An abstract class is a class that can be declared abstract key word. An abstract class may or may not be abstract methods. An abstract class can not make an object but can be sub classed.

25. What is a final ?

Answers : Final is a keyword. Final can be applied variables, methods and classes. Final Variables can not be modified. Final methods can be overloading but can not overriding. Final Classes can not extended.

26. What is a final Variable ?

Answers : A final variable that is not initialized at the time of declaration is known as blank final variable. It can be initialized only in constructor.

Example : final String panCardNo;

27. What is a static final Variable ?

Answers : A static final variable that is not initialized at the time of declaration is known as static blank final variable. It can be initialized only in static block.

Example : final String panCardNo;

28. What is a Throwable ?

Answers : Throwable is a class that represents all errors and exception which may occur in Java Virtual Machine.

29. What is a Exception ?

Answers : Exception is an event that disrupt the normal flow of the program.

30. What is a Exception Handling ?

Answers : Exception Handling is a mechanism to handle the run time error.

31. What is a Try Block ?

Answers : Try Block is used to enclose the code that might throw an exception. Try Block must be declared inside the method only.

32. What is a Catch Block ?

Answers : Catch Block is used to handle the exceptions. Catch Block must be declared after the try block inside the method only.

33. What is a Constructor in Java ?

Answers : Constructor is a special type of method that is used to initialize the objects. Constructors is invoked at the time of object creation. It constructs the value.

34. What is Inner Class ?

Answers : Inner Class is a class which is declared inside the class or interface.

35. What is SIB ?

Answers : SIB Stands for Static Initialization Block. SIB executes when the class gets loaded and executed only once in entire execution.

36. What is IIB ?

Answers : IIB Stands for Instance Initialization Block. IIB executes when the constructor is called but before the execution of constructor. So, it executes as many times as constructor gets executed.

37. Which is ListIterator ?

Answers : ListIterator is an interface. ListIterator can retrieve the elements in forward and backword direction from a collection object.

38. What is SerialVersionID ?

Answers : Whenever, an object is serialized the object is stamped with a version Id number for the object class.

Answers : serialVersionUID is a unique identifier assigned to a class during the serialization process. It ensures that a serialized object corresponds to the same class definition during deserialization.

39. Which is Resouce Bundle ?

Answers : The Resouce Bundle class is used to internationalize the message.

40. Which is a File ?

Answers : File is a class. File can not used to actually read (or) write data. File can used to making new files, searching for files, deleting files, making directories and working with pathes etc.

41. Which is FileReader ?

Answers : FileReader is a class. FileReader can used to read single character files, the whole stream of character (or a fixed number of characters.

42. Which is OutOfMemoryError in Java ?

Answers : OutOfMemoryError is a sub class of java.lang.VirtualMachineError and its throws by JVM when it ran out of heap memory.
C:\> java MyProgram -Xms 1024m - Xmx 1024m - XX:PermSize=64M -XX:MaxPermSize = 256m.

43. Which is the famous team used to describe Java ?

Answers : WORA mean Write One Run Anywhere. Java is guaranteed to be Write Once, Run Anywhere.

44. Why is SerialVersionUID Important ?

Answers : Serialization converts an object into a byte stream, enabling it to be saved to a file or transferred over a network. During deserialization, Java reconstructs the object from the byte stream. For this process to succeed, the serialVersionUID of the serialized object must match the serialVersionUID of the class being deserialized.

45. What is FileWriter ?

Answers : FileWriter is a class. FileWriter class is used to write single characters, the whole stream of characters (or) fixed number of character.

46. What is BufferReader ?

Answers : BufferReader is a class. BufferReader is used to read large chunks of data from a file at once and keep this data in a buffer.

47. Is it possible to re-throw exception ?

Answers : Yes, We can re-throw exceptions from catch block to another class where it can be handled.

48. What is the super class for all exceptions ?

Answers : Throwable is the super class of all exceptions in Java.

49. Can we define an interface inside the class ?

Answers : Yes, If we can define an Interface inside the class.

50. Can you store a primitive data type into a collection ?

Answers : No, Collections store only objects.

51. Can we intialize black final variable ?

Answers : Yes but only in Constructor.

52. Can you make List elements synchronized ?

Answers : Yes, Collections class provides methods to make List elements as synchronized.
public static List SynchronizedList(List list) { }

53. Can you make Set elements synchronized ?

Answers : Yes, Collections class provides methods to make Set elements as synchronized.
public static Set SynchronizedSet(Set set) { }
public static SortedSet SynchronizedSortedSet(SortedSet set) { }

54. Can you make Map elements synchronized ?

Answers : Yes, Collections class provides methods to make Map elements as synchronized.
public static Map SynchronizedMap(Map map) { }
public static SortedMap SynchronizedSortedMap(SortedMap map) { }

55. Can we override the overloaded methods ?

Answers : Yes, we can override the overloaded methods.

56. Can you declare the main method as final ?

Answers : Yes, such as public static final void main (String [] args) { }

57. Can you have virtual functions in Java ?

Answers : Yes, all functions in Java are virtual functions by default.

58. Can we override main() method ?

Answers : No, main() method is a static method and is thus not polymorphic.

59. Can we return any value in try block ?

Answers : Yes, we can return any value in try block.

60. Can we return any value in catch block ?

Answers : Yes, we can return any value in catch block.

61. Can we return any value in finally block ?

Answers : Yes, we can return any value in finally block.

62. Can we return any value in try, catch, finally block at a time ?

Answers : No, we can return any value either from try block or catch block or finally block.

63. Can we define a class inside the interface ?

Answers : Yes, If we define a class inside the interface.

64. Can we overload main() method ?

Answers : Yes, by method overloading. You can have any number of main() methods in a class by method overloading.

65. What is instanceOf Keyword ?

Answers : instanceof is a binary operator used to determine whether an object is an instance of a specific class, subclass, or implements a particular interface. It is also referred to as a "type comparison operator" because it compares an object's runtime type against a specified type.

66. is final method inherited ?

Answers : Yes, final method is inherited but you can not override it.

67. Can we call one constructor from another if a class has multiple constructor ?

Answers : Yes, use this() method.

Java Difference Interview Questions

1. Differentiate between xxxValue(), valueOf() and parseXXX() ?

xxxValue() valueOf() parseXXX()
Convert a wrapper to a Primitive Convert a String to a Wrapper Convert a String to a Primitive

2. Differentiate between Compiler and Interpreter ?

Compiler Interpreter
Compiler takes entire program as input Interpreter takes single instruction as input.
Intermediate object code is generated No intermediate object code is generated.
Conditional control statements are executed faster Conditional control statements are executed slower.
Memory requirement is more Memory requirement is less.
Program need not be compiled every time Every time higher level program is converted into lower level program.
Errors are displayed after entire program is checked Errors are displayed for every instruction interpreted.
Compiler Exmple : C, C++, Cobol Interpreter Example : Basic, Visual Basic, Python, Ruby, PHP, Perl, MatLab.

3. Differentiate between ArrayList and CopyOnWriteArray ?

Parameters ArrayList CopyOnWriteArray
Synchronized No Yes
Thread Safe No Yes
Iterator Fail Fast Fail Safe
Performance Fast Slow
Added Java 1.2 Java 1.5
Throw CurrentModificationException Yes No

4. Differentiate between Failsafe and Failfast?

Parameters Failsafe Failfast
Behavior Iterates over a copy of the collection to avoid errors Fails immediately upon detecting structural changes
Concurrent Modification Does not throw ConcurrentModificationException Throws ConcurrentModificationException
Implementation Uses a separate copy or snapshot during iteration Directly iterates over the actual collection
Performance Higher memory usage due to a copy More efficient as it does not create a copy
Examples CopyOnWriteArrayList, ConcurrentHashMap ArrayList, HashMap, HashSet

5. Differentiate between List and Set ?

Parameters List Set
Duplicates Allows duplicate elements Does not allow duplicate elements
Order Maintains insertion order Does not maintain insertion order except LinkedHashSet
Null Values Allows multiple null values Allows at most one null value
Performance Generally faster for indexed access Optimized for searching and uniqueness
Examples ArrayList, LinkedList HashSet, TreeSet, LinkedHashSet

6. Differentiate between HashMap and TreeMap ?

Parameters HashMap TreeMap
Ordering No specific order Maintains natural or custom (via Comparator) order
Performance Faster for most operations (O(1) for get/put) Slower (O(log n) for get/put) due to tree structure
Null Keys/Values Allows one null key and multiple null values Does not allow null keys, but allows null values
Underlying Structure Uses a hash table Uses a Red-Black tree
Examples HashMap, LinkedHashMap TreeMap

7. Differentiate between Stack and Queue ?

Parameters Stack Queue
Order Follows LIFO (Last In, First Out) Follows FIFO (First In, First Out)
Operations push, pop, peek add, remove, peek
Use Cases Backtracking, parsing Task scheduling, buffering
Examples Stack (Legacy class) LinkedList, PriorityQueue

8. Differentiate between Queue and Deque ?

Parameters Stack Queue
Order Follows FIFO Supports FIFO and LIFO
Operations add, remove, peek addFirst, addLast, removeFirst, removeLast
Examples LinkedList, PriorityQueue ArrayDeque, LinkedList

9. Differentiate between Singly Linked List and Doubly Linked List ?

Parameters Singly Linked List Doubly Linked List
Links Each node points to the next Each node points to both next and previous nodes
Memory Usage Requires less memory Requires more memory due to additional pointer
Traversal Can be traversed in one direction Can be traversed in both directions
Performance Simpler and faster Slightly slower due to additional operations

10. Differentiate between PriorityQueue and TreeSet ?

Parameters PriorityQueue TreeSet
Ordering Natural order or custom Comparator; duplicates allowed Sorted order, no duplicates
Null Values Does not allow null elements Does not allow null elements
Performance O(log n) for insertion/removaln O(log n) for insertion/removal
Use Cases Priority-based tasks, heaps Unique elements in sorted order

11. Differentiate between HashSet and TreeSet ?

Parameters HashSet TreeSet
Ordering No specific order Maintains sorted order
Null Values Allows one null element Does not allow null elements
Performance Faster (O(1) for most operations) Slower (O(log n) for operations)
Examples HashSet, LinkedHashSet TreeSet

12. Differentiate between Iterable and Iterator

Parameters Iterable Iterator
Definition Represents a collection that can be iterated Used to traverse through elements in a collection
Methods iterator() hasNext(), next(), remove()
Usage Enable for-each loop Enables manual iteration
Examples ArrayList, HashSet Returned by iterator() on collections

13. Differentiate between HashMap and TreeMap

Parameters HashMap TreeMap
Ordering No specific order Maintains natural or custom (via Comparator) order
Performance Faster for most operations (O(1) for get/put) Slower (O(log n) for get/put) due to tree structure
Null Keys/Values Allows one null key and multiple null values Does not allow null keys, but allows null values
Underlying Structure Uses a hash table Uses a Red-Black tree
Examples HashMap, LinkedHashMap TreeMap

14. Differentiate between List and Map

Parameters List Map
Data Structure Ordered collection of elements Key-value pairs
Duplicates Allows duplicates Keys must be unique, values can be duplicates
Null Values Allows multiple null values Allows one null key and multiple null values
Examples ArrayList, LinkedList HashMap, TreeMap

15. Differentiate between Singleton Class and Static Members ?

Singleton Class Static Members
Singleton is an object Static is not an object
Singleton can be extended/sub classed Static cannot be extended/sub classed
Singleton can be passed around as an object Static cannot be passed around as an object
Singleton can be garbage collected Static can not be garbage collected
Singleton class is a design pattern Static is a keyword
Singleton class can be overridden by extending Static method can not be overridden
Singleton class are bounded on runtime Static methods are bounded on compiler time

Note : Static provides better performance than Singleton Class.

16. Differentiate between Constructor and Method

Parameters Constructor Method
Purpose Used to initialize the state of an object. Used to exhibit the behaviour of an object.
Name It must have the same name as the class. Can have any name different from the class.
Return Type Does not have a return type, not even void. Must have a return type, can be void.
Calling Automatically called when an object is created. It must be called explicitly.
Inheritance It cannot be inherited. It can be inherited.
Overloading It can be overloaded. It can be overloaded and overridden.
Invoking It cannot be invoked explicitly, invoked by new. It can be invoked by object reference.
Default Version A default constructor is provided if none is specified. No default method is provided.

17. Differentiate between Comparable and Comparator ?

Comparable Comparator
Comparable provides only one sort of sequence Comparator provides multiple sort of sequence.
Comparable is used to compare itself by using with another object Comparator is used to compare two data types or objects.
Comparable provides only one method namely compareTo ( ) method Comparator provides two methods namely compare ( ) and equals ( ) methods.
Comparable is found in java.lang package where as Comparator is found in java.util package.
If we implement Comparable interface actual class is modified if we implement Comparator interface actual class is not modified.

18. Differentiate between CPP (C++) and Java ?

CPP (C++) Java
C++ has functions Java have methods.
C++ has destructors Java does not have destructors.
C++ has three access modifiers Java have four access modifiers.
C++ has goto statement Java does not have goto statement.
Pointers are available in C++ pointers are not available in Java.
C++ support multiple inheritance Java does not support multiple inheritance.
C++ is not a purely object-oriented programming language Java is a purely object-oriented programming language.
We can write C++ program without using a class or an object we cannot write Java Program without using a class or an object.

19. Differentiate between throw and throws ?

throw throws
Throw is used to handle user defined exception JVM handles the exceptions which are specified by thows.
Throw is used for to through exception system explicitly Throws is used for to throws exception means throws IOException and ServletException etc.
Throw is used to throw the exception to catch block and handle it throws is used to throw an exception from the method without handling that exception.

20. Differentiate between HashMap and CurrentHashMap ?

HashMap CurrentHashMap
HashMap is not a thread safe CurrentHashMap can allow a thread safe.
HashMap can allow one null key CurrentHashMap cannot allow null key.
HashMap can throw CurrentModificationException CurrentHashMap cannot throw CurrentModificationException.

21. Differentiate between HashTable and CurrentHashMap ?

CurrentHashMap HashTable
We will get thread safety without locking the total map object just with a bucket level lock. We will get thread safety by locking the whole map object.
At a time multiple threads are allowed to operate on map objects safely. At a time one thread is allowed to operate on a map object.
Read operation can be performed without lock but write operation can be performed with bucket level lock. Every read and write operations required total map object.
While one thread iterating map objects the other thread is allowed to modify the map and won't get ConcurrentModificationException. While one thread iterating map object the other threads are not allowed to modify the map otherwise we will get ConcurrentModificationException.
Iterator of ConcurrentHashMap is fail-safe and won't raise ConcurrentModificationException Iterator of HashTable is fail-fast and it will raise ConcurrentModificationException.
Null is not allowed for both keys and values. Null is not allowed for both keys and values.
Introduce in Java 1.5 Version Introduce in Java 1.0 Version

22. Differentiate between SynchronizedMap and HashTable ?

SynchronizedMap HashTable
We will get thread safety by locking the whole map object We will get thread safety by locking the whole map object.
At a time only one thread is allowed to perform any operation on a map object. At a time one thread is allowed to operate on a map object.
Every read and write operations required total map object Every read and write operations required total map object.
While one thread iterating map object the other threads are not allowed to modify the map otherwise we will get ConcurrentModificationException. While one thread iterating map object the other threads are not allowed to modify the map otherwise we will get ConcurrentModificationException.
Iterator of SynchronizedMap is fail-fast and it will raise ConcurrentModificationException Iterator of HashTable is fail-fast and it will raise ConcurrentModificationException.
Null is allowed for both keys and values Null is not allowed for both keys and values.
Introduce in Java 1.2 Version Introduce in Java 1.0 Version

23. Differentiate between SynchronizedMap and ConcurrentHashMap ?

SynchronizedMap ConcurrentHashMap
We will get thread safety by locking the whole map object We will get thread safety without locking the total map object just with a bucket level lock.
At a time only one thread is allowed to perform any operation on a map object. At a time multiple threads are allowed to operate on map objects safely.
Every read and write operations required total map object Read operation can be performed without lock but write operation can be performed with bucket level lock.
While one thread iterating map object the other threads are not allowed to modify the map otherwise we will get ConcurrentModificationException. While one thread iterating map objects the other thread is allowed to modify the map and won't get ConcurrentModificationException.
Iterator of SynchronizedMap is fail-fast and it will raise ConcurrentModificationException Iterator of ConcurrentHashMap is fail-safe and won't raise ConcurrentModificationException.
Null is allowed for both keys and values Null is not allowed for both keys and values.
Introduce in Java 1.2 Version Introduce in Java 1.5 Version

24. Difference between HashMap and IdentityHashMap ?

HashMap IdentityHashMap
HashMap implements the Map interface but it doesn't violate the map general contract. IdentityHashMap also implements the Map interface but it intentionally violates the map general contract.
HashMap uses object equality to compare the key and values. IdentityHashMap uses reference equality to compare the key and values.
HashMap uses the hashCode() method of HashMap class to find the bucket location. IdentityHashMap doesn't use the hashCode() method instead it uses the System.IdentityHashCode() method to find the bucket location.
HashMap uses chaining. IdentityHashMap uses a simple liner probe hash table.
To safely store the objects in HashMap the keys need to be immutable. IdentityHashMap doesn't require the key to be immutable.
HashMap performs slightly less than the IdentityHashMap. IdentityHashMap performs better than HashMap.