0%
Loading ...

Java Tutorials

This category contains Java basic tutorials

Thread class methods

In this tutorial, we will learn about Thread class methods. In the last tutorial, we already saw two thread class methods run() and start() method. There are a lot of other methods in Thread class. Check this following list. Method Description public void start() This method is used to start the execution of the thread. public void run() This method is used to describe the action in the thread. public final void setName(String name) This method is used to set the name of the thread. public final void setPriority(int priority) This method is used to set the priority of the thread. public final void join(long milliseconds) This method is used to block the current thread for specified milliseconds until another thread completes its execution or specified milliseconds passed public void interrupt() This method is used to interrupt a thread. public void stop() This method is used to stop a thread. public void suspend() This method is used to suspend a thread. public void resume() This method is used to resume the suspended thread. public final boolean isAlive() This method is used to check whether a thread is alive or not. public static void yield() This method is used to block currently running thread and allow other threads with the same property to run temporarily. public static void sleep(long milliseconds) This is used to block a thread for specific milliseconds. public static boolean holdsLock(Object x) This method will return true if the current thread holds the lock on the given Object. public static Thread currentThread() This method returns the reference of currently running thread. public static void dumpStack() This method prints the stack trace of currently running thread. public void destroy() This method is used to destroy the thread group. Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

Thread class methods Read More »

Thread in Java

In this tutorial, we will learn ways to create a Thread in Java. A Thread is a lightweight process and Java has a feature called multithreading which means we can run multiple threads simultaneously. There are two ways to create the thread in Java first one is by extending Thread class and the second one is by implementing Runnable interface. Creating a thread using Thread Class: In Java, we can inherit Thread class in our class to create threads. Thread class contain constructors and methods which makes it so easy to create and maintain a thread. Check out these few steps to create a thread using Thread class. First of all, inherit Thread class in your class. Override the run() method in your class. Use the start() method to start your thread. Check out the following example. To understand it more wisely. Example Program: //Inherting Thread class in Example class public class Example extends Thread{ //Overiding run method public void run(){ for(int i=0;i<5;i++){ System.out.println(i); } } public static void main(String args[]){ Example obj=new Example(); obj.start(); //using start() method to start thread } } Output: 0 1 2 3 4 Creating a thread using the Runnable interface: We know Multiple Inheritance is not allowed in Java and we know to perform multi-threading we have to inherit Thread class in our class. But in some scenarios, if a class already inheriting another class we cannot inherit Thread class. So in this kind of situation, we can implement Runnable interface to create a thread in class. Runnable interface contains only one method which is run() method. Example Program: //Implementing Runnable interface in Example class public class Example implements Runnable{ //Overiding run method public void run(){ for(int i=0;i<5;i++){ System.out.println(i); } } public static void main(String args[]){ Example obj=new Example(); Thread thread=new Thread(obj); thread.start();//using start() method to start thread } } Output: 0 1 2 3 4 It is important to note we know Runnable interface contains an only a single method which is run(). But we need the start() method to start a thread. So to get this start method we create an object of Thread class(check 12th line in the above example code) and we pass the object of our class in the constructor of Thread class. After that, we called the start method using thread class object. Here is another example program. In which you can see how we can directly define and override run() method in the constructor of the Thread class. Example Program: public class Example { public static void main(String args[]){ Thread thread=new Thread(new Runnable(){ public void run(){ for(int i=0;i<5;i++){ System.out.println(i); } } }); thread.start();//using start() method to start thread } } Output: 0 1 2 3 4   Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

Thread in Java Read More »

Multi-Threading in Java

In this tutorial, we will learn about Multi-Threading in Java. In java we can run more than one threads(a piece of code) simultaneously at the same time with the help of Multithreading and each piece code can perform a different task. Here thread means a lightweight process which can perform some task in the program. It is important to note that, in multithreading, all the threads share common resources(CPU). Before joining further let’s check out the life cycle of a thread. Life Cycle of a Thread: Every thread in Java goes through various stages all these all states together known as a life cycle of a thread. Check out the following illustration to see the life cycle of a thread. Now we will learn about each states of Life Cycle of Thread. Newborn: when we create a thread object. Then thread enters in the newborn state. After this, we use the start() method to start a newborn thread. Runnable: In this state, the thread is ready to run and waiting for the availability of the resources. In case all the threads in the program have equal priority then they will get time slots for execution First Come First Serve manner. Running: This is the state when a thread is running. Blocked: In case a thread is prevented to enter in running or runnable state also not dead it means the thread is in block statement. There are various methods which can move a thread into this blocked state such as suspend(), sleep(milliseconds), wait(). A thread can beck enter into running or runnable state from this state with the help of resume() and notify() methods. Dead: This is the last stage in the life cycle of a thread. If a thread completed executing it’s run() method, it is known as a natural death. But we can kill a thread using stop() method. Thread Priorities: We can set priority to each thread. When we set the priority of thread it helps thread scheduler to decide the order in which all the threads will run. Threads with high priority get the allocation of processor time before lower-priority threads. There is a total of three constants available in Thread class and we can use these constants to set the priority of Thread. MIN_PRIORITY NORM_PRIORITY MAX_PRIORITY This was a theory tutorial of Multithreading. In the next tutorial, we will create thread program so keep continue with the next tutorial. Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

Multi-Threading in Java Read More »

Custom Exception in Java

In this tutorial, we will learn about Custom Exception in Java. Custom Exceptions are also known as a user-defined exception. The main motive of creating a custom exception is to create a new exception according to project requirement. When you create a custom exception you have to inherit Exception class as a parent in your custom exception class. please check out the following example. Example Program: //creating an custom Exception class class MyCustomException extends Exception{ public MyCustomException(){ System.out.println(“Constucor of MyCustomException invoked”); } public String getMessage() { return “Hello, This is getMessage() in MyCustomException”; } } public class Example{ public static void main(String args[]){ try{ System.out.println(“In try block”); throw new MyCustomException(); //throwing exception explicitly }catch(MyCustomException e){ System.out.println(e.getMessage()); System.out.println(“In catch block”); } } } Output: In try block Constucor of MyCustomException invoked Hello, This is getMessage() in MyCustomException In catch block   Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

Custom Exception in Java Read More »

Throw keyword in Java

In this tutorial, we will learn about throw keyword in Java. The throw keyword in java is used to throw an exception explicitly. We can throw both kinds of checked and unchecked exceptions using this throw keyword. But we mainly use throw keyword to throw custom exceptions(also known as the user-defined exceptions). Check out the following syntax of throw keyword. throw objectOfExceptionClass; As in above syntax you can see to throw an exception first of all we have to write throw keyword then object of Exception class. Please check out the following example program. Example Program: public class Example { public static void main(String args[]) { try { System.out.println(“In try block”); throw new ArithmeticException(); } catch(ArithmeticException e) { System.out.println(“In catch block”); } } } Output: In try block In catch block   Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

Throw keyword in Java Read More »

Throws keyword in Java

In this tutorial, we will learn throws keyword in Java. There are many time when compiler finds some suspicious code that might throw a checked exception and warn programmers to solve exceptions. If programmer will not handle this kind of exceptions then the compiler will throw an error while compiling unreported exception XXX must be caught or declared to be thrown. In this kind of situation, we have two options whether to use a try-catch block to handle the exception or use throw keyword. The throw keyword works in a simple way when we write it with our suspicious code it means we will not handle this exception the caller of this function will solve the exception. If our code is in the main function then JVM will handle that exception. Check out the following example program. Example Program: public class Example { public static void main(String[] args) { Thread.sleep(100); // a checked exception System.out.println(“Owlbuddy”); } } Output: Example.java:5: error: unreported exception InterruptedException; must be caught or declared to be thrown Thread.sleep(10000); // a checked exception ^ 1 error Do not worry In case you don’t know what is Thread. You will get detail tutorials of Multi-Threading in upcoming tutorials. In above we have a checked exception that’s why our code is not compiling. Here we will rewrite the same code again what this time we will use throws keyword to solve this Exception. Example Program: public class Example { public static void main(String[] args) throws InterruptedException { Thread.sleep(100); // a checked exception System.out.println(“Owlbuddy”); } } Output: Owlbuddy Here is a question for you, do you know in the above example who is responsible for handling InterruptedException. If your answer is JVM then it’s right. Because here exception inside the main method. It is important to note that using throws keyword we are not handling any exception we are just delegating the responsibility of exception handling to the caller.  Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

Throws keyword in Java Read More »

Try Catch block in Java

In this tutorial, we will learn about Try Catch Block in Java. Using Try Catch block is the best way to handle exceptions in Java. We keep all the code that might throw an exception in the try block. The try block is followed by the catch and finally blocks. In this catch and finally blocks, we write code to handle the exception. try{ //Here is code that may throw an exception }catch(Exception_Class ref){ } Before going further, here we write a code(with exception) without Try Catch block: Example Program(without Try Catch Block) public class Example{ public static void main(String args[]){ System.out.println(“Ans of 10/2 =”+(10/2)); System.out.println(“Ans of 12/3 =”+(12/3)); System.out.println(“Ans of 5/0 =”+(5/0)); System.out.println(“Ans of 24/6 =”+(24/6)); System.out.println(“Ans of 8/2 =”+(8/2)); } } Output: Ans of 10/2 =5 Ans of 10/2 =4 Exception in thread “main” java.lang.ArithmeticException: / by zero at Example.main(Example.java:5)} As you can see in the above example program we got an ArithmeticException(Because we can’t divide a number by zero in Java) on the fifth line. Now in the next example, we will write the same program but with the Try-Catch block to handle the Arithmetic Exception we got in our last example. Example Program(With Try-Catch): public class Example{ public static void main(String args[]){ System.out.println(“Ans of 10/2 =”+(10/2)); System.out.println(“Ans of 12/3 =”+(12/3)); try{ System.out.println(“Ans of 5/0 =”+(5/0)); }catch(ArithmeticException e){ System.out.println(e.getMessage()); } System.out.println(“Ans of 24/6 =”+(24/6)); System.out.println(“Ans of 8/2 =”+(8/2)); } } Output: Ans of 10/2 =5 Ans of 12/3 =4 / by zero Ans of 24/6 =4 Ans of 8/2 =4 Here you can see how we handled ArithmeticException in our last example using try catch block. In the try block, we placed all the code which might throw an exception and we catch this exception using catch block. Instead of adding particular exception class such as ArithmeticException or ArrayIndexOutOfBoundsException you can directly add parent Exception class. Example Program: public class Example{ public static void main(String args[]){ System.out.println(“Ans of 10/2 =”+(10/2)); System.out.println(“Ans of 12/3 =”+(12/3)); try{ System.out.println(“Ans of 5/0 =”+(5/0)); }catch(Exception e){ System.out.println(e.getMessage()); } System.out.println(“Ans of 24/6 =”+(24/6)); System.out.println(“Ans of 8/2 =”+(8/2)); } } Output: Ans of 10/2 =5 Ans of 12/3 =4 / by zero Ans of 24/6 =4 Ans of 8/2 =4 Multiple catch blocks: In many situations, your code might throw multiple types of exception so to solve different kind of exception we can add multiple catch block with a try block. Check out the following example. Example Program: public class Example{ public static void main(String args[]){ try{ int num[]=new int[5]; num[4]=10/0; System.out.println(“Done”); } catch(ArithmeticException e){ System.out.println(“Can not divide by Zero”); } catch(ArrayIndexOutOfBoundsException e){ System.out.println(“Out of Array Index”); } System.out.println(“Outside try-catch block”); System.out.println(“Outside try-catch block”); } } Output: Can not divide by Zero Outside try-catch block Outside try-catch block As in the above example, you can see we have added multiple catch blocks(ArithmeticException and ArrayIndexOutOfBoundsException) and in the above example, we are got handled ArithmeticException. Here is the same example again with little change to show you the concept of multiple catch blocks. Example Program: public class Example{ public static void main(String args[]){ try{ int num[]=new int[5]; num[6]=10/2; System.out.println(“Done”); } catch(ArithmeticException e){ System.out.println(“Can not divide by Zero”); } catch(ArrayIndexOutOfBoundsException e){ System.out.println(“Out of Array Index”); } System.out.println(“Outside try-catch block”); System.out.println(“Outside try-catch block”); } } Output: Out of Array Index Outside try-catch block Outside try-catch block Please note, if you want to add multiple catch blocks with try block then always add parent Exception class in the last catch block. Example Program: public class Example{ public static void main(String args[]){ try{ int num[]; num[6]=10/2; System.out.println(“Done”); } catch(ArithmeticException e){ System.out.println(“Can not divide by Zero”); } catch(ArrayIndexOutOfBoundsException e){ System.out.println(“Out of Array Index”); } catch(Exception e){ System.out.println(“Exception in Code”); } System.out.println(“Outside try-catch block”); System.out.println(“Outside try-catch block”); } } Finally Block in Java: We can add finally block at the end of all the catch blocks. Finally block is mainly used to hold cleanup code such as you can code to close a database connection. The important thing to note about finally block is the code inside the finally both runs in both situation whether exception occur or not. Please check out the following example. public class Example{ public static void main(String args[]){ try{ int num[]=new int[5]; num[3]=10/2; System.out.println(“Done”); } catch(ArithmeticException e){ System.out.println(“Can not divide by Zero”); } catch(ArrayIndexOutOfBoundsException e){ System.out.println(“Out of Array Index”); } finally{ System.out.println(“This is finally block”); } System.out.println(“Outside try-catch block”); System.out.println(“Outside try-catch block”); } } Output: Done This is finally block Outside try-catch block Outside try-catch block   Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

Try Catch block in Java Read More »

Exception Handling in Java

In this tutorial, we will learn about an Introduction to Exception Handling in Java. According to the dictionary, the word exception means abnormal and Here Exception handling means to solve abnormal situations which occur while the execution of code. During the execution of the program due to several reasons such as wrong input, or some programming mistakes, the program stops working and throw an error on screen which is known exception. Java has a concept called Exception Handling to handle these exceptions. Example Program: public class Example{ public static void main(String args[]){ System.out.println(“Ans of 10/2 =”+(10/2)); System.out.println(“Ans of 12/3 =”+(12/3)); System.out.println(“Ans of 5/0 =”+(5/0)); System.out.println(“Ans of 24/6 =”+(24/6)); System.out.println(“Ans of 8/2 =”+(8/2)); } } Output: Ans of 10/2 =5 Ans of 10/2 =4 Exception in thread “main” java.lang.ArithmeticException: / by zero at Example.main(Example.java:5)} As in the above example, you can see our code was working perfectly till the 4th line. But when it reached to 5th line and we tried to divide 5 by 0. We got an exception(In Java / by Zero is an Exception) and our program stropped to working immediately as two can see there were two more lines(line number 6th and 7th) which were not executed because of Exception. In java, there are various inbuilt classes available in Java Standard Library which helps us to work with exception class. The parent class of all the exception class is java.lang.Exception Class Types of Exception: Java has two kinds of exception which an occur in Java programs. Types of Exception are as follow: Checked Exception Unchecked Exception Checked Exception: The checked exceptions are those exceptions which can be caught on compilation time by the compiler. These kinds of exceptions can not be ignored by the compiler. The programmer has to solve these exceptions first to run the program(without solving these checked exceptions program would not compile). List of Checked Exceptions in Java: ClassNotFoundException NoSuchFieldException NoSuchMethodException InterruptedException IOException InvalidClassException SQLException any many more… Example Program of Checked Exception in Java: import java.io.File; import java.io.FileReader; public class Example{ public static void main(String args[]) { File file = new File(“c://myfile.txt”); FileReader fileReader = new FileReader(file); } Output: Example.java:8: error: unreported exception FileNotFoundException; must be caught or declared to be thrown FileReader fileReader = new FileReader(file); Unchecked Exception: Unchecked Exceptions are those exceptions which can not be caught at the time of compilation of code. These exceptions only occur while the execution of code and stops the code from working. Example Program of Unchecked Exception in Java: public class Example { static String names[]={“ABC”,”XYZ”,”MNO”}; public static void main(String args[]) { System.out.println(names[5]); } } Output: Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 5 at Example.main(Example.java:4) List of Unhecked Exceptions in Java: ArithmeticException ArrayIndexOutOfBoundsException EnumConstantNotPresentException NegativeArraySizeException NumberFormatException NullPointerException IllegalStateException UnsupportedOperationException and many more.. Exception Class Hierarchy: The exception classes which we saw in list of checked and unchecked Exception classes are child classes of Exception class. Here is illustration to show hierarchy of all these exception classes. Please continue with next tutorial the next tutorial we will learn how to handle exception in java using try catch block. Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

Exception Handling in Java Read More »

Enum in Java

In this tutorial, we will learn about Enum in Java. In Java Enum is a kind of class and it is used to represent a group of constants. For example days of week and months of the year etc. Enum is only used in case we know all the possible values(constants) on the time of compiling code. There is enum keyword is available in Java which is used to create Enum. Furthermore, we use comma(,) operator in Enum to separate constants. Example Program: enum Days { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY; } public class ShowDays { public static void main(String[] args) { Days day = Days.SUNDAY; System.out.println(day); } } Output: SUNDAY Using switch statement with Enum in Java: enum Days { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY; } public class ShowDays { public static void main(String[] args) { Days day = Days.SUNDAY; switch(day) { case SUNDAY: System.out.println(“Finally Sunday, Enjoy your Day”); break; case MONDAY: System.out.println(“Go Back to Work”); break; case TUESDAY: System.out.println(“Again Boring working day”); break; case WEDNESDAY: System.out.println(“OMG Still Three days to Sunday”); break; case THURSDAY: System.out.println(“Thank God Haft week passed”); break; case FRIDAY: System.out.println(“Sunday is Near.”); break; case SATURDAY: System.out.println(“It’s Saturday Night”); break; } } } Output: Finally Sunday, Enjoy your Day The important thing to note about Enum: Internally Enum is represented as a class and the constants of Enum represents objects of the class. Here is an example of how the compiler will see our Days Enum which we created in the last example. class Days { public static final Days SUNDAY = new Days(); public static final Days MONDAY = new Days(); public static final Days TUESDAY = new Days(); public static final Days WEDNESDAY = new Days(); public static final Days THURSDAY = new Days(); public static final Days FRIDAY = new Days(); public static final Days SATURDAY = new Days(); } Methods in Enum: There are some methods which are present inside the java.lang.Enum class. These methods are as follow: values(): This method is used to fetch all the constants of Enum. ordinal(): This method helps us to get an index of constant. valueOf(): This method returns the enum constant of String value. Example Program: enum Days { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY; } public class ShowDays { public static void main(String[] args) { Days week[] = Days.values(); // enum with loop for (Days day : week) { System.out.println(“No. “+(day.ordinal()+1) + ” day is ” +day); } } } Output: No. 1 day is SUNDAY No. 2 day is MONDAY No. 3 day is TUESDAY No. 4 day is WEDNESDAY No. 5 day is THURSDAY No. 6 day is FRIDAY No. 7 day is SATURDAY   Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

Enum in Java Read More »

Abstract vs Interface

In the last tutorials two tutorials, we learned about abstract class and interface. In this tutorial, we will learn what is the difference between Abstract class and Interface. Abstract class Interface An abstract class can have both abstract and non-abstract methods. But an Interface can have only abstract methods. We can not perform multiple inheritances in the abstract class. But in the case of Interface we can perform multiple inheritance. An Abstract class can have both final or non-final and static or non-static variables. But Interface can has only static and final variables. An abstract class can have class members like private, protected, etc. But in case of interface all members are public by default. We can implement an interface in an abstract class. But in an Interface can’t implement an abstract class. The abstract keyword is used to declare an abstract class. The interface keyword is used to declare an interface. To inherit the abstract class in our class we use “extends” keyword. To inherit in interface in our class we use “implements” keyword. Parvesh SandilaParvesh Sandila is a passionate web and Mobile app developer from Jalandhar, Punjab, who has over six years of experience. Holding a Master’s degree in Computer Applications (2017), he has also mentored over 100 students in coding. In 2019, Parvesh founded Owlbuddy.com, a platform that provides free, high-quality programming tutorials in languages like Java, Python, Kotlin, PHP, and Android. His mission is to make tech education accessible to all aspiring developers.​ new.owlbuddy.com

Abstract vs Interface Read More »

Scroll to Top
×