Java Interview Prep
jautomation_ava interview questions.pdf
PDF
answer all the question 1-125 questions
The document contains a comprehensive set of Java interview questions, covering topics like Java basics,
OOP concepts, collections, exception handling, and various programming tasks. Since answering all 125
questions here isn't practical in a single response, I can:
1. Provide answers in batches (e.g., Java basics first, then OOP, then collections, etc.).
2. Generate a structured document with all the answers.
3. Focus on specific areas you're preparing for.
Let me know which approach works best for you! 🚀
ok answers me in batches (e.g., Java basics first, then OOP, then collections, etc.).
Let's start with Java Basics (Questions 1-24).
Java Basics
1. What is JDK?
JDK (Java Development Kit) is a software development kit used to develop Java applications. It
includes JRE (Java Runtime Environment), compiler (`javac`), and development tools like debuggers
and profilers.
2. Which is the latest version of Java?
The latest version of Java keeps updating. You can check the latest version on the Oracle website.
3. Explain the advantages of Java.
Platform-independent (Write Once, Run Anywhere)
Object-oriented
Secure (Bytecode, Security Manager)
Multi-threaded
Robust (Exception handling, Memory management)
Rich API and huge community support
4. Explain `javac` and `java` commands and which folder they are available in.
`javac`:Java compiler used to compile `.java` files into bytecode (`.class` files).
`java`:Java interpreter that runs the compiled bytecode.
These commands are available in the `/bin` directory of the JDK installation.
5. What is the signature of the main method?
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/20
java
public static void main(String[] args)
`public` - Accessible from anywhere.
`static` - No need to create an object.
`void` - Does not return anything.
`String[] args` - Accepts command-line arguments.
6. Explain keywords. List some keywords in Java.
Keywords are reserved words that have special meanings in Java. Examples:
`class`, `public`, `static`, `void`, `int`, `if`, `else`, `return`, `try`, `catch`, `finally`,
`this`, `super`, etc.
7. Explain identifiers in Java.
Identifiers are the names of variables, methods, classes, or interfaces. They must start with a letter,
`_`, or `$`, and cannot be a keyword.
8. Explain literals in Java.
Literals are fixed values assigned to variables. Examples:
Integer literals (`10, 20`)
Floating-point literals (`3.14, 2.5f`)
Character literals (`'A'`)
String literals (`"Hello"`)
Boolean literals (`true, false`)
9. Why is Java platform-independent?
Java code is compiled into bytecode, which runs on any system with a JVM (Java Virtual Machine),
making Java platform-independent.
10. Is JVM platform-independent?
No, JVM is platform-dependent as each operating system has its own implementation of JVM.
11. Difference between compiler and interpreter?
Compiler: Converts the whole source code into machine code at once (e.g., `javac`).
Interpreter: Executes the code line by line (e.g., `java` for bytecode execution).
12. What is Rule and Convention?
Rules are strict guidelines (e.g., Java keywords cannot be used as variable names).
Conventions are best practices (e.g., class names should start with an uppercase letter).
13. Explain JRE (Java Runtime Environment).
JRE includes JVM and libraries required to run Java applications but does not include development
tools like the compiler.
14. Explain variables in Java and different types of variables.
Local Variables - Declared inside methods, exist only within the method.
Instance Variables - Declared inside a class but outside a method, belong to objects.
Static Variables - Declared using `static`, shared among all instances of the class.
15. Mention all primitive data types in Java.
Integer types: `byte`, `short`, `int`, `long`
Floating-point types: `float`, `double`
Character type: `char`
Boolean type: `boolean`
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/20
16. Explain primitive variables.
Primitive variables store actual values (e.g., `int x = 10;`).
17. Explain reference variables.
Reference variables store addresses of objects rather than actual data (e.g., `String s = new
String("Hello");`).
18. What is a String in Java?
A `String` in Java is an object that represents a sequence of characters and is immutable.
19. Explain methods in Java and why we use methods.
Methods are reusable blocks of code that perform specific tasks, improving modularity and
reusability.
20. Write the general syntax for a method.
java
returnType methodName(parameters) {
// method body
}
21. What is the default execution method in Java?
The `main` method is the entry point of execution in Java.
22. Can we execute a Java program without a `main` method?
No, unless using a static block in older versions (before Java 7). From Java 7 onward, `main` is
mandatory.
23. Can we compile a Java program without the `main` method?
Yes, compilation will succeed, but execution will fail.
This covers Java Basics (1-24). Let me know if you need any clarification or want me to proceed with
OOP Concepts next! 🚀
proceed with OOP Concepts next!
Object-Oriented Programming (OOP) in Java (Questions 25-50)
Class and Object
25. What is an Object?
An object is an instance of a class that contains state (fields/attributes) and behavior (methods).
Example:
java
class Car {
String color = "Red";
void drive() { System.out.println("Car is moving"); }
}
public class Main {
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/20
public static void main(String[] args) {
Car myCar = new Car(); // Object creation
System.out.println(myCar.color);
myCar.drive();
}
}
26. What is a Class?
A class is a blueprint for objects. It defines attributes (fields) and behaviors (methods).
27. Explain Members of a Class.
Fields (Instance variables)
Methods
Constructors
Static and non-static blocks
Inner classes (if any)
28. Explain Static Members and Non-Static Members of a Class.
Static Members: Shared across all instances, belong to the class. Declared using `static`.
Non-Static Members: Unique to each object.
29. Difference Between Static and Non-Static Members
| Static Members | Non-Static Members | |---------------|--------------------| | Shared among all objects |
Separate for each object | | No need to create an object | Requires object creation | | Uses
`ClassName.member` | Uses `objectName.member` | | Example: `static int count;` | Example: `int
age;` |
30. What are Global Variables?
Variables declared outside any method but inside a class. Example:
java
class Test {
static int x = 10; // Global static variable
int y = 20; // Global non-static variable
}
31. How to Access Static and Non-Static Global Variables?
Static: `ClassName.variableName`
Non-Static: `objectName.variableName`
32. Default Values for Global Variables, Reference Variables, Boolean Variable?
Integer types → `0`
Floating types → `0.0`
Boolean → `false`
Object references → `null`
33. Difference Between Local and Global Variables?
Local Variables: Declared inside methods, accessible only within the method.
Global Variables: Declared at class level, accessible across methods.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 4/20
34. How to Declare Constant Variables in Java?
Use the `final` keyword:
java
final int MAX_SPEED = 120;
35. Can We Declare a Final Global Variable Without Initializing?
No, it must be initialized either at the time of declaration or inside a constructor.
Blocks in Java
36. Explain Static Blocks and Non-Static Blocks.
Static Block: Runs once when the class is loaded.
Non-Static Block: Runs each time an object is created.
37. When Does a Static Block Get Executed?
When the class is loaded into memory. It executes only once.
38. When Does a Non-Static Block Get Executed?
When an object is created, it executes before the constructor.
Methods and Constructors
39. What Does a Method’s Return Type Signify?
It specifies what type of value the method returns. Example:
java
int sum(int a, int b) {
return a + b; // Return type is int
}
40. Can We Develop a Method Without a Return Type?
Yes, by using `void`:
java
void printMessage() {
System.out.println("Hello!");
}
41. What is the Data Type of a Reference Variable in Java?
It is a class type, not a primitive type. Example:
java
String s = new String("Hello"); // Reference variable
42. What Are Constructors? Types of Constructors?
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 5/20
Constructors initialize objects when they are created.
Types of Constructors:
Default Constructor
Parameterized Constructor
Copy Constructor (not explicitly supported in Java)
43. What is the Default Constructor?
A constructor with no parameters. Example:
java
class Car {
Car() { System.out.println("Car created!"); }
}
44. What is Constructor Overloading? Why Do We Use It?
Defining multiple constructors with different parameters in the same class.
It helps in flexible object creation.
java
class Car {
Car() { System.out.println("Default Car"); }
Car(String model) { System.out.println("Car Model: " + model); }
}
45. What is `this()` Calling Statement? Why Do We Use It?
It is used to call another constructor in the same class.
java
class Car {
Car() { this("Default Model"); }
Car(String model) { System.out.println(model); }
}
46. What is Recursion?
A method calling itself until a base condition is met. Example:
java
int factorial(int n) {
if (n == 1) return 1;
return n * factorial(n - 1);
}
47. What Happens If Recursion Is Used in Constructor Overloading?
It leads to infinite recursion and causes a StackOverflowError.
48. What is `this` Keyword?
Refers to the current object.
Used to differentiate instance variables from local variables.
49. Explain the Use of `this` Keyword?
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 6/20
Access instance variables.
Call another constructor (`this()`).
Pass the current object as a parameter.
50. Explain "Has-A" Relationship?
Also known as Composition.
Example:
java
class Engine { }
class Car {
Engine engine; // Car HAS-A Engine
}
This completes OOP Basics (Class & Object, Methods, Blocks, Constructors). Next, I’ll cover
Inheritance, Polymorphism, Abstraction, and Encapsulation (Questions 51-94). Let me know if you
want any modifications before proceeding! 🚀
next question covercover Inheritance, Polymorphism, Abstraction, and Encapsulation (Questions 51-
94).
Inheritance, Polymorphism, Abstraction, and Encapsulation (Questions 51-94)
Inheritance (51-58)
51. What is Inheritance? Types of Inheritance?
Inheritance allows a class to acquire properties and behaviors of another class.
Types of Inheritance in Java:
1. Single Inheritance – One class inherits another.
2. Multilevel Inheritance – Chain of inheritance.
3. Hierarchical Inheritance – Multiple classes inherit from one.
4. Multiple Inheritance (via Interfaces) – Java doesn’t support direct multiple inheritance due
to ambiguity.
52. What is the `extends` keyword?
Used to inherit from a class.
java
class Parent { }
class Child extends Parent { }
53. Does Java support multiple inheritance? Justify.
No, Java does not support multiple inheritance with classes to avoid Diamond Problem.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 7/20
Java achieves multiple inheritance using interfaces.
54. What is the Diamond Ambiguity Problem?
When two parent classes have the same method and a child class tries to inherit both, ambiguity
occurs.
Java solves this by disallowing multiple inheritance with classes.
55. Explain `super()` and `super` keyword.
`super()` calls the parent class constructor.
`super` accesses the parent class’s members (methods/variables).
56. Difference between `this()` and `super()`.
| `this()` | `super()` | |----------|----------| | Calls current class constructor | Calls parent class
constructor | | Used for constructor chaining in the same class | Used to call the base class
constructor | | Must be the first statement in a constructor | Must be the first statement in a
constructor |
57. Difference between `this` and `super` keyword.
`this` → Refers to the current object.
`super` → Refers to the parent class object.
58. What is Constructor Chaining?
Calling one constructor from another in a sequence.
java
class A {
A() { System.out.println("A"); }
}
class B extends A {
B() { super(); System.out.println("B"); }
}
Polymorphism (59-72)
59. What is Method Overloading? Example?
Same method name, different parameters.
java
class MathOperations {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
}
60. Why Do We Need Method Overloading?
Improves code readability and allows flexibility in method calls.
61. What is Method Overriding? Example?
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 8/20
Same method name and parameters, different implementation in subclass.
java
class Parent {
void display() { System.out.println("Parent"); }
}
class Child extends Parent {
void display() { System.out.println("Child"); }
}
62. Can We Override Static Methods?
No, static methods belong to the class and cannot be overridden.
63. What is Type Casting?
Converting one data type into another.
64. What is Primitive Casting?
Implicit (Widening) – Smaller type → Bigger type (`int` → `double`).
Explicit (Narrowing) – Bigger type → Smaller type (`double` → `int`).
65. What is Auto Widening and Explicit Narrowing?
Auto Widening: `int` → `long` → `float` → `double`
Explicit Narrowing: `double` → `float` → `long` → `int`
66. What is Auto Upcasting and Explicit Downcasting?
Upcasting (Automatic):
java
Parent p = new Child();
Downcasting (Explicit):
java
Child c = (Child) p;
67. Can We Achieve Object Casting Without Inheritance?
No, object casting is possible only with inheritance.
68. Can We Achieve Downcasting Without Upcasting?
No, downcasting requires prior upcasting.
69. What is Polymorphism?
One interface, many implementations.
Types:
1. Compile-time (Method Overloading)
2. Runtime (Method Overriding)
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 9/20
70. What Are the Different Types of Polymorphism?
Compile-time polymorphism → Method Overloading
Runtime polymorphism → Method Overriding
71. When Does Java Throw `ClassCastException`?
When downcasting fails.
72. What is the Use of `instanceof` Operator?
Checks if an object is an instance of a class.
java
if (obj instanceof String) { }
Abstraction (73-90)
73. What are Abstract Methods?
Methods without body, implemented by subclasses.
74. What is an Abstract Class?
A class that cannot be instantiated and may have abstract methods.
75. Why Can’t We Instantiate an Abstract Class?
Because it may contain undefined methods.
76. What is the Rule for Subclass of an Abstract Class?
Must implement all abstract methods or be declared abstract.
77. Can an Abstract Class Inherit Another Abstract Class?
Yes.
78. Is an Abstract Class 100% Abstract?
No, it can have concrete methods.
79. What is an Interface in Java?
A 100% abstract class with only method signatures.
80. Difference Between Abstract Class and Interface?
| Abstract Class | Interface | |---------------|-----------| | Can have method implementations | Cannot
have method implementations (before Java 8) | | Supports constructors | No constructors | |
Supports instance variables | Only static & final variables |
81. Do Abstract Classes Have Constructors? Why?
Yes, for initializing common properties.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 10/20
82. Do Interfaces Have Constructors?
No.
83. Can We Instantiate an Interface?
No.
84. What is `implements` Keyword?
Used by a class to implement an interface.
85. Can an Interface Inherit Another Interface?
Yes, using `extends`.
86. How to Achieve Abstraction?
Using Abstract Classes and Interfaces.
87. Can We Declare Final Methods in an Interface?
No, methods in an interface are by default abstract.
88. Can We Declare a Final Abstract Class?
No, `final` prevents inheritance.
89. Can We Declare a Static Method in an Abstract Class?
Yes.
90. Can We Declare a Variable in an Interface Without Initializing?
No, all variables in an interface are public, static, and final.
Encapsulation (91-94)
91. What Are Different Access Levels in Java?
private → Accessible within the class.
default → Accessible within the same package.
protected → Accessible within the same package and subclasses.
public → Accessible everywhere.
92. What is a Singleton Class?
A class that allows only one instance.
java
class Singleton {
private static Singleton instance = new Singleton();
private Singleton() { }
public static Singleton getInstance() { return instance; }
}
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 11/20
93. What is Encapsulation?
Data hiding using private variables with public getters/setters.
94. What is a Java Bean Class?
A class with private properties, public getters/setters, and a no-arg constructor.
This completes Inheritance, Polymorphism, Abstraction, and Encapsulation (Questions 51-94). Let
me know if you want explanations for any topic or if I should proceed with Libraries and Exception
Handling (Questions 95-125)! 🚀
Libraries and Exception Handling (Questions 95-125)
Libraries and Exception Handling (Questions 95-125)
Object Class (95-104)
95. Which is the Supermost Class for All Classes in Java?
`java.lang.Object` is the parent class of all Java classes.
96. Explain `toString()`, `hashCode()`, `equals()` of the Object Class.
`toString()` → Returns string representation of an object.
`hashCode()` → Returns a unique integer for an object (memory-based).
`equals()` → Compares two objects for equality.
97. Can a Subclass Override `toString()`, `hashCode()`, and `equals()` of the Object Class?
Yes, for custom implementations.
98. Explain the `final` Method in Java.
Prevents method overriding. Example:
java
class Parent {
final void display() { System.out.println("Final method"); }
}
99. Explain the `final` Class in Java.
Prevents inheritance. Example:
java
final class A { }
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 12/20
100. What is the Use of `clone()` Method?
Creates an exact copy of an object.
101. What is a Marker Interface?
An interface without methods, used to mark a class for special behavior (e.g., `Serializable`).
102. Explain Arrays in Java.
A fixed-size data structure storing elements of the same type.
103. Difference Between Primitive Array and Derived (Class-Type) Array?
Primitive Array: Stores primitive values (`int[] arr = {1, 2, 3};`)
Derived Array: Stores object references (`String[] arr = new String[5];`)
String in Java (105-110)
105. Why Are Strings Immutable in Java?
Stored in the String Pool, shared by references.
Prevents modification after creation.
106. Can We Inherit the String Class?
No, `String` is `final`.
107. Behavior of `toString()`, `hashCode()`, `equals()` in `String` Class?
`equals()` → Compares values.
`hashCode()` → Returns unique integer based on content.
`toString()` → Returns the string itself.
108. What is the String Pool Area?
A special memory region where Java stores string literals.
109. Difference Between `==` Operator and `.equals()` Method?
`==` → Compares memory locations.
`.equals()` → Compares values.
110. Difference Between String, StringBuilder, and StringBuffer?
String → Immutable.
StringBuilder → Mutable, not thread-safe.
StringBuffer → Mutable, thread-safe.
Collections (111-117)
111. Explain List, Set, and Queue Types of Collections.
List → Ordered, allows duplicates (`ArrayList`).
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 13/20
Set → Unordered, no duplicates (`HashSet`).
Queue → FIFO data structure (`LinkedList` as Queue).
112. Difference Between List, Set, Queue?
List → Allows duplicates, ordered.
Set → No duplicates, unordered.
Queue → Follows FIFO, processes elements sequentially.
113. Features of `ArrayList` and `LinkedList`?
ArrayList → Fast random access, slower insertions/deletions.
LinkedList → Fast insertions/deletions, slower access.
114. Features of `HashSet`, `LinkedHashSet`, and `TreeSet`?
HashSet → No order, allows `null`.
LinkedHashSet → Maintains insertion order.
TreeSet → Sorted order, no `null`.
115. Explain Generics and How to Apply It to Collections.
Allows type safety in collections.
java
List<String> list = new ArrayList<>();
116. What is Boxing and Unboxing in Java?
Boxing → Converting primitive to object (`Integer i = 10;`).
Unboxing → Object to primitive (`int x = i;`).
117. What Are Wrapper Classes? Why Are They Required?
Converts primitives into objects (`Integer`, `Double`).
Needed for collections that only store objects.
Exceptions in Java (118-125)
118. What is an Exception in Java?
An unexpected error disrupting normal execution.
119. How to Handle Exceptions?
Using `try-catch`:
java
try { int x = 10 / 0; } catch (ArithmeticException e) { System.out.println("Error!"); }
120. What Are Checked and Unchecked Exceptions?
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 14/20
Checked Exceptions → Checked at compile time (`IOException`).
Unchecked Exceptions → Checked at runtime (`NullPointerException`).
121. Difference Between Checked and Unchecked Exceptions?
Checked → Must be handled using `try-catch`.
Unchecked → Doesn’t require handling but may cause runtime errors.
122. Difference Between `throw` and `throws`?
`throw` → Used to explicitly throw an exception.
`throws` → Declares an exception in a method signature.
java
void test() throws IOException { throw new IOException("Error"); }
123. Use of `finally` Block?
Executes regardless of exception occurrence.
java
try { int x = 10 / 0; } catch (Exception e) { } finally { System.out.println("Always runs!"); }
124. Different Ways of Handling Checked Exceptions?
Try-catch block
Throws declaration
Custom exception handling
125. Difference Between `final`, `finally`, and `finalize()`?
`final` → Used for constants, prevents method overriding and inheritance.
`finally` → Block that always executes after `try-catch`.
`finalize()` → Called before object garbage collection.
This completes Libraries and Exception Handling (Questions 95-125)! 🚀
Would you like explanations for the programming questions (Collections, Strings, Arrays) next? 😃
programming questions (Collections, Strings, Arrays) IN PYTHON
Great! I'll provide Python implementations for the programming questions related to Collections,
Strings, and Arrays while maintaining logic similar to Java.
Collections (Lists, Sets, Dictionaries)
1️⃣ List-Based Programs (Equivalent to Java `ArrayList` and `LinkedList`)
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 15/20
1. How to copy or clone a list?
python
original_list = [1, 2, 3, 4, 5]
cloned_list = original_list.copy()
print(cloned_list) # Output: [1, 2, 3, 4, 5]
2. How to check if a list contains all elements of another list?
python
list1 = [1, 2, 3, 4, 5]
list2 = [2, 3, 4]
print(set(list2).issubset(set(list1))) # Output: True
3. How to convert a list to an array?
In Python, lists are dynamic arrays. But if needed, we can use NumPy:
python
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr) # Output: [1 2 3 4 5]
4. How to shuffle elements in a list?
python
import random
my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
print(my_list)
5. How to swap two elements in a list?
python
my_list = [1, 2, 3, 4, 5]
my_list[1], my_list[3] = my_list[3], my_list[1]
print(my_list) # Output: [1, 4, 3, 2, 5]
2️⃣ Set-Based Programs (Equivalent to Java `HashSet`)
6. How to copy a set?
python
original_set = {1, 2, 3, 4}
cloned_set = original_set.copy()
print(cloned_set) # Output: {1, 2, 3, 4}
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 16/20
7. How to find common elements in two sets?
python
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
common = set1.intersection(set2)
print(common) # Output: {3, 4}
3️⃣ Dictionary-Based Programs (Equivalent to Java `HashMap` and `TreeMap`)
8. How to copy a dictionary?
python
original_dict = {"a": 1, "b": 2}
cloned_dict = original_dict.copy()
print(cloned_dict) # Output: {'a': 1, 'b': 2}
9. How to find a key in a dictionary?
python
my_dict = {"a": 1, "b": 2}
print("b" in my_dict) # Output: True
10. How to get all keys from a dictionary?
python
print(my_dict.keys()) # Output: dict_keys(['a', 'b'])
String Programs
1. How to reverse a string?
python
s = "hello"
print(s[::-1]) # Output: "olleh"
2. Reverse a string using recursion
python
def reverse_recursive(s):
return s if len(s) == 0 else reverse_recursive(s[1:]) + s[0]
print(reverse_recursive("hello")) # Output: "olleh"
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 17/20
3. Count the number of words in a string
python
s = "Hello world this is Python"
print(len(s.split())) # Output: 5
4. Find duplicate words in a string and their occurrences
python
from collections import Counter
s = "apple banana apple orange banana apple"
words = s.split()
counter = Counter(words)
print(counter) # Output: {'apple': 3, 'banana': 2, 'orange': 1}
5. Check if a string is a palindrome
python
def is_palindrome(s):
return s == s[::-1]
print(is_palindrome("madam")) # Output: True
print(is_palindrome("hello")) # Output: False
6. Check if two strings are anagrams
python
def is_anagram(str1, str2):
return sorted(str1) == sorted(str2)
print(is_anagram("listen", "silent")) # Output: True
print(is_anagram("hello", "world")) # Output: False
Array-Based Programs
1. Find the sum of all elements in an array
python
arr = [1, 2, 3, 4, 5]
print(sum(arr)) # Output: 15
2. Find the min and max elements in an array
python
arr = [10, 5, 8, 1, 3]
print(min(arr)) # Output: 1
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 18/20
print(max(arr)) # Output: 10
3. Find the second min and second max element
python
arr = [10, 5, 8, 1, 3]
sorted_arr = sorted(set(arr))
print(sorted_arr[1]) # Second min (Output: 3)
print(sorted_arr[-2]) # Second max (Output: 8)
4. Find the average of an array
python
arr = [10, 20, 30, 40]
print(sum(arr) / len(arr)) # Output: 25.0
5. Reverse an array
python
arr = [1, 2, 3, 4, 5]
print(arr[::-1]) # Output: [5, 4, 3, 2, 1]
6. Find index of an element in an array
python
arr = [10, 20, 30, 40]
print(arr.index(30)) # Output: 2
7. Swap two elements in an array
python
arr = [1, 2, 3, 4]
arr[1], arr[3] = arr[3], arr[1]
print(arr) # Output: [1, 4, 3, 2]
8. Shift array elements to the right
python
arr = [1, 2, 3, 4, 5]
arr = [arr[-1]] + arr[:-1]
print(arr) # Output: [5, 1, 2, 3, 4]
Conclusion
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 19/20
This covers Collections, Strings, and Array programming questions in Python. 🐍
Would you like me to add explanations, optimize specific solutions, or include more advanced
implementations? 🚀
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 20/20