EduArn – Online & Offline Training with Free LMS for Python, AI, Cloud & More

Showing posts with label Programming Basics. Show all posts
Showing posts with label Programming Basics. Show all posts

⭐ Top 15 Python Strings & Variables MCQs for Interview Preparation - By Eduarn


 

Python is widely used in interviews, coding tests, and real-world projects. Strings and variables are foundational concepts that often appear in both technical rounds and online coding assessments.

This blog post provides 15 multiple-choice questions (MCQs) to help you practice and strengthen your Python fundamentals.


MCQ 1

Which of the following is a valid variable name in Python?
A) 1variable
B) my-variable
C) _name
D) for

Answer: C) _name
Explanation: Variable names cannot start with a number, cannot use hyphens, and cannot be Python keywords.


MCQ 2

What is the output of:

x = "Python" print(x[1:4])

A) Pyt
B) yth
C) hon
D) Pyth

Answer: B) yth
Explanation: String slicing [start:end] includes start index but excludes end index.


MCQ 3

Which statement about Python strings is True?
A) Strings are mutable
B) Strings are immutable
C) Strings cannot be sliced
D) Strings can only contain letters

Answer: B) Strings are immutable


MCQ 4

How do you convert the string "123" into an integer?
A) int("123")
B) str("123")
C) float("123")
D) convert("123")

Answer: A) int("123")


MCQ 5

What will be the output of:

a = "hello" b = a print(a is b)

A) False
B) True
C) Error
D) None

Answer: B) True
Explanation: is checks object identity. Both variables point to the same string object.


MCQ 6

Which of the following is the correct way to take string input from a user?
A) input()
B) scanf()
C) cin >>
D) read()

Answer: A) input()


MCQ 7

What does len("Python") return?
A) 5
B) 6
C) 7
D) Error

Answer: B) 6
Explanation: The len() function returns the number of characters in a string.


MCQ 8

Which of the following will convert an integer to a string?
A) str(10)
B) int("10")
C) float(10)
D) string(10)

Answer: A) str(10)


MCQ 9

What will s = "Python"; s[0] = "p" do?
A) Change the first character
B) Throw an error
C) Replace all characters
D) None

Answer: B) Throw an error
Explanation: Strings are immutable; individual characters cannot be changed.


MCQ 10

How do you reverse a string s = "hello"?
A) s.reverse()
B) s[::-1]
C) reverse(s)
D) s.reverse_string()

Answer: B) s[::-1]


MCQ 11

Which of the following joins a list of words into a single string?

words = ["Python", "Rocks"]

A) " ".join(words)
B) words.join(" ")
C) join(words)
D) " ".concat(words)

Answer: A) " ".join(words)


MCQ 12

What will be the output of:

s = "banana" print(s.count("a"))

A) 1
B) 2
C) 3
D) Error

Answer: C) 3
Explanation: count() returns the number of occurrences of a character.


MCQ 13

Which of these will check if a variable x is a string?
A) type(x) == "str"
B) isinstance(x, str)
C) x.isstring()
D) str(x)

Answer: B) isinstance(x, str)


MCQ 14

What will s = " Python "; print(s.strip()) return?
A) "Python"
B) " Python "
C) "Python "
D) " Python"

Answer: A) "Python"
Explanation: strip() removes leading and trailing whitespace.


MCQ 15

Which of the following correctly swaps two variables without a temporary variable?

a = 5 b = 10

A) a = b; b = a
B) a, b = b, a
C) swap(a, b)
D) a = a + b; b = a - b; a = a - b

Answer: B) a, b = b, a


🎓 Conclusion

These 15 MCQs on Python Strings & Variables cover the most common topics asked in interviews and coding rounds. Regular practice will strengthen your understanding of:

  • Variable naming rules

  • String indexing and slicing

  • String methods (strip, join, count)

  • Type conversions (int, str)

  • Python fundamentals like immutability and variable swapping


🔥 Boost Your Python Skills with Eduarn

If you want to master Python and get interview-ready, check out our industry-focused courses at Eduarn.com.

  • Live coding sessions

  • Real-world projects

  • Interview preparation material

  • Beginner to advanced level learning

Learn Python, build your career, and crack your dream job with Eduarn.

Mastering Exception Handling in Java: A Complete Guide for Beginners

 

Java Exception Handling is a critical part of writing robust, error-resilient code. Whether you're building enterprise-grade applications or preparing for interviews, understanding how exceptions work in Java will set you apart as a confident developer.

In this blog, we’ll explore:

  • What exceptions are in Java

  • Types of exceptions

  • How to handle them with try-catch blocks

  • Best practices for exception handling

  • Real-world examples


     


What Is an Exception in Java?

An exception in Java is an unwanted or unexpected event that disrupts the normal flow of a program's execution. For example, dividing a number by zero or accessing a null object can result in runtime exceptions.

In Java, all exceptions are objects that inherit from the base class Throwable.


Exception Hierarchy in Java

Java's exception hierarchy is broadly divided into two categories:

1. Checked Exceptions

  • These are checked at compile time

  • The compiler ensures they are either caught or declared using the throws keyword

  • Common examples:

    • IOException

    • SQLException

    • FileNotFoundException

2. Unchecked Exceptions

  • These occur at runtime and are not checked during compilation

  • They usually indicate programming errors

  • Common examples:

    • NullPointerException

    • ArrayIndexOutOfBoundsException

    • ArithmeticException


How to Handle Exceptions in Java

Java provides a powerful mechanism to handle exceptions using try-catch blocks. Here’s the basic syntax:

try { // risky code } catch (ExceptionType name) { // handling code }

You can also use finally and throw/throws:

✅ Example:

public class ExceptionExample { public static void main(String[] args) { try { int result = 10 / 0; } catch (ArithmeticException e) { System.out.println("Cannot divide by zero."); } finally { System.out.println("Cleanup completed."); } } }

Output:

Cannot divide by zero. Cleanup completed.

Java Exception Keywords Explained

KeywordDescription
tryDefines a block of code to be tested for errors
catchHandles the exception thrown in try block
finallyExecutes code after try-catch, regardless of exception
throwManually throws an exception
throwsDeclares exceptions that a method can throw

Common Java Exceptions (With Examples)

1. NullPointerException

Occurs when you try to access a method or variable on a null object.

String text = null; System.out.println(text.length()); // Throws NullPointerException

2. ArrayIndexOutOfBoundsException

Occurs when an invalid array index is accessed.

int[] nums = {1, 2, 3}; System.out.println(nums[5]); // Throws ArrayIndexOutOfBoundsException

3. FileNotFoundException

Thrown when trying to access a file that doesn't exist.

FileReader file = new FileReader("data.txt"); // May throw FileNotFoundException

Best Practices for Exception Handling in Java

  1. Catch Specific Exceptions First
    Always catch more specific exceptions before generic ones like Exception.

  2. Avoid Swallowing Exceptions
    Don’t write empty catch blocks — always log or handle the exception meaningfully.

  3. Use Custom Exceptions
    For business logic errors, define your own exception classes that extend Exception or RuntimeException.

  4. Don’t Use Exceptions for Control Flow
    They are costly in performance and should only be used for error handling.

  5. Always Clean Up Resources
    Use finally blocks or try-with-resources for closing connections, streams, etc.

try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) { // use the reader } catch (IOException e) { e.printStackTrace(); }

Final Thoughts

Java’s exception handling mechanism is one of the most powerful features for writing safe and maintainable code. By using try-catch, understanding the difference between checked and unchecked exceptions, and following best practices, you can make your Java applications much more reliable.


Ready to Learn More?

Explore hands-on Java projects and deepen your backend skills with real-world use cases on Eduarn.com — our learning platform is free for learners and packed with practical content!

 Core Java Full Courses more