Let's learn java programming language with easy steps. This Java tutorial provides you complete knowledge about java technology.

Thursday 8 August 2024

What is IllegalArgumentException in Java with simple examples

 Java Illegal Argument Exception(i.e IllegalArgumentException in java)

In Java, an IllegalArgumentException is a runtime exception that is thrown to indicate that a method has been passed an illegal or inappropriate argument. This exception is typically used to enforce valid method arguments and catch potential bugs early in the development process. Here are some examples of when and how to use IllegalArgumentException.


Basic Usage Example

Suppose you have a method that calculates the square root of a number. You might want to ensure that the number is not negative, as the square root of a negative number is not defined in the realm of real numbers.

public class MathUtils {

    public static double calculateSquareRoot(double number) {

        if (number < 0) {

            throw new IllegalArgumentException("Number must be non-negative.");

        }

        return Math.sqrt(number);

    }


    public static void main(String[] args) {

        try {

            System.out.println(calculateSquareRoot(9)); // This will work fine

            System.out.println(calculateSquareRoot(-1)); // This will throw an exception

        } catch (IllegalArgumentException e) {

            System.err.println("Caught an exception: " + e.getMessage());

        }

    }

}

Example with Multiple Arguments

You can also use IllegalArgumentException for methods with multiple parameters. Consider a method that sets the dimensions of a rectangle:

public class Rectangle {

    private double width;

    private double height;


    public void setDimensions(double width, double height) {

        if (width <= 0) {

            throw new IllegalArgumentException("Width must be positive.");

        }

        if (height <= 0) {

            throw new IllegalArgumentException("Height must be positive.");

        }

        this.width = width;

        this.height = height;

    }


    public static void main(String[] args) {

        Rectangle rectangle = new Rectangle();

        try {

            rectangle.setDimensions(5, 10); // Valid

            rectangle.setDimensions(-5, 10); // Invalid, throws exception

        } catch (IllegalArgumentException e) {

            System.err.println("Caught an exception: " + e.getMessage());

        }

    }

}

Example with Collections

IllegalArgumentException is also useful for checking arguments related to collections, such as ensuring a list is not empty before performing operations on it.

import java.util.List;

public class ListUtils {

    public static int getFirstElement(List<Integer> list) {

        if (list == null) {

            throw new IllegalArgumentException("List must not be null.");

        }

        if (list.isEmpty()) {

            throw new IllegalArgumentException("List must not be empty.");

        }

        return list.get(0);

    }


    public static void main(String[] args) {

        List<Integer> numbers = List.of(1, 2, 3);

        try {

            System.out.println(getFirstElement(numbers)); // Prints 1

            System.out.println(getFirstElement(List.of())); // Throws exception

        } catch (IllegalArgumentException e) {

            System.err.println("Caught an exception: " + e.getMessage());

        }

    }

}

When to Use IllegalArgumentException

Invalid Argument Values: If a method receives arguments that are not valid according to its logic or purpose.
Preconditions: When you want to enforce preconditions on method parameters to prevent incorrect usage.
User Input Validation: When processing user input, IllegalArgumentException can be used to reject bad data.

Handling IllegalArgumentException

IllegalArgumentException is an unchecked exception (a subclass of RuntimeException). It doesn't require mandatory handling with a try-catch block, but it's often a good practice to catch it where appropriate to provide meaningful error messages or alternative flows in your application.

try {

    // Code that might throw IllegalArgumentException

} catch (IllegalArgumentException e) {

    // Handle the exception, log it, or recover

}


Share:

Thursday 6 July 2023

How to make Age calculator program in java

 Java Program for Age Calculator

Here we are going to learn most important program of java which is Age Calculator by this java example we will able to calculate age of users. So let's start making code for java age calculator.

import java.time.LocalDate;

import java.time.Period;

import java.util.Scanner;

public class AgeCalculator

{

public static void main(String args[])

{

LocalDate birthDate, currentDate;

Scanner scanner = new Scanner(Sytem.in);

System.out.print("Please Enter your birth date (yyy-mmm-ddd): " );

String birthDateSt = scanner.nextLine();

birthDate = LocalDate.parse(birthDateSt);

currentDate = LocalDate.now();

Period age = Period.between(birthDate, currentDate);

System.out.println("Your age is : "+age.getYears()+" years, "+age.getMonths+" month, and "+age.getDays+" days. ");

scanner.close();

}

}

By using above age calculator program we can easily calculate age.


Share:

Saturday 24 July 2021

Write a Java Program To Count Letters in String

How To Count Letters in String in Java


In the last post, we have discussed how to find character or character position in string in java with simple examples and now here we are going to create a simple example for how to count letters in java string with examples.

So let's start with a useful example for finding the number of letters in a given java String.

The below example gives you a total number of letters count in a given java string i.e (given string is "sun45tt" and letters in this give string is suntt i.e 5).

Java Program to Count Letters in String

class LettersCountInString
{
public static void main(String args[])
{
String str = "sun45tt";
int count = 0; 
for(int i = 0; i<str.length(); i++)
{
if(Character.isLetter(str.charAt(i)))
{
count++;
}
}
System.out.println(count);
}
}

Output: 5

Here we discussed, how to write a java program to count letters in string with a simple example.


Share:

Friday 23 July 2021

How Do I Find a Character in a String in Java

 Searching Characters in a String in Java

In the last article, we have learned how do I find a first non-repeated character in string in java and now here we are going to make a java program for how do I find a character in a string with a simple example.

Here we will find the index position of a character given in a java string by using the pre-defined method of a java String Object.

Here we will find the character position in a sting by using the indexOf( ) method of the String class.

So let's start searching for specific character in string.

Find Character in Java String

class FindingCharacterInString
{
public static void main(String args[])
{
String str = "how are you men";
int indexPosition = str.indexOf('a'); //finding character a String
System.out.println("Index Position of character a is  "+indexPosition);
}
}

Output : Index Position of character is 4

Note the above program for finding a character will give you the first occurrence of the character's position not the second occurrence of a character.

Let's understand by simple example where we again find the character in a string but with a different character.

class FindingCharacterInString
{
public static void main(String args[])
{
String str = "how are you men";
int indexPosition = str.indexOf('o'); //finding character String
System.out.println("Index Position of character is  "+indexPosition);
}
}

Output: Index Position of character is 1

So here we discussed some useful examples for how do i find a character in a String in java.
Share:

Monday 19 July 2021

How Do You Find The First Non Repeated Character of a String in Java

Find First Non Repeating Character in a String in Java 

Now Here we are going print First non repeated character in String in java through a simple example or java program so that you can understand well.

So let's start a simple java program for find the first non repeated character of a String.

For example, we take a string in  java like String str = "akalsys";

So in above string there is k is a first non repeated character in String.

Java Example for First Non-Repeated Character in String.

class FirstNonRepeatedCharacterInString
{
public static void main(String args[])
{
String str = "akalsys";
for(char ch : str.toCharArray( ))
{
if(str.indexOf(ch) == str.lastIndexOf(ch))
{
System.out.println(ch);
break;
}
}
}
}

Output : k

Above example will you give the k as output.

Here we learned, how to find the first non repeated character in java string with a simple example.

Share:

Facebook Page Likes

Follow javatutorial95 on twitter

Popular Posts

Translate