Java Python Interview Questions
Java Python Interview Questions
7. What are the four Java access modifiers, and how do you use them?
Ans: Default, public, private, and protected are the four access
modifiers available in Java. They're used to figure out who has access to
keywords or information in a class.
source: image
Because the thread may be accessing completely different global
variables relatively close together in memory, false sharing is difficult to
detect. The primary way to avoid false sharing, as with many concurrency
issues, is to review your code carefully and align your data structure with
the size of a cache line.
12. How do you explain the difference between JDK and JVM?
Ans: The Java Development Kit (JDK) and the Java Virtual Machine
(JVM) are the two components that allow Java to run on a device. The
apps we make with JDK's tools wouldn't run on people's phones or
tablets if they didn't have JVM.
16. What do you think the reason for the string's immutability is?
Ans: Immutable string is threadsafe. If a string were not immutable,
changing one reference would change the value of others.
17. Explain how to call the run() method of the Thread class.
Ans: If the thread was created using a separate Runnable object, the
run() method of the Thread class is called; otherwise, this method does
nothing and returns. The code specified in the run() method is executed
when the run() method is called. The run() method can be used multiple
times.
The start() method or the run() method can both be used to call the run()
method. However, using the run() method to call itself causes issues.
26. Explain the FailFast and FailSafe iterators and provide examples for
both.
Ans: In Java Collections, FailFast and FailSafe iterators are used.
FailFast iterators do not allow changes or modifications to Java
Collections, so they will fail if the most recent element is added to the
collection or an existing element is removed. FailFast iterators frequently
fail and throw a ConcurrentModificationException exception.
ArrayList, HashMap, etc., are examples of FailFast.
30. Is it possible to run some code before calling the primary method?
Ans: Yes, we can run any code before calling the primary method. When
creating the objects at the class's load time, we'll use a static code
block. Any statements in this static code block will be executed
simultaneously as the class is loaded, even before the primary method
creates objects.
31. How many times does the finalized method get invoked?
Ans: The Garbage Collector is the name of the finalized method. The
Garbage Collector only calls the finalize() method once for each object.
What should I do to prepare for a Java interview?
Java Fundamentals is an excellent place to start when preparing for a Java
interview.
Algorithms and Data Structures
Concepts - Object-Oriented.
The fundamentals of multithreading, concurrency, and threading.
Java Collections Framework is a framework for storing and retrieving
data in Java.
Conversion of data types and fundamentals
Array.
Collection of garbage.
In Java, what is the super keyword?
Definition and Application The super keyword refers to objects that belong to a
superclass (parent). It's used to access the superclass constructor and call
superclass methods. The super keyword is most commonly used to distinguish
between superclasses and subclasses that have methods with the same name.
What is garbage in Java?
The process by which Java programs perform automatic memory management is
known as garbage collection. Java programs are compiled into bytecode that can be
executed by a Java Virtual Machine, or JVM. Objects are created on the heap, a
portion of memory dedicated to the Java program when it runs on the JVM.
PYTHON
(Optional) For opening a text file using the above modes, we can also append ‘t’ with them as
follows:
read-only mode (rt)
write-only mode (wt)
read-write mode (rwt)
Similarly, a binary file can only be appropriately parsed and read by appending 'be with them
as follows:
read-only mode (RB)
write-only mode (wb)
read-write mode (rwb)
If you want to append the content in the files, we can also use the append mode (a):
For text files, mode would be 'at'
For binary files, it would be ‘ab’
2. What are the functions of file-related modules in Python? Give some examples of
such types of modules?
Ans. Python has many file-related modules that can manipulate text files and binary files in a
file system. It can also use them to pickle-unpickle data from files, while It can use some of
them to create a text or binary file, update their content, copy, delete etc.
Some such modules are os, os.path, and shutil.os. The os.path module has function to access
the file system, while the shutil.os module can also be used to copy or delete files.
3. What is the difference between opening a Python file versus using the 'with'
statement to do the same? What is the syntax to do that?
Ans. Using the 'with' statement in Python, one can open a file that gets automatically closed
as soon as the block of code, where 'with' is used, exits. In this way, we can opt not to use the
close() method.
with open("filename", "mode") as file_var:
def read_random_line(fname):
lines = open(fname).read().splitlines()
return random.choice(lines)
print(read_random_line ('randomfile.txt'))
5. Why isn’t all the memory deallocated after the end of execution of Python programs?
Ans.
When Python programs exit, especially those using Python modules with circular
references to other objects or the objects referenced from the global namespaces are
not always deallocated or freed.
Since it is not possible to deallocate those portions of memory that the C library
reserves.
On exit, because of having its efficient cleanup mechanism, Python would try to
deallocate every object.
6. What advantages does Numpy Arrays Have over Nested Lists for data analysis with
large datasets?
Ans. Numpy is written in C, so all its complexities are backed into a simple "to use module".
While Lists, on the other hand, are dynamically typed. Therefore, Python checks the data type
of each element every time it uses it. This makes Numpy arrays much faster than python lists.
Numpy has many additional functionalities that the list doesn't offer; for instance, It can
automate many things in Numpy.
Note that in the range 1:3, the elements are counted up to (the second index) 2 and not 3.
14. Mention the critical differences between using Django, Pyramid and Flask.
Ans.
Flask is a web “microframework” primarily built for a small application with more
detailed requirements. In Flask, you have to use some external libraries to achieve most
of the standard functionalities required. Flask has an "Always quickly ready to use"
approach.
Pyramid is built for larger applications. It provides flexibility and lets the developers use
the right tools required for their projects. Developers can choose the database, URL
structure, templating style and more. The "Pyramid" framework is heavily configurable.
One can also use Django for larger applications, just like Pyramid. But comes with a
specific structure and style/pattern of creating most functional components. It also
includes an ORM.
def Current_datetime(request):
now = datetime.datetime.now()
html = "<html><body>It is {} right now!</body></html>".format(now)
return HttpResponse(html)
19. How are sessions maintained and used in the Django framework?
Ans. Django provides session tokens that let you store and retrieve data on a per-site-visitor
basis. Django abstracts the process of sending and receiving cookies by placing a session ID
cookie on the client-side and keeping all the related data on the server-side.
21. How To Save An Image Locally Using Python Whose URL Address I Already
Know?
Ans. We will use the following code to save an image locally from an URL address:
import urllib.request
urllib.request.urlretrieve("URL", "local-filename.jpg")
22. Are there any tools for identifying bugs and performing static analysis in Python?
Ans. Yes, tools like PyChecker and Pylint are used as static analysis and linting tools,
respectively. PyChecker helps find bugs in the python source code files and raises alerts for
the code issues and complexities. Pylint also checks for the module's coding standards and
supports various plugins to enable custom features to meet this requirement.
24. What are decorators, and how are they used in Python?
Ans. Decorators in Python are essentially functions that add functionality to existing
functions in Python without changing the structures of the functions themselves. They are
represented by '@decorator_name' in Python and are called in a bottoms-up fashion. For
instance:
# decorator function to convert to lowercase
def lowercase_decorator(function):
def wrapper():
func = function()
string_lowercase = func.lower()
return string_lowercase
return wrapper
# decorator function to split words
def splitter_decorator(function):
def wrapper():
func = function()
string_split = func.split()
return string_split
return wrapper
@splitter_decorator # this is executed next
@lowercase_decorator # this is executed first
def hello():
return 'Hello World'
hello() # output => [ 'hello' , 'world' ]
The beauty of these decorators lies in the fact that besides adding functionalities to existing
outputs of the methods, they can even accept arguments for functions and further modify
those arguments before passing them to the function itself. The inner nested function, i.e.
'wrapper' function, plays significant role here. It is implemented in order to enforce
encapsulation and thus, keep itself hidden from the global scope.
# decorator function to capitalize names
def names_decorator(function):
def wrapper(arg1, arg2):
arg1 = arg1.capitalize()
arg2 = arg2.capitalize()
string_hello = function(arg1, arg2)
return string_hello
return wrapper
@names_decorator
def say_hello(name1, name2):
return 'Hello ' + name1 + '! Hello ' + name2 + '!'
say_hello('sara', 'ansh') # output => 'Hello Sara! Hello Ansh!'
25. Write a script to scrape data from IMDb top 250 movies page. It should only have
fields of movie name, year, and rating.
Ans. We can use the following script for the same:
from bs4 import BeautifulSoup
import requests
import sys
The script above will help scrape data from IMDb's top 250 list.
reduce(): Reduce repeatedly reduces a sequence in a pair-wise manner until it reaches a single
value.
Ex.
from functools import reduce
reduce( lambda x , y : x - y , [1,2,3,4,5] )
Output:
-13
29. How will you access the dataset of a publicly shared spreadsheet in CSV format
stored in Google Drive?
Ans. https://docs.python.org/3/We can use the StringIO module from the io module to read
from the Google Drive link, and then we can use the pandas library using the obtained data
source.
from io import StringIO
import pandas
csv_link = "https://docs.google.com/spreadsheets/d/..."
data_source = StringIO.StringIO(requests.get(csv_link).content))
dataframe = pd.read_csv(data_source)
print(dataframe.head())
31. What is classification? How would you import Decision Tree Classifier using the
"Sklearn" module?
Ans.
Classification refers to a predictive modelling process where a class label is predicted
for a given example of input data. It helps categorise the provided input into a label
that other observations with similar features have. For example, one can use it to
classify a mail, whether it is spam or not or check whether users will churn based on
their behaviour.
df
Output:
33. How do you split the data in train and test datasets in Python?
Ans. One can achieve this by using the "Scikit" machine learning library and importing the
"train_test_split" function in Python as shown below:
Import sklearn.model_selection.train_test_split
34. Is it possible to overfit a model if the data is split into train/test splits?
Ans. Yes, a common beginner’s mistake often is re-tuning a model or training new models
with different parameters even after seeing its performance on the test set.
Tips
It is always often recommended to research the company and your interview role. In addition,
the following tips are helpful for beginners when preparing for your next big tech interview:
1. Get your Basics Right: You cannot build a great building on a weak foundation. First of
all, I have a solid grip on Python fundamentals. You may refer to our free guided path.
2. Explaining concepts using examples: Anyone can theoretically answer the difference
between lists or dictionaries or the meaning of duck-typing in Python, but explaining
the idea using a program will set you apart from others. The interviewer will
understand that you know the concepts well.
3. OOPs: OOPs concepts are one of the most frequently asked questions in Python
interviews. It's recommended to have a clear understanding of the various concepts like
Inheritance, Encapsulation etc.
4. Data Structures and Algorithms: Get a good understanding of Python's various data
structures and algorithms. You may practice questions asked in top product based
companies on Code studio.
Python Interview Questions for Intermediates
1. What is a lambda function? How are these written in Python?
Ans. An anonymous function is also known as a lambda function. It can have any number of
parameters but can have just one statement.
Example
v = lambda p,q : p+q
print(v(7, 5))
Output: 12
The statement random.random() method returns a floating-point number in the range of [0,
1). This function generates random float numbers. Here, The methods used with the random
class are the bound methods of the hidden instances. The 'random' module instances can show
the multithreading programs that create different examples of individual threads.
**kwargs
**kwargs is a special syntax used as the function definition to pass a variable-length
keyword argument. Here, also, "kwargs" is used just as a convention. It can also use any
other name to represent "kwargs" here.
Keyworded argument means a variable that has a name when passed to the function. It
is a dictionary of the variable terms and their value.
def KeyArguments(**kwargs):
for key, value in kwargs.items():
print(key + ": " + value)
KeyArguments(arg1 = "item 1", arg2 = "item 2", arg3 = "item 3")
# output:
# arg1: item 1
# arg2: item 2
# arg3: item 3
Modules are simply Python files with a '.py' extension and can have a set of functions,
classes and variables defined. They can be imported and initialised using import statements if
partial functionality is required to import the requisite classes or processes, such as the foo
import bar.
Packages provide for hierarchical structuring of the module namespace using a '.' dot
notation. As modules help avoid clashes between global and local variable names, similarly,
packages can help prevent conflicts between module names.
Creating a package is easy since it also uses the system's inherent file structure that exists.
Modules combined into a folder are known as packages. Importing a module or its contents
from a package requires the package name as a prefix to the module's name joined by a dot.
To access the name attribute, we call the attribute using the dot operator as shown below:
print(employee.name)
# Prints -> Jeff
Output:
Name created = Arun
# protected members
_name = None
_age = None
# private members
__department = None
# constructor
def __init__(self, emp_name, age, department):
self._name = emp_name
self._age = age
self.__department = department
# public member
def display():
print(self._name + " "+ self._age + " " + self.__department)
14. Does python support 'multiple inheritance'? How does it work in Python? Explain
with an example.
Ans. Multiple Inheritance: This is achieved when one child class derives its members from
more than one parent class. All the features of parent classes are inherited in the child class.
class Parent1:
def parent1_func(self):
# Parent class2
class Parent2:
def parent2_func(self):
# Child class
def child_func(self):
self.parent1_func()
self.parent2_func()
# Driver's code
obj1 = Child()
obj1.child_func()
Output:
Hi, I am the first Parent
Hi, I am the second Parent.
self.name = name
self.age = age
self.salary = 20000
print(E1.name)
print(E1.age)
print(E1.salary)
Output:
XYZ
23
20000
# Constructor
self.name = name
class Child(Parent):
# Constructor
Parent.name = name
self.age = age
def display(self):
print(Parent.name, self.age)
# Driver Code
obj = Child("ChildClassInstance", 9)
obj.display()
# Constructor
self.name = name
class Child(Parent):
# Constructor
'''
'''
super(Child, self).__init__(name)
self.age = age
def display(self):
print(self.name, self.age)
# Driver Code
obj = Child("ChildClassInstance", 9)
obj.display()
pass
class Child(Parent):
pass
# Driver Code
We can check if an object is also an instance of a class by making use of isinstance() method:
obj1 = Child()
obj2 = Parent()
count = 0
text = fh.read()
if character.isupper():
count += 1
21. What is the 'main' function in Python? How do you invoke it?
Ans. In the world of programming languages, the 'main' function is considered as an entry
point for the execution for a program. But in Python, this is known that the interpreter serially
interprets the file line-by-line. This means that Python does not provide the 'main()' function
explicitly. But this doesn't mean that it a cannot simulate the execution of 'main'. It can do
this by defining the user-defined 'main()' function and using the python file's '__name__'
property. This '__name__' variable is a particular built-in variable that points to the current
module's name. This can be done as shown below:
def main():
print("Hi Ninja!")
if __name__ == "__main__":
main()
Output :
Hi Ninja!
22. Are there any tools for identifying bugs and performing static analysis in Python?
Ans. Yes, tools like PyChecker and Pylint are used as a static analysis and linting tools,
respectively. PyChecker helps find bugs in a python source code file and raises alerts for code
issues and complexity. Pylint checks for a module's coding standards and supports different
plugins to enable custom features to meet this requirement.
24. What are decorators, and how are they used in Python?
Ans. Decorators in Python are the functions that add functionality to an existing function in
Python without changing the structure of the function itself. They are represented by the
@decorator_name in Python and are called in a bottoms-up fashion. For example:
# decorator function to convert to lowercase
def lowercase_decorator(function):
def wrapper():
func = function()
string_lowercase = func.lower()
return string_lowercase
return wrapper
def splitter_decorator(function):
def wrapper():
func = function()
string_split = func.split()
return string_split
return wrapper
def hello():
The beauty of a decorator lies in the fact that besides adding functionality to the output of the
method, they are can even accept arguments for functions and can further modify those
arguments before passing them to the function itself. The are inner nested function, i.e.
'wrapper' function, plays a significant role here. It is implemented to enforce encapsulation
and thus, keep itself hidden from the global scope.
# decorator function to capitalize names
def names_decorator(function):
arg1 = arg1.capitalize()
arg2 = arg2.capitalize()
return string_hello
return wrapper
@names_decorator
26. What is the 'pandas' library used in Python? How is a 'pandas' data frame created?
Ans. Pandas is an open-source, python library used in data manipulation of applications that
require high performance. The name is derived from "Panel Data", that has multidimensional
data. It was developed in 2008 by Wes McKinney and designed for data analysis.
Pandas help perform five significant data analysis steps: load the data, clean/manipulate it,
prepare it, model it, and analyse it.
A data frame is a 2D mutable and tabular structure representing data labelled with axes - rows
and columns.
The syntax for creating data frame:
import pandas as pd
Here:
Data - Represents various forms such as series, map, ndarray, lists, dict etc.
index - Optional arguments that represent an index to row labels.
columns - Optional argument for column labels.
Type - the data type of each column. Again optional.
concat() method: This is used to stack data frames vertically. This is best used when the data
frames have the same columns fields. Syntax:
PD.concat([df1, df2])
join() method: It is used for extracting data from various data frames having one or more
common columns.
df1.join(df2)
28. Can you create a series from the dictionary object in pandas?
Ans. One-dimensional array capable of storing different data types is called series. We can
create pandas series from dictionary object as shown below:
import pandas as pd
series_obj = pd.Series(dict_info)
print (series_obj)
Output:
x 2.0
y 3.1
z 2.2
dtype: float64
If the index is not specified in the input method the keys of the dictionaries are sorted in
ascending order for constructing the indices. If the index is passed, then it will extract values
of the index label from the dictionary.
29. How will you identify and deal with missing values in a data frame?
Ans. We can identify if a data frame has missing values by using the 'IsNull()' and 'isna()'
methods.
Missing_data_count = df.isnull().sum()
We can handle missing values here by either replacing the values in the columns with 0 as
follows:
df['column_name'].fillna(0)
df = pd.DataFrame(data_info)
# To add new column third
df['third']=pd.Series([10,20,30], index= ['a','b','c'])
print(df)
# To add new column fourth
df['fourth'] = df['first'] + info['third']
print(df)
31. How will you delete indices, rows and columns from a data frame?
Ans.
To delete an Index:
Execute the 'del df.index.name' for removing the index by name.
Alternatively, the df.index. It can assign a name to None.
For example, if you have the below data frame:
Column 1
Names
John 1
Jack 2
Judy 3
Jim 4
# del df.index.name
print(df)
Column 1
John 1
Jack 2
Judy 3
Jim 4
32. How can the first row be re-indexed as the name of the columns in pandas?
Ans.
new_header = df.iloc[0] # grab the first row for the header
In addition to the above questions, one may also ask questions related to the Input and Output
of programs, Write specific programs, Packages, In-built methods.
Tips
It is always recommended to research the company and your interview role. In addition, the
following tips are helpful for beginners when preparing for your next extensive tech
interview:
1. Get your Basics Right: You cannot build a great building on a weak foundation. First of
all, I have a solid grip on Python fundamentals. You may refer to our free guided path.
2. Explaining concepts using examples: Anyone can theoretically answer the difference
between lists or dictionaries or the meaning of duck-typing in Python, but explaining
the idea using a program will set you apart from others. The interviewer will
understand that you know the concepts well.
3. OOPs: OOPs concepts are one of the most frequently asked questions in Python
interviews. It's recommended to have a clear understanding of the various concepts like
Inheritance, Encapsulation etc.
4. Data Structures and Algorithms: get a good understanding of Python's various data
structures and algorithms. You may practice questions asked in top product based
companies on Code studio.
Key Takeaways
The article discussed frequently asked Python interview questions for intermediates with
experience in working with Python for specific use-cases. Once you are done with this, you
may check out our Interview Preparation Course to level up your programming journey and
get placed at your dream company.
This article covered Intermediate questions. Basic and advanced level questions are discussed
in the following posts.
1. Python Interview Questions for Beginners
2. Python Interview Questions for Experts
Previous Article