✨ Throw vs Throws In Java, exception handling is a critical part of writing robust and reliable applications. Understanding when to use throw and throws ensures cleaner code, better error handling. 🔹 throw Keyword throw is used inside a method to explicitly create and throw an exception. It is typically used for custom or conditional exception handling. ✅ Use case: Throwing a specific exception when a condition fails. throw new IllegalArgumentException("Invalid Input"); 🔹 throws Keyword throws is used in the method signature to declare that a method may throw one or more exceptions. It simply informs the caller to handle or propagate those exceptions. ✅ Use case: Declaring checked exceptions that the method does not handle internally. void readFile() throws IOException 🚀 Key Differences at a Glance ▪️ throw → Actively throws an exception. ▪️ throws → Declares possible exceptions. ▪️ throw → Used inside a method. ▪️ throws → Used in method declaration. ▪️ throw → Can throw only one exception at a time. ▪️ throws → Can declare multiple exceptions. #CoreJava #exceptionhandling #throwvsthrows #Programming
Java Exception Handling: throw vs throws
More Relevant Posts
-
🔑 Java String Insights I Learned Today 🚀 • String is immutable — methods like concat() do not modify the original string unless reassigned • s.concat("programming") returns a new string, original s remains unchanged • trim() removes leading & trailing spaces, but quotes are only for code, not output • Output of trim() is java, not "java" • Use String.valueOf() to convert primitive types → String safely • split() works exactly on the delimiter you specify split(",") ≠ split(", ") • concat() has O(n) time complexity because Java copies characters into a new string • For heavy string manipulation, prefer StringBuilder 📌 Small details in Strings = BIG difference in understanding Java. Frontlines EduTech (FLM) #java #strings
To view or add a comment, sign in
-
🔹 What is a String? In Java, a String is an object that represents a sequence of characters enclosed in double quotes (" "). Strings are immutable, meaning their value cannot be changed once created, and they use UTF-16 encoding internally. 🔹 Types of Strings Java provides different types of classes to work with strings based on mutability and thread-safety: String – Immutable and thread-safe. StringBuffer – Mutable and thread-safe; suitable for multi-threaded environments. StringBuilder – Mutable and not thread-safe; ideal for single-threaded programs. 🔹 Why We Use Strings Strings are essential for handling text data in applications: User input and output Authentication and authorization (username/password) API requests and responses Logging and messaging File and data processing 🔹 Advantages of Strings Immutable → ensures data integrity and security Thread-safe → safe in concurrent programs Memory-efficient → uses String Constant Pool for literals Rich API → provides powerful built-in methods for manipulation #Java #CoreJava #StringsInJava #JavaBasics #Programming #LinkedInLearning #JavaInterview
To view or add a comment, sign in
-
-
One of the Most Frequently Asked Java Questions - Yet Still Ignored What is an Immutable Class in Java? How to Create One? An immutable class in Java is a class whose object state cannot be changed after it is created. Once initialized, the data remains constant throughout the object’s lifetime. Why immutable classes matter • Thread-safe by design (no synchronization needed) • Easier to reason about and debug • Safer for use as keys in HashMap / elements in HashSet • Prevents accidental data modification Classic example: String, Integer, LocalDate How to create a custom immutable class in Java 1. Declare the class as final Prevents subclassing, which could alter immutability. 2. Make all fields private and final Ensures fields are assigned only once. 3. Initialize fields using a constructor only 4. Do not provide setter methods 5. Return defensive copies for mutable fields Especially important for objects like List, Date, Map. Follow me on LinkedIn : https://lnkd.in/dE4zAAQC #Java #JavaDeveloper #Programming #SoftwareEngineering
To view or add a comment, sign in
-
🚀 Java Concept: Understanding Var-args (Variable Number of Arguments) We can pass a flexible number of parameters to a method without overloading it multiple times. That’s where Var-args comes in. In Java, Var-args allows a method to accept zero or more arguments of the same type. 🔹 Syntax ----------------- public static void printNumbers(int... nums) { for (int num : nums) { System.out.println(num); } } we can now call this method in multiple ways: printNumbers(1); printNumbers(1, 2, 3); printNumbers(5, 10, 15, 20); 🔹 Why Varargs is powerful ✅ Reduces method overloading ✅ Cleaner and more readable APIs ✅ Great for utility methods and frameworks ✅ Internally treated as arrays (so performance is predictable) 🔹 Important Rules Varargs must be the last parameter in the method A method can have only one varargs parameter It is treated as an array inside the method. Code: --------- void log(String level, String... messages) // Valid void log(String... messages, int code) // ❌ Invalid In real-world applications (like logging frameworks, APIs, and microservices), varargs help make APIs flexible and developer-friendly. Small features like this often make a big difference in writing clean, maintainable code #Java #Programming #SoftwareEngineering #BackendDevelopment #CleanCode #LearningEveryday #Microservices
To view or add a comment, sign in
-
🚀 Exploring Java 17 Features – Modern Java at Its Best Java 17 is a Long-Term Support (LTS) release and brings several modern features that improve code readability, maintainability, and efficiency. Here are some standout features: 🔹 1️⃣ Records – Immutable Data Classes Records provide a concise way to create immutable data classes without writing boilerplate code for constructors, getters, equals(), hashCode(), or toString(). public record Person(String name, int age) {} Person p = new Person("Durga Prasad", 25); System.out.println(p.name()); // Durga Prasad ✅ Why use Records? Less boilerplate Immutable by default Ideal for DTOs and simple data carriers 🔹 2️⃣ Pattern Matching in Switch Statements Switch statements now support type patterns, making code cleaner and safer. Example : Object obj = "Hello"; switch (obj) { case String s -> System.out.println("String: " + s); case Integer i -> System.out.println("Integer: " + i); default -> System.out.println("Other type"); } ✅ Benefits: Combines type checking and casting in one step Reduces verbose if-else chains 🔹 3️⃣ Enhanced Pseudo-Random Number Generators Java 17 introduces new interfaces and implementations for random number generation. They are more flexible, secure, and performant. RandomGenerator generator = RandomGenerator.of("L64X128MixRandom"); System.out.println(generator.nextInt(1, 100)); ✅ Advantages: Multiple algorithms to choose from Better performance and reproducibility More control over random number generation #Java17 #Records #PatternMatching #RandomGenerator #JavaDeveloper #CleanCode #BackendDevelopment
To view or add a comment, sign in
-
what is the output of the below code? String text = " "; System.out.println(text.isEmpty()); System.out.println(text.isBlank()); The output of the provided Java code will be: false true Here is a breakdown of why: text.isEmpty() returns false because the string " " contains a space character, meaning its length is not zero. isEmpty() only returns true for an empty string (""). text.isBlank() returns true because the string " " contains only whitespace characters. The isBlank() method, introduced in Java 11, checks if a string is empty or contains only whitespace.
To view or add a comment, sign in
-
💡 Day 24/30 — Annotations in Java: metadata that drives frameworks Today I learned how annotations add extra information to your code, and how frameworks use that information to activate behavior. [Video Link] - https://lnkd.in/ghbSkrxG 🔵 Examples we use every day @Override prevents accidental mistakes @Deprecated warns when something is unsafe @Test triggers JUnit @FunctionalInterface ensures one abstract method Annotations improve quality, safety, and tooling. 🧩 Creating your own annotation You can define custom behavior: @interface Loggable {} And then apply it: @Loggable public void process() {} A framework can scan the classpath and add: logging security checks validation caching This is how Spring Boot works internally. 🔐 Retention policy matters We decide where the annotation exists: SOURCE → only in code CLASS → in bytecode RUNTIME → available to reflection Frameworks love RUNTIME. ⭐ Key takeaway Annotations enable clean, declarative programming — you annotate your intent and let the framework do the rest. Tomorrow: Day 25 — JVM internals: how Java actually runs your code #Java #Annotations #SpringBoot #SoftwareEngineering #CleanCode #LearningChallenge
To view or add a comment, sign in
-
Statement: If a Java class is not created or not present, compilation gives cannot find symbol, and if missing at runtime, JVM throws ClassNotFoundException or NoClassDefFoundError #what is the reason? ans: (class loader sub system). 1.First, the JVM requests the Application ClassLoader to load the required class. 2.The Application ClassLoader delegates the request to the Extension ClassLoader. 3.The Extension ClassLoader further delegates the request to the Bootstrap ClassLoader. 4.The Bootstrap ClassLoader searches for the class in the bootstrap classpath. 5.If the class is found, it is loaded immediately and the process stops. 6.If the class is not found, the request is delegated back to the Extension ClassLoader, which searches in the extension classpath. 7.If still not found, the Application ClassLoader searches in the application classpath. 8.If the class is not found in any classpath, the JVM throws a ClassNotFoundException or NoClassDefFoundError (depending on the situation). This diagram show what we discussed above in the text
To view or add a comment, sign in
-
-
Recently, I spent some time revisiting Java Generics, and it explained me why they are such an important part of writing clean and reliable Java code. Generics allow us to define classes and methods that work with different data types while still providing compile-time type safety. This helps avoid unexpected runtime errors and makes the code easier to understand and maintain. A common problem without generics is relying on Object and manual type casting, which can easily lead to ClassCastException at runtime. Generics solve this by letting the compiler enforce the correct type usage. For example, imagine a box that is meant to store just one kind of thing at a time. class GiftBox<T> { private T gift; public void put(T gift) { this.gift = gift; } public T open() { return gift; } } public class GenericsExample { public static void main(String[] args) { GiftBox<String> messageBox = new GiftBox<>(); messageBox.put("Happy Birthday"); GiftBox<Integer> chocolateBox = new GiftBox<>(); chocolateBox.put(10); System.out.println(messageBox.open()); System.out.println(chocolateBox.open()); } } Here, the compiler ensures that a String box only contains strings and an Integer box only contains integers. #Java #JavaGenerics #Programming
To view or add a comment, sign in
-
💡 Creating Threads in Java Using the Thread Class In my previous post, we understood what multithreading is and why it is important. Now, let’s look at the first approach to achieve multithreading in Java — 👉 Extending the Thread class. 🔍 How this approach works Create a class that extends Thread Override the run() method (this contains the task to execute) Create an object of the thread class Call start() to begin execution ⚠️ Important Note: Never call run() directly — it behaves like a normal method. Always call start() because it creates a new thread and internally invokes run(). 🌍 Real-world example Imagine a kitchen in a restaurant 🍽️ One chef is cooking, another is plating, and another is serving — all tasks happen at the same time, not one after another. This is exactly how threads work in Java. 💻 Simple Code Example class MyThread extends Thread { public void run() { System.out.println( "Task running in: " + Thread.currentThread().getName() ); } } public class Demo { public static void main(String[] args) { MyThread t1 = new MyThread(); MyThread t2 = new MyThread(); t1.start(); t2.start(); } } ✅ Key Points to Remember ✔ run() defines the task ✔ start() creates a new thread ✔ Multiple threads run concurrently ✔ Output order may vary — this is normal in multithreading 🔜 Next Post: We’ll see the second approach — 👉 Implementing the Runnable interface, which is more flexible and commonly used. #Java #Multithreading #ThreadClass #CoreJava #TapAcademy #JavaDeveloper
To view or add a comment, sign in
-
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