#Interview-134: Java: Can we have a catch block without a try block, or a try block without a catch block? In Java, a catch block cannot exist without a try block – that is simply not allowed. The catch block is meant to handle exceptions thrown from the corresponding try, so without try, it has no purpose and won’t even compile. Now coming to the second part - can we have a try block without a catch? Yes, we can, but only if we use a finally block. So the valid combinations in Java are: 1. try + catch 2. try + catch + finally 3. try + finally 4.Just try alone (not allowed) Example of valid try without catch: try { int data = 10 / 0; } finally { System.out.println("This will always execute"); } Even though an exception occurs, the finally block will still execute. So - a catch block must always follow a try, but a try block can exist without a catch only if it is followed by a finally block. #interviewprep #interview #testing #qajobs #jobs #jobsearch #jobseekers #hiring #hiringnow #lookingforjob #manualtesting #testautomation #bdd #cucumber #testng #etltesting #performance #apitesting #softwaretesting #manualtester #qatester
Java Try Block Without Catch or Finally
More Relevant Posts
-
#Interview-137: Java - What's the difference between final, finally and finalize? The difference between final, finally, and finalize is mainly about their purpose — one is a keyword, one is a block, and one is a method. final (Keyword): restrict something from being changed. • Final variable → value cannot be changed (constant) • Final method → cannot be overridden • Final class → cannot be inherited finally (Block): used in exception handling, and it always executes whether an exception occurs or not. • Used with try-catch • Typically used for cleanup (closing files, DB connections) finalize() (Method): was used for garbage collection cleanup before an object is destroyed. Deprecated in modern Java (Java 9+) In modern Java, instead of finalize(), we prefer using try-with-resources or explicit cleanup methods because finalize() is unreliable and deprecated. #interviewprep #interview #testing #qajobs #jobs #jobsearch #jobseekers #hiring #hiringnow #lookingforjob #manualtesting #testautomation #bdd #cucumber #testng #etltesting #performance #apitesting #softwaretesting #manualtester #qatester
To view or add a comment, sign in
-
#Interview-146: Java - What is String Constant Pool? String Constant Pool in Java is a special memory area inside the heap where Java stores string literals. Whenever we create a string like: String s1 = "Hello"; String s2 = "Hello"; Java doesn’t create two separate objects. Instead, it checks the String Constant Pool, and if the value already exists, it reuses the same object. So here, both s1 and s2 actually point to the same memory location. It’s mainly for memory optimization. Since strings are widely used and are immutable in Java, reusing them saves memory and improves performance. Now compare this with using new: String s3 = new String("Hello"); In this case, Java creates a new object in heap memory, even if "Hello" already exists in the pool. So: • "Hello" → goes to String Pool • new String("Hello") → creates a separate object outside the pool Important concept: immutability - Strings in Java are immutable, which means once created, their value cannot be changed. That’s what makes pooling safe—because no one can modify the shared string. #interviewprep #interview #testing #qajobs #jobs #jobsearch #jobseekers #hiring #hiringnow #lookingforjob #manualtesting #testautomation #bdd #cucumber #testng #etltesting #performance #apitesting #softwaretesting #manualtester #qatester
To view or add a comment, sign in
-
Java Developer Interview (3–4 Years Experience) – Here’s a concise list of questions I was asked along with one-liner answers -- Java 17 Features LTS version with features like records, sealed classes, pattern matching, and improved performance. -- what changes done in Java 17 for GC -- Java 8 Features Introduced lambda, streams, functional interfaces, Optional, and new Date-Time API. -- Functional Interface An interface with exactly one abstract method, used for lambda expressions. -- Static Method Use Cases Used for utility methods, shared logic, and when no object state is required. -- Method Reference Shorthand for lambda expressions using :: to directly refer to methods. -- Ways to Create Thread Thread class, Runnable, Lambda, Callable + Future, CompletableFuture. -- CompletableFuture Used for asynchronous programming and combining independent tasks. -- Stream API (Intermediate vs Terminal) Intermediate → lazy transformations; Terminal → triggers execution and gives result. -- map vs flatMap map = one-to-one transformation; flatMap = one-to-many + flattening. -- Memory Issues in Java 8 Heap OOM, Metaspace OOM, memory leaks, GC overhead, stack overflow. -- YAML vs Properties YAML is hierarchical and readable; properties are flat key-value pairs. -- Externalized Configuration (Spring Boot) Store config outside code using properties, YAML, env variables, or command-line. -- Circuit Breaker Prevents cascading failures by stopping calls to failing services and using fallback. -- Orchestration vs Choreography Orchestration = central control; Choreography = event-driven decentralized flow. -- Transaction Propagation Defines how transactions behave when one method calls another (e.g., REQUIRED, REQUIRES_NEW). -- Merging Arrays (Java 8) Use Stream/CompletableFuture to combine arrays cleanly. #java #interviewexperience ##interviewexperience #springboot #backenddeveloper #careergrowth #experiencedhire #javadeveloper
To view or add a comment, sign in
-
This are 5 tricky questions than made me in my last interview for a java developer position. 😅 How many of these would you answer right on the spot? 1️⃣ String Pool Mania String s1 = "Java"; String s2 = "Java"; String s3 = new String("Java"); System.out.println(s1 == s2); System.out.println(s1 == s3); System.out.println(s1.equals(s3)); What is the output? 2️⃣ Why can't static methods be overriding and only hidden ? 3️⃣ What happens if two threads update the same key ? 4️⃣ Why does Java support multiple inheritance of type (interfaces) but not multiple inheritance of state (classes)? 5️⃣ Dependency Injection: Field vs. Constructor 🏗️ In a Spring Boot environment, why is Constructor Injection universally preferred over @Autowired on a field? Give me one reason that isn't "it's easier for unit testing." #Java #JavaDevelopment #JavaInterview #ProgrammingLife #BackendDeveloper #CodingQuiz #LearnToCode #JavaCommunity #TechInterview #ProgrammingTricks
To view or add a comment, sign in
-
#Interview-143: Java - Can you create an object of an interface? Why or Why not? No, we cannot directly create an object of an interface in Java. An interface is just a blueprint, not a complete implementation. It only contains method declarations (at least conceptually), and doesn’t provide the full behaviour needed to create an object. We can create a reference of an interface, but the actual object will be of a class that implements that interface. Can we ever “create” an interface object? Indirectly, yes. We can use: Anonymous classes OR Lambda expressions (for functional interfaces). #interviewprep #interview #testing #qajobs #jobs #jobsearch #jobseekers #hiring #hiringnow #lookingforjob #manualtesting #testautomation #bdd #cucumber #testng #etltesting #performance #apitesting #softwaretesting #manualtester #qatester
To view or add a comment, sign in
-
Most Java developers fail interviews not because of coding… but because they don’t know ADVANCED Java concepts. Here are the 30 most asked Advanced Java interview questions for Java Developer roles (India + Global): 1. Difference between JDK, JRE, and JVM? 2. How does JVM work internally? 3. What are ClassLoaders? Explain types. 4. Difference between == and equals()? 5. Why is String immutable in Java? 6. Difference between String, StringBuilder, and StringBuffer? 7. How does HashMap work internally? 8. Why HashMap allows one null key? 9. Difference between HashMap and ConcurrentHashMap? 10. What is fail-fast vs fail-safe iterator? 11. What is Garbage Collection? How does it work? 12. Difference between Minor GC and Major GC? 13. What are memory leaks in Java? 14. Stack memory vs Heap memory? 15. What is the difference between shallow copy and deep copy? 16. What is Serialization? Why is it used? 17. Difference between transient and volatile? 18. What is reflection? Where is it used? 19. What are design patterns? Name a few used in Java. 20. Difference between abstract class and interface (real use cases)? 21. What is multithreading? 22. Difference between Runnable and Callable? 23. What is thread safety? 24. Difference between synchronized and Lock? 25. What is deadlock? How to prevent it? 26. What is ExecutorService? 27. Difference between wait() and sleep()? 28. What is Java Stream API? 29. Difference between map() and flatMap()? 30. What happens if main() method is not static? ⚠️ Interview Tip: If you can explain ANY of these questions with real examples, you are already ahead of 80% Java developers. #java #sql #hiring #microservices #dsa #linkedin For detailed Questions and Answers PDFs comment #cfbr
To view or add a comment, sign in
-
♨️ Java Interview Preparation| Day 43/90 Why Default & Static Methods were added in Java Interfaces? Before Java 8, interfaces were very strict — only abstract methods. But this created a big problem when evolving APIs. 👉 Imagine: If you add a new method to an existing interface, all implementing classes must update their code. This breaks backward compatibility ❌ 💡 Solution introduced in Java 8: ✅ Default Methods Allow method implementation inside interfaces Help extend interfaces without breaking existing code Provide backward compatibility 👉 Real-world example: List interface got new methods like sort() without breaking older implementations. ✅ Static Methods Belong to the interface, not to implementing classes Used for utility/helper methods related to the interface Called using Interface name (not object) 👉 Example: Comparator.comparing() – clean and reusable utility 🔥 Key Benefits: ✔ Backward compatibility ✔ API evolution becomes easy ✔ Less boilerplate code ✔ Better design flexibility 💬 In simple words: Default methods = “optional implementation” Static methods = “utility methods inside interface” #Java #Java8 #Programming #SoftwareDevelopment #InterviewPrep #Developers #Coding
To view or add a comment, sign in
-
-
Ever faced a bug in production where everything looked fine in code review, but failed because of one small issue? Java Bug Fix Interview Question: A payment service is getting duplicate transactions even though the API is called only once. Question: What is the bug in this code and how would you fix it? The code is not thread-safe. If two threads enter "processPayment()" at the same time, both can see "isProcessing = false" and process duplicate payments. Possible Fixes: - synchronized method - ReentrantLock - AtomicBoolean - Distributed lock for microservices This type of question is very common for backend, Java, multithreading, and production support interviews. #Java #Backend #Multithreading #InterviewQuestions #SpringBoot #JavaDeveloper #Concurrency #CodingInterview
To view or add a comment, sign in
-
-
🚀 Java Interview Series – Day 22 What is an Interface in Java? An interface in Java is a contract that defines what a class should do, but not how it should do it. It contains method declarations (by default public and abstract) that implementing classes must define. 🔹 Key characteristics: • Cannot have concrete method implementations (before Java 8) • Supports multiple inheritance • Helps achieve abstraction • Promotes loose coupling Why is this important? ✔ Enables flexible and scalable system design ✔ Allows multiple implementations of the same contract ✔ Makes code easier to test and maintain 💡 Example: A Payment interface can define a method pay(). Different classes like CreditCardPayment, UPIPayment, and NetBankingPayment implement it differently. ⚡ Key Insight: Modern Java (8+) allows: default methods (with implementation) static methods inside interfaces This makes interfaces more powerful than before. 💬 Interview Tip: Always mention: Interface = contract Multiple inheritance Real-world use case Java 8 enhancements Interfaces are at the heart of frameworks like Spring and are heavily used in building scalable and loosely coupled systems. #Java #JavaDeveloper #OOP #Interface #Abstraction #SoftwareEngineering #BackendDevelopment #CleanCode #TechInterview #CodingInterview #SystemDesign #Developers #LearningInPublic #CareerGrowth #IndiaJobs #USJobs #UKJobs #AustraliaJobs
To view or add a comment, sign in
-
-
🚀 Java Streams Interview Question Given a list of integers, remove duplicates and return a sorted list using Stream API. import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(5, 3, 8, 1, 3, 5, 9, 2, 8); List<Integer> sortedUniqueNumbers = numbers.stream() .distinct() .sorted() .collect(Collectors.toList()); System.out.println(sortedUniqueNumbers); } } Output: [1, 2, 3, 5, 8, 9] 🔹 distinct() removes duplicate elements 🔹 sorted() arranges the elements in ascending order 🔹 collect(Collectors.toList()) converts the stream back to a list #Java #JavaStreams #CodingInterview #Programming #Developers #SoftwareEngineering #BackendDevelopment
To view or add a comment, sign in
More from this author
-
Interview #443: Can you explain API chaining with an example?
Software Testing Studio | WhatsApp 91-6232667387 4h -
What is Agentic QA
Software Testing Studio | WhatsApp 91-6232667387 1d -
Interview #442: Postman - How do you manage different environments like QA, UAT, and Production?
Software Testing Studio | WhatsApp 91-6232667387 2d
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development