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

Showing posts with label CORE JAVA. Show all posts
Showing posts with label CORE JAVA. Show all posts

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:

Sunday, 23 May 2021

What is NullPointerException in Java with Examples

 Java "NullPointerException" Program

Here we are going to learn what NullPointerException in java with an example. So let's start the simple java null pointer exception program.

When we call any method by using any reference which is assigned null value then nullpointerexception occurs in java. Let's take a simple example of Java NullPointerExcepton which is given below.

NullPointerException Example in Java

class NullPointerExceptionExample
{
public void show()
{
System.out.println("not running");
}
public static void main(String args[])
{
NullPointerExceptionExample npl = null;//assigning null value to this reference
npl.show();
}
}

Now above java program will throw NullPointerException.

So, here we learned what is null pointer exception in java and when it occurs in java programs.


Share:

Sunday, 1 April 2018

What is the difference between C++ and Java

Difference Between C++ and Java 

Difference Between C++ and Java Programming Language

Here we going to see what is the difference between C++ and Java Programming language. Both programming language are used for software development for different-different purpose.

Here we will discuss java vs c++ differences with point-to-point.

Let's start main differences between java and c++ programming language.


Java vs c++ is also important question for both core java interviews and c++ interviews .

C++ Programming Language

  • C++ was developed in 1979.
  • C++ is invented by Bjarne Stroustrup.
  • C++ is platform-dependent programming language.
  • C++ is mainly used for windows applicaton or system or desktop application.
  • C++ supports pointer concept.
  • C++ supports goto statement.
  • C++ supports multiple inheritance.
  • C++ supports structures and union concepts.
  • C++ requires explicit memory management.
  • C++ supports both call by reference and call by value.
  • C++ supports operator overloading concept.
  • C++ is compiled programming language.
  • C++ supports conditional inclusion e.g #ifdef, #ifndef.
  • C++ does not allow documentation comment.
  • C++ does not have built-in support for threads.

Java Programming Language

  • Java was developed in 1995.
  • Java is invented by James Gosling.
  • Java is platform-independent programming language.
  • Java is mainly used for web application, desktop application, mobile application and enterprise application.
  • Java does not supports pointer concept.
  • Java does not supports goto statement.
  • Java does not supports multiple inheritance through class but it can be possible by using interface concept in java.
  • Java does not support structure and union concepts.
  • Java provides automatic garbage collection for mamory mangement.
  • Java supports only call by value.
  • Java does not support operator overloading. Supports only method overloading and method overrding.
  • Java is both compiled and interpreted programming language.
  • Java does not support conditional compilationa and inclusion.
  • Java allows documentation comment.
  • Java provides built-in supports for threads.

Here we discussed main differences between java and c++ programming language one by one.


                    Difference between HashSet and HashMap in Java.
                    Difference between String and StringBuffer.
Share:

Monday, 27 November 2017

How To Use Scanner Class In Java

Scanner Class in Java

How to use Scanner Class in Java

In this article, We will see how to use scanner class in java with the help of some basic and easy java programs.

Java scanner class is a predefined class Which is used for reading the input or data from the keyboard given by the user.

Scanner class is a final class in java and it extends Object class and implements Closeable, AutoCloseable, and Iterator interfaces. 

For example

public final class Scanner
extends Object
implements Iterator<String>, Closeable

Java scanner class is used for obtaining the input of primitive data types e.g int, double, etc. and String type.


How to Import Scanner Class

Scanner class is predefined class which is available in java.util.* package.

If you want to use Scanner class in your java programs you have to import Scanner class in your programs.

java.util.Scanner;


Java Scanner Class Constructors

There are lots of constructors of scanner class but some of them are given below.

1) Scanner(java.io.File source)

Constructs a new scanner that produces values scanned from the specified path.

2) Scanner(java.io.InputStream source)

Constructs a new scanner that produces values scanned from the specified input stream.

3) Scanner(java.lang.readable source)

Constructs a new scanner that produces values scanned from the specified source.

4) Scanner(java.lang.String source)

Constructs a new scanner that produces values scanned from the specified string.


Methods of Scanner Class in Java

There are many methods defined in the Scanner class and by the help of scanner class method we can read the the input from the console or keyboard easily. Some Scanner class methods are given below.

1) public byte nextByte()

This method is used to read the data as byte value.

2) public short nextShort()

This method is used to read the data as short value.

3) public int nextInt()

This method is used to read the data as integer value.

4) public long nextLong()

This method is used to read the data as long value.

5) public float nextFloat()

This method is used to read the data as float value.

6) public double nextDouble()

This method is used to read the data as double value.

7) public char nextChar()

This method is used to read the data as character value.

8) public boolean nextBoolean()

This method is used to read the data as boolean value i.e true/false

9) public String nextLine()

This method reads any kind of data in the form of String.

10) public String next()


Declaration of Scanner Class in Java

Before going to learn examples of Scanner class see the declaration of Scanner class.

Scanner sc = new Scanner(System.in);

Explanation:

Scanner(System.in) = This constructor creates an object of Scanner class with the object of InputStream class.

in = This is object of an InptutStream class.

System = System is a class and object 'in' is declared in System class as static data member.

System.in = Helps to read the input data from the console.

Let's see some Scanner class examples in java.


1) Scanner Class in Java Example

This is simple scanner class in java example where we will get input of int, double, types.

import java.util.Scanner;
class Demo1
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);

System.out.println("Enter your Age");
int age = sc.nextInt();
System.out.println("Your age is : "+age);

System.out.println("Enter your Marks");
double db = sc.nextDouble();
System.out.println("Your marks is : "+db);

}
}

Output: Enter your Age
             50
             Your age is : 50
             Enter your Marks
             65
             Your marks is : 65.0


2) Java Scanner Example With String

This is simple java scanner string example where we will learn how to take string input in java using scanner class.

import java.util.*;
class Demo2
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);

System.out.println("What is your first name");
String firstname = sc.next();
System.out.println("What is your last name");
String secondname = sc.next();

System.out.println("Your full name is : "+firstname+" "+secondname);
}
}

Output: What is your first name
              Anurag
              What is your last name
              Singh
              Your full name is : Anurag Singh

Read More:

Java Wrapper Classes Tutorial.
Java Abstract Class with example.
Java String Handling with example.

Here we discussed scanner class in java with the simple examples step-by-steps. I hope, you understand what is scanner class and some methods of scanner class in java.
Share:

Sunday, 17 September 2017

Difference Between class and interface in java


Class vs Interface in Java

class vs interface in java

In the last post we have already discussed what is the difference between abstract class and interface in java but here we will learn what is the difference between class and interface in java in detail.

Let's start what is the differences between class and interface in java with examples.


Java Class

  • In java 'class' keyword is used to create a class.
  • We can create object or instance of class easily in java.
  • We cannot achieve multiple inheritance through class.
  • The data members of a class are not public, static, and final by default.
  • The methods of class are not public and abstract by default.
  • We can declare default and parameterized constructor in a class.
  • A class can implement interface.
  • In a class method can be final and static.
  • Here 'extends' keyword is used for inheritance in class.
  • In a class, we can use public, private and protected access specifiers with method.
  • We can declare main() method in class.
  • There only concrete methods are allowed i.e with method{} body.
  • A class can extend only one class but implement any number of interfaces.

Simple Java Class Example

class Students
{
String name;
int rollno;
Students(String name, int rollno)
{
this.name = name;
this.rollno = rollno;
System.out.println(name+" "+rollno);
}
static void run()
{
System.out.println("Students participates in race program");
}
public static void main(String... s)
{
Students ss = new Students("sachin", 12);
Students.run();
}
}

Output: sachin 12
             Students participates in race program


Java Interface

  • In java 'interface' keyword is used to create interface in java.
  • We can't create object of an interface.
  • We can achieve multiple inheritance through interface in java.
  • The data members of an interface are public, static, and final by default.
  • The methods of an interface are public and abstract by default.
  • We cannot declare any kind of java constructor in an interface.
  • A class can implement an interface but an interface cannot extend a class or implement a class.
  • In an interface, methods cannot be static or final.
  • Here 'implements' keyword is used for inheritance in an interface.
  • In an interface, there only public specifier is allowed.
  • We can't declare main() method in an interface.
  • There only abstract method(without body) is allowed in an interface but now in java 8 version we can keep non-abstract method(with body).
  • An interface can extend multiple interfaces but cannot implement any interface.



Simple Example of Java Interface

This is the simple interface program in java with output.

interface My
{
void show();
}
interface My2
{
void display();
}
class Test implements My,My2
{
public void show()
{
System.out.println("Interface My");

}
public void display()
{
System.out.println("Interface My2");
}
public static void main(String args[])
{
Test t =
new Test();

t.show();
t.display();
}
}

Output: Interface My
             Interface My2


Use of Interface in Java

  • So that we can achieve fully abstraction in java.
  • So that we can achieve multiple inheritance in java.

In this article, you have learned what is the difference between class and interface in java.

I hope, this interface vs class article will be useful to you.



Share:

Wednesday, 16 August 2017

Serialization In Java


What is Serialization In Java?

Serialization In Java

Serialization in java is a mechanism to convert an object into a byte stream so that we can send over the network or save it as file or store into a database. Java serialization was introduced in JDK 1.1 and it is the most important feature of java.

Deserialization in java is just opposite of serialization in java. 

The main purpose of serialization in java is to converting an state of an object into a stream of bytes.

Here we will learn serialization and deserialization in java with example so that you can understand better.

Serialization is used in RMI, JPA, Hibernate etc.


Advantages of Serialization In Java

  1. It is mainly used to travel the object on the network.
  2. The entire process is JVM independent because object serialized on one platform and deserialized on an entirely different platform.


java.io.Serializable Interface

A class must implement java.io.Serializable interface to be eligible for serialization.

For example:

import java.io.Serializable;
class Student implements Serializable
{
int rollno;
String name;
Student(int rollno, String name)
{
this.rollno = rollno;
this.name = name;
}
}

In the above example, Student class implements Serializable interface . Now the object of the Student class can be converted into stream.

In java ObjectOutputStream and ObjectInputStream both are high-level stream that contains methods for serialization and deserialization of an object.


Java ObjectOutputStream Class

It is used to write primitive data types and objects to an output stream. Only objects that supports Serializable interface.

Methods of ObjectOutputStream

There are some methods of this class.

(1) public final void writeObject(Object obj)throws IOException 

This method writes the specified object to the ObjectOutputStream.

(2) public void flush() throw IOException

This method flushes the current output stream.

(3) public void close() throw IOException

This method closes the current output stream.



Java Serialization Example

In this class, we are going to serialize the object of Student class by the help of writeObject() method of ObjectOutputStream class because it provides the functionality to serialize the object. We will save the data of an object in a particular file name anu.txt.

import java.io.Serializable;
import java.io.*;
class Sample
{
public static void main(String args[])throws Exception
{
Student s = new Student(32, "amir");
FileOutputStream fout = new FileOutputStream(" anu.txt ");
ObjectOutputStream out = new ObjectOutputStream(fout);

out.writeObject(s);
out.flush();
System.out.println("task complete");
}
}

Output: task complete


Deserialization In Java

Deserialization in java is used to converting stream to object. Java deserialization is opposite of serialization.

Java ObjectInputStream Class

This class is used to deserialized the object of a class.

Methods of ObjectInputStream

There are some methods of output stream class which will help in deserializing an object.

(1) public final void readObject()throws IOException, ClassNotFoundException

This method read the object from the input stream.

(2) public void close()throws IOException

This method close object input stream.


Java Deserialization Example

This is simple example of deserialization of an object.

import java.io.Serializable;
import java.io.*;
class Sample1
{
public static void main(String args[])throws Exception
{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("anu.txt"));
Student ss = (Student)ois.readObject();
System.out.println(ss.rollno+" "+ss.name);
ois.close();
}

}

Output: 32 amir


Share:

Wednesday, 2 August 2017

Java Reflection

Reflection API in Java

Reflection Java

Java reflection basically provides the facility to inspect or examine and modifying the run-time behavior of a class or application at run-time.

In other words, Reflection is used to find out the details of any class at run-time. It is the most powerful concept and it is mostly used for backend in any application, not in the front end for the application.

It provides the facility to analyze the behavior of a class at run-time.

The java.lang.reflect and java.lang package provides the classes and interfaces to use for reflection.


The java.lang.Class class provides some methods that can be used to get the metadata i.e data about data, examine, modifying the run-time behavior of a class.


Uses of Reflection Java

The reflection API in java can be used in many areas like

  • Developing IDE(Integrated Development Environment) e.g MyEclipse, Eclipse, and NetBeans etc.
  • For debugging and Test tools.
  • Loading Drivers and providing dynamic information.


Drawbacks of Reflection In Java

There are some drawbacks of reflection in java and these are given below.
  • Poor performance.
  • Security risk.
  • High maintenance.
  • Oops concept violation.

Reflection in java is not used in normal programming but it is mostly used in java and j2ee frameworks e.g Hibernate framework, Struts framework, JUnit, etc.

Java.lang.Class class

The Class class belongs to the java.lang package. Class class provides method for (1) get the metadata of a class at run-time and (2) examine and change the behavior of a class at run-time.

Class class in java reflection is a final class and extends the super class of java i.e Object class and implements many interfaces like Serialization, Type, GenericDeclaration, and AnnotatedElement.

Instances of the class Class represent classes and interface in a running java application.

An enum is a kind of class and annotation is a kind of interface. Every array also belongs to a class that is reflected as a Class object that is shared by all arrays with the same element types and number of dimension. 

All the java primitives types(byte, short, char, int, long, float, double, and boolean) and the keyword void also represented as a Class object.

Class class has no public constructor.  


There are Some Methods of Class class

There are given below some commonly used method of Class class.

(1) public String getName()

This method returns the name of the entity(class, interface, array class, primitive types and void) represented by this Class's object in the form of String.

(2) pubic static Class forName(String classname)throws ClassNotFoundException

This method loads the class and returns the reference of Class class.

(3) public boolean isInterface()

This method checks if it interfaces or not.

(4) public boolean isArray()

This method checks if it is array or not.

(5) public boolean isPrimitive()

This method checks if it is primitive or not.

(6) public Class getSuperclass()

This method returns the super class reference.

(7) public Object newInstance()throws InstantiationException, IllegalAccessException 

Creates a new instance.


(8) public ClassLoader getClassLoader()

Returns the class loader for the class.

(9) public int getModifiers()

This method returns the java modifiers for this class or interface, encoded in an integer.

(10) public Method[] getDeclaredMethods()throws SecurityException

Returns the total number of methods of this class.



How to Get the Object of Class class

There are 3 methods to get the instance of Class class, They are
  1. forName() method of Class class
  2. getClass() method of Object class
  3. .class syntax
1) forName() Method of Class class

class Test
{
public static void main(String args[])throws ClassNotFoundException
{
Class c = Class.forName("Test");
System.out.println(c.getName());
}
}

Output : Test

In the above example, We have used forName() method, forName() method should be used if you know the fully qualified name of the class. It can't be used for primitive types.

2) getClass() Method of Object class

This method returns the instance of a Class class.

class Demo
{}
class Test
{
void showName(Object obj)
{
Class c = obj.getClass();
System.out.println(c.getName());
}
public static void main(String args[])
{
Demo d = new Demo();
Test t = new Test();
t.showName(d);
}
}

Output : Demo

3) isInterface() Method of Class class

interface My
{}
class My1
{}
class Test
{
public static void main(String args[])
{
try
{
Class c = Class.forName("My");
System.out.println(c.isInterface());

Class c1 = Class.forName("My1");
System.out.println(c1.isInterface());
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Output : true
Share:

Facebook Page Likes

Follow javatutorial95 on twitter

Popular Posts

Link

Translate