Polymorphism in Java | Types of Polymorphism in Java with Examples | Method Overloading vs Overriding in Java

Polymorphism in Java

In this tutorial, we will be discussing the most important concept of Java ie., Polymorphism. Knowing each and every bit about the polymorphism in java is very crucial for beginners & experienced coders. So, check out this page without missing any of the links available below. Let’s start with understand what is java polymorphism?

Java Polymorphism

Polymorphism in Java is a concept which enables you to do a single action in various ways. It is the ability of an object or method to take many forms according to requirements. One of the most important features of object-oriented programming (OOPs) is Polymorphism. It is a combination of 2 Greek words: poly and morph. The poly word signifies many and morphs words mean forms. Therefore, when one thing has many forms it is called Java Polymorphism.

Let’s consider a scenario where Car is a class that has a method speed(). Yet, the speed of the car may change according to cars. For instance, the Maruti car has a speed of 60 Km/h, the Alto car has a speed of 70 km/h, and the Brezza car has a speed of 80 km/h. So here is a single method called speed() but their behavior is different according to cars. This is known as polymorphism in Java.

Polymorphism in Java 1

Types of Polymorphism in Java

There are two types of polymorphism in Java:

  1. Static Polymorphism.
  2. Dynamic Polymorphism.

Compile-time polymorphism is also recognized as static polymorphism. Method Overloading is a way to implement compile-time polymorphism.

Runtime Polymorphism is also called Dynamic Polymorphism. Method Overriding is a method to perform the run-time polymorphism.

Polymorphism in Java 2

Also Check:

1. Static or Compile-time Polymorphism in Java:

This compile-time type of polymorphism is also known as static polymorphism. It is achieved by function overloading or operator overloading. But, Operator Overloading is not supported by java.

Method Overloading in Java:

Methods are said to be overloaded when many methods in a class having the same name but different parameter lists. It is similar to Constructor Overloading in Java, which allows a class to have more than one constructor having the same name but having different parameter lists. It increases the readability of the program.

Suppose we have a class Addition and you want to perform the addition of the given number, but there can be any number of parameters. If you write a method such as add2(int x, int y) for two parameters, and add3(int x, int y, int z) for three parameters, then it may be difficult for you and others to understand the behavior of the methods because of its name differs.

Ways to overload a method:

There are three ways to overload a method in Java.

  1. By changing the number of parameters.
  2. By changing the data type.
  3. By changing the sequence of the data type.

Example of Method Overloading: changing the number of parameters.

In this instance, we are going to show you how we can overload a method by changing the number of parameters. In this example, we have created two methods named as add(), first, add() method performs the addition of two numbers, and the second add() method performs the addition of three numbers.

class Addition{
public int add(int x, int y){
return x+y;
}
public int add(int x, int y, int z){
return x+y+z;
}
}
class Person{
public static void main(String args[]){
Addition obj = new Addition();
System.out.println("The Addition of two numbers is : " +obj.add(10,20));
System.out.println("The Addition of three numbers is : " +obj.add(10,20,30));
}
}

Output:

Polymorphism in Java 3

Example of Method Overloading: changing the data type of a parameter.

In this example, we are going to show you how we can overload a method by changing the data type of arguments. In this example, we have created two methods named as add(), But that method differs in data type. The first method calculates the addition of two integer value and the second method calculate the addition of two double value.

class Addition{
public int add(int x, int y){
return x+y;
}
public double add(double x, double y, double z){
return x+y+z;
}
}
class Person{
public static void main(String args[]){
Addition obj = new Addition();
System.out.println("The Addition of two numbers is : " +obj.add(10,20));
System.out.println("The Addition of three numbers is : " +obj.add(10.01, 20.02, 30.04));
}
}

Output:

Polymorphism in Java 4

Example of Method Overloading: changing the sequence data type.

In this example, we are going to show you how we can overload a method by changing the sequence of a data type. In this example, we have created two methods named as a display() with a different sequence of the data type of arguments list. The first method having the arguments (int, double), and the second method having the arguments (double, int).

class Addition{
public void display(int x, double y){
System.out.println("Defination of first method");
}
public void display(double x, int y){
System.out.println("Defination of second method");
}
}
class Person{
public static void main(String args[]){
Addition obj = new Addition();
obj.display(5, 4.5);
obj.display(2.5, 5);
}
}

Output:

Polymorphism in Java 5

Note: Method Overloading in Java is not possible by changing the return type of the method only because of the ambiguity problem. Let’s see how ambiguity may occur.

class Addition{
public int add(int x, int y){
return x+y;
}
public double add(int x, int y){
return x+y;
}
}
class Person{
public static void main(String args[]){
Addition obj = new Addition();
System.out.println(obj.add(4,5)); //Ambiguity may occur
}
}

In this example, we have created two methods named add(), But having a different return type. When we call this method Java compiler show compile-time error, because how can the Java compiler determine which add() method should be called?

2. Dynamic or Runtime Polymorphism in Java

Dynamic polymorphism is also known as runtime polymorphism. Method Overriding is a way to implement runtime polymorphism in Java.

Method Overriding in Java:

Method Overriding is a feature that allows you to redefine the parent class method in the child class based on its requirement.

In other words, whatever methods parent has by default available to the child through inheritance. Sometimes a child may not satisfy with parent methods implementation. Then the child is allowed to redefine that method based on its requirements, this process is called method overriding.

  • The parent class method which is overridden is known as an overridden method.
  • The child class method which is overriding is known as an overriding method.

The main purpose of method overriding is that the class gives its own implementation to an inherited method without even modifying the parent class code.

Rules for Method Overriding in Java:

  • The method of the parent class and the method of child class must have the same name.
  • The method of the parent class and the method of child class must have the same parameter.
  • Method Overriding in Java is possible through inheritance only.

Therefore to understand the concept of method overriding you should have the basic knowledge of Inheritance in Java

Example of Java Method Overriding:

Let’s take a simple example to understand the concept of method overriding.
We have two classes: A parent class Animal and a child class Dog. The Dog class extends the Animal class. Both the class have a common method eat(). The Dog class is giving its own implementation to the eat() method. It is an overriding eat() method.

The child class gives its own implementation so that when it calls this method, it prints Dog is eating instead of Animal is eating.

class Animal{
public void eat(){
System.out.println("Animal is eating");
}
}
class Dog extends Animal{
public void eat(){
System.out.println("Dog is eating");
}
}
class Person{
public static void main(String args []){
Dog obj = new Dog();
obj.eat();
}
}

Output:

Dog is eating

Overloading vs Overriding in Java:

  1. Overloading is also known as compile-time polymorphism or static polymorphism or early binding while overriding is also called runtime polymorphism or dynamic polymorphism or late binding.
  2. The main purpose of overloading is to enhance the readability of the program while overriding the class gives its own implementation to an inherited method without even modifying the parent class code.
  3. Overloading occurs at compile-time whereas Overriding occurs at runtime.
  4. Overloading is made in the same class whereas Overriding inheritance is required.
  5. In overloading, the parameter needs to be different while in overriding the parameter must be the same.
  6. Private, static, and final methods can be overloaded but cannot be overridden.
  7. The return type can be the same or different in overloading while the return type must be the same or covariant return type in the overriding.

Statement Interface in Java – JDBC | Definition, Syntax, and Methods of Statement Interface with Example

Statement Interface in Java

In this tutorial, you will learn Statement Interface in Java-JDBC. With the help of the Statement object, we can send our SQL Query to Database. Furthermore, you will also read Statement interface methods with an example.

What is Statement Interface in JDBC?

In JDBC Statement is an Interface. By using the Statement object, we can send our SQL Query to Database. At the time of creating a Statement object, we don’t need to provide any Query. Statement object can work only for the static query.

Whenever we are applying an execute() method, every time Query will be compiled and executed. As Query will be compiled every time, its performance is low. Best choice for Statement object, if you want to work with multiple queries.

Syntax:

Statement stmt=conn.createStatement();

Commonly used Methods of Statement Interface

The important methods of Statement Interface are given below:

1. public boolean execute(String url): This method is used for all types of SQL statements (eg. Select, Insert, Update, etc.). This method returns a boolean value. If you don’t know which method is used (executeQuery() or executeUpdate()) then you should go for execute() method.

2. public ResultSet executeQuery(String url): This method is used for the Select a statement which retrieves some data from the database. This method returns a ResultSet object.

3. public int executeUpdate(String url): If you want to modify in your database, then you should go for the executeUpdate() method. This method returns an int value which indicates the number of rows affected.

4. public int[] executeBatch(): This method is used the execute the batch of commands. This method returns an integer array.

Also Refer:

Here is my empty database:

Statement Interface in Java 1

JDBC Statement Interface Example:

import java.sql.*;
import java.util.*;
class InsertMultipleRows{
public static void main(String args[])throws Exception{
class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/emp_record","root"," ");
Statement st = con.createStatement();
Scanner sc = new Scanner(System.in);

while(true){
System.out.println("Enter employee number: ")
int eno = sc.nextInt();
System.out.println("Enter employee name: ")
String ename = sc.next();
System.out.println("Enter employee salary: ")
double esal = sc.nextDouble();
System.out.println("Enter employee address: ")
String eaadr = sc.next();

String sqlquery = String.format("insert into insert_rows values(%d,%s,%f.%s)", eno,ename,esal,eaddr);
st.excecuteUpdate(sqlquery);
System.out.println("Record inserted succesfully ");
System.out.println("Do you want to insert more records[yes/no]");
String option = sc.next();
if(option.equalsIgnoreCase("no")){
break;
}
}
}
}

Output:

Statement Interface in Java 2

Statement Interface in Java 3

Servlet Interface and its Methods Explained with Example | Methods of Servlet Interface

Servlet Interface and its Methods Explained with Example

Learn about Servlet Interface and its methods in detail by going through this tutorial. We will explain the purpose of all the methods with an example. Servlet Interface has five methods and is described below. Let us learn what is a Servlet Interface and the Methods supported by it.

What is the Servlet Interface?

All the servlets must implement the servlet interface. It defines the init(), service(), and destroy() methods that call by the server during the life cycle of a servlet. It also has a method that allows a servlet to obtain any initialization parameters.

Servlet Interface and its Methods

The methods define by servlet are given below:

1. public void init(ServletConfig sc) throws ServletException: It is called when the servlet initialized. The initialization parameter for the servlet can be obtained from sc. If you can’t initialize the servlet then you will get an Unavailable Exception.

2. public void service(ServletRequest req,ServletResponse res): It throws both ServletException, IOException
The Service() method is called to process a request from a client. You can read the request from a client from req. The response to the client can be written to res. You will get an Exception if IO and Servlet Problem Occurs.

3. public void destroy(): On completion of all pending requests or time out to the servlet, the server calls the destroy() method.

4. public String getServletInfo(): This method returns a string describing the servlet.

5. public ServletConfig getServletConfig(): This method returns a ServletConfig object that contains any initialization parameters.

Do Refer Similar Articles:

Java Servlet Interfaces with Examples

In this example, we have created a servlet by extending the Servlet Interface.

ServletInterfaceDemo.java file

Servlet interface and its methods explained with example 1

Web.xml file:

Servlet interface and its methods explained with example 2

Output:

Servlet interface and its methods explained with example 3

What is Enterprise JavaBeans (EJB)? – Architecture, Types, Advantages, Disadvantages

What is Enterprise JavaBeans (EJB)

EJB stands for Enterprise JavaBeans. EJB is a server-side component written in the Java programming language. Enterprise JavaBeans encapsulates the business logic of applications. Enterprise JavaBeans are typically deployed in EJB containers and run on the EJB servers.

EJB Architecture and its Components

EJB Architecture has three main components. They are

  • Enterprise Beans
  • EJB Container
  • Java Application Server

In general, Enterprise Beans run inside an EJB Container whereas EJB Container runs in a Java Application Server. This is how EJB Architecture works.

EJB container has the environment in which one or more Enterprise JavaBeans run. It provides the following control and management services.

  • Life Cycle Management.
  • Naming services.
  • Security checks.
  • Resource pooling.
  • persistence management.
  • Transactions coordinations.
  • Bean runtime context information(meta data).

Types of Enterprise JavaBeans

There are three types of Enterprise JavaBeans – Session beans, Entity beans, and Message-driven beans.

1. Session Bean: It stores the information of a particular client for a single session. Ecan Session bean is associated with one EJB client. It is created and destroyed by the particular client that is associated with it. It either can have stateless or stateful. A session bean can be destroyed if at all the EJB server crashes. Session bean does not represent data that must be stored in a database.

2. Entity Bean: It represents persistent data storage. In a persistent storage mechanism, an Entity bean denotes the business object. The Application Server has a relational database which is the persistent storage mechanism. An entity bean can be shared by multiple EJB clients. An entity bean can share access from many users. These are persistent and can survive when the EJB server crashes.

3. Message-Driven Bean: It is the third form of EJB, which you can initiate by sending a request from Java Message Service (JMS). Message-Driven bean includes the business logic same as in the session bean but it is invoked by passing the message. It can consume JMS messages from external entities.

When to Use Enterprise JavaBeans?

  • If the Application needs remote access i.e. if it is distributed.
  • If you need the Application to be Scalable you can go with Enterprise JavaBeans as it supports load balancing, clustering, and failover.
  • If the Application needs encapsulated business logic you can go with Enterprise JavaBeans. The application can be differentiated from the persistent and demonstration layer.

Advantages of Enterprise JavaBeans (EJB)

  • Enterprise JavaBeans can simplify the development of large, and distributed applications.
  • The EJB container – and not the Bean Developer – provides system-level services, such as transaction management and security authorization. So the developer has to focus only on the business logic of the applications.
  • EJB is of portable components, so the developer can build new applications by using the existing beans.

Disadvantages of Enterprise JavaBeans (EJB)

  • To run the EJB Applications they need an application server.
  • Developing the EJB applications requires only Java Developer.
  • Complex to develop EJB applications.

How to find String length in Java using length method? | Java String length() with Example | length vs length()

How to find String length in Java using length method

In this tutorial, we will discuss how to find the string length in java. We can find string length in java using the length() method of the String class.

Java String length()

This method returns the length of the string. Remember that the length variable is used in the array whereas the length() method is used in the string. If you try to use the length variable to find the string length then the complier will get a compile-time error. The signature of java string length() is written as shown below.

Syntax:

The syntax of the string class length() method is given below:

public int length()

Return Value

This method returns the length of a string in Java.

Internal Implementation

public int length() { 
return value.length; 
}

length vs length()

length  length() Function
The length variable in an array returns the length of an array i.e. a number of elements stored in an array. The length() returns the length of a string object i.e. the number of characters stored in an object.
Once arrays are initialized, their length cannot be changed, so the length variable can directly be used to get the length of an array. String class uses this method because the length of a string can be modified using the various operations on an object.
Examples: length can be used for int[], double[] to know the length of the arrays. Examples: length() can be used for String, StringBuilder, etc. Basically, it is utilized for String class-related Objects to know the length of the String
The length variable is used only for an array. The String class internally uses a char[] array that it does not expose to the outside world.

Also Read:

Example of Java String length() Method

class StringLength{
public static void main(String args[]){
String str1 = "Javastudypoint";
String str2 = "Prashant";
//14 is the length of the str1.
System.out.println("The length of the str1 is: "+str1.length());
//8 is the length of the str2.
System.out.println("The length of the str2 is: "+str2.length());
}
}

Output:

The length of the str1 is: 14
The length of the str2 is: 8

Let’s see an example of what happened if we are using the length variable instead of the length() method in the case of a string. If you do so, then the compiler will get a compile-time error saying cannot find the symbol. Let’s see the sample code on it.

class StringLength{
public static void main(String args[]){
String str1 = "Javastudypoint";
String str2 = "Prashant";
//using length variable instead of length().
System.out.println("The length of the str1 is: "+str1.length);
//using length variable instead of length().
System.out.println("The length of the str2 is: "+str2.length);
}
}

Output:

How to find String length in Java using length method

Session Tracking in Servlet and its Techniques | Session Tracking Methods

Session Tracking in Servlet and its Techniques

In this tutorial, we will learn What is Session, Session tracking in the servlet, why do we use sessions, and various techniques for Sessions. Usually, there are 4 different techniques to manage the session. Before discussing its techniques in detail let’s first understand the basics of the session.

What is a Session?

The session means a particular interval of time. The data of the session are stored on a server. Usually, Session is a conversation between the client browser and a server.

What is Session Tracking in Servlet?

Session tracking means keeping needful information about the user and his action for a series of conversions. Session tracking is also known as Session Management.

Also, Check:

Why do we use Session?

HTTP is a stateless protocol that means each time a user requests to the server, it treats a new request as shown in the figure given below. It provides no built-in-way for a server to recognize that a sequence of requests all originated for the same user. To maintain the state of a user to recognize particular user session tracking will use. To understand this see the image given below:

Session Tracking in Servlet and its Techniques

Session Tracking Techniques

There are 4 ways to manage the session. We have outlined in detail all 4 session tracking methods for your convenience. They are as such

  1. Cookies
  2. Hidden Form Field
  3. URL Rewriting
  4. HttpSession

Cookies

Webserver assigns a unique session ID as a cookie to each web client and on client subsequent requests we can identify them as received cookie. This is not that effective as the browser will not always support a cookie and it is better to use this procedure in order to maintain sessions.

Hidden Form Fields

A Webserver can send hidden HTML Format along with unique session ID as such

<input type = "hidden" name = "sessionid" value = "12345">

This entry means after submitting the form, a specified name and value will be automatically included in the GET or POST-Data. You can keep the track of different web browsers using the sesson_id value whenever the web browser sends a request back.

This can be an effective technique to keep track of the session. However, clicking on a regular hypertext link will not result in form submission. Thus, Hidden Form Fields will not even support general session tracking.

URL Rewriting

You can append extra data at the end of each URL which identifies the session that the server can associate with the session identifier with data, it stored regarding the session.

For example, with http://btechgeeks.com/file.htm;sessionid = 12345, the session identifier is attached as session-id = 12345 with which it can be accessed at the webserver for client identification.

URL Rewriting is a better technique to maintain sessions. This works even if the web browser doesn’t support cookies. The only drawback with this method is you need to generate each URL Dynamically to allot a session ID even if you need a simple static HTML Page.

HttpSession Object

Along with the above listed three ways servlet provides HttpSession Interface provides a way to identify a user across more than one page request or visit to a website and stores info regarding the user.

Servlet Container uses this interface to create a session between HTTp Client and HTTP Server. The session exists for a specific time duration over more than one connection or page request from a user.

You can obtain the HttpSession object by calling the public method getSession() of HttpServletRequest, as such

HttpSession session = request.getSession();

Exception Handling in JSP | What is Exception & Error? | Methods of Handling Exceptions in JSP with Examples

Exception Handling in JSP

In the previous tutorial, we have discussed JSP Directives. Now, we have come with the new JSP Topic ie., Exception Handling in JSP. So, in this tutorial, we will learn JSP Exception Handling with Examples. Before understanding JSP Exception Handling, let’s start learning what is Exception and how it is different from errors. Just use the direct links for quick reference about the JSP Exception Types, Methods, etc.

What is an Exception?

An exception is an event, that occurs during the execution of a program, that disrupts the normal flow of program instructions. when an error occurs within a method, the methods create objects and hands it off to the runtime system.

The object called an exception object. It contains the information about the error, including its type and state of the program when the error occurred. Exception Handling is the process of handle the errors that may occur during runtime.

Types of Exceptions in JSP

There are three types of JSP Exceptions. They are as follows:

Checked Exceptions

It is usually a user error or problems which are not recognized by the developer are named as checked exceptions.

Runtime Exceptions

Runtime exceptions are the one which could have evaded by the programmer. They are overlooked at the time of compilation.

Error Exception

It is an example of the throwable class, and it is used in error pages.

A few of the throwable class methods are:

  • Public String getMessage() – returns the message of the exception.
  • Public printStackTrace()- returns the stacktrace of the exception.
  • Public throwablegetCause() – returns cause of the exception.

What is Error?

Most of the time errors are not caused by our program these are caused by system resources. We cannot handle the errors.

For instance: if OutOfMemory occurs being a programmer we can’t do anything and the program will be terminated automatically.

Also Read:

Methods of Handling Exception in JSP

In JSP, We can handle the exceptions in two ways. They are as such:

  • By errorPage and isErrorPage attributes of page directive
  • By <error-page> element in web.xml file

Handling Exception using page directive attributes

In JSP Page Directive, there are two attributes that help in handling exceptions in JSP. They are:

1. errorPage:

This attribute is utilized to notify the container to jump the control to another JSP page if an exception occurs in the current JSP page. Extra JSP page is used to handle the exception that is happened in the current JSP page.

Syntax: <%@ errorPage = “error.jsp” %>

2. isErrorPage:

This attribute is utilized to notify the container that makes a JSP an error page or not. The default value of this attribute is false. It means a JSP page is not acting as an error page by default. To make a JSP page as an error page than we should write isErrorPage = “true”. If isErrorPage = “true” then only execution objects is passed into a JSP page.

Syntax: <%@ isErrorPage=”true” %>

Example of exception handling in JSP by the elements of page directive:

In this example, we are creating the 3 files.

  1. index.jsp: for input values.
  2. calculation.jsp for dividing the two numbers and display the result.
  3. error.jsp for handle the jsp exception.

index.jsp

Exception Handling in JSP 1

calculation.jsp

Exception Handling in JSP 2

error.jsp

Exception Handling in JSP 3

Output:

Exception Handling in JSP 4

Exception Handling in JSP 5

Handling Exceptions Using error-page Element in web.xml File

The other way of defining the error page for each element, but in place of using the errorPage directive, the error page for each page can be specified in the web.xml file, with the help of the <error-page> element.

The syntax for <error-page> is as follows:

<web-app> 

<error-page> 
<exception-type>Type of Exception</exception-type> 
<location>Error page url</location> 
</error-page> 

</web-app>

Example of JSP exception handling by the error-page element in web.xml file:

The below example shows the usage of this technique to handle exceptions:

index.html

<html>
<head>
<body>
<form action="a.jsp"> 
Number1:<input type="text" name="first" >
Number2:<input type="text" name="second" > 
<input type="submit" value="divide"> 
</form> 
</body>
</html>

a.jsp

// JSP code to divide two numbers
< %

String num1
= request.getParameter("first");
String num2 = request.getParameter("second");
// extracting the numbers
int x = Integer.parseInt(num1);
int y = Integer.parseInt(num2);
int z = x / y; // dividing
out.print("division of numbers is: " + z); // result

% >

error.jsp

// JSP code for error page, which displays the exception
<%@ page isErrorPage="true" %> 

<h1>Exception caught</h1> 

// displaying the exception
The exception is: <%= exception %>

web.xml

<web-app> 

<error-page> 
<exception-type>java.lang.Exception</exception-type> 
<location>/error.jsp</location> 
</error-page> 

</web-app>

Output:

In this case, the output is as same as the previous one.

Java String lastIndexOf() Method with Example | Definition, Syntax, Usage & Types of Java.lang.String.lastIndexOf() Method

Java String lastIndexOf() Method with Example

In the last tutorial, we have learned all about Java String indexOf() method. We discussed all the four variants of the indexOf() method. In this tutorial, we will learn about the Java String lastIndexOf() method. There are four variants of the lastIndexOf() method. Here, we will discuss all the four variants of the Java String lastIndexOf() method. Let’s discuss these four variants one by one.

Java.lang.String.lastIndexOf() Method

The java string lastIndexOf() method returns the last index of the furnished character value or substring. If it is not detected, it returns -1. The index counter starts from zero.

Internal Implementation

public int lastIndexOf(int ch) {  
       return lastIndexOf(ch, value.length - 1);  
   }

Parameters Values

  • ch: char value i.e. a single character e.g. ‘a’
  • fromIndex: index position from where the index of the char value or substring is returned
  • substring: substring to be explored in this string

Return Value

This method returns the last index of the string.

Read More: 

Java String lastIndexOf() Example

public class JavaExample {  
   public static void main(String[] args) {  
    String str = "BtechGeeks is for beginners";
    char ch = 'b';
    char ch2 = 's';
    String subStr = "beginners";
    int posOfB = str.lastIndexOf(ch);
    int posOfS = str.lastIndexOf(ch2);
    int posOfSubstr = str.lastIndexOf(subStr);
    System.out.println(posOfB);
    System.out.println(posOfS);
    System.out.println(posOfSubstr);
   }  
}

Java String lastIndexOf() Signature

You can observe 4 types of the lastIndexOf method in java. The signature of lastIndexOf methods are tabulated below:

No. Method Description
1 int lastIndexOf(int ch) returns last index position for the given char value
2 int lastIndexOf(int ch, int fromIndex) returns last index position for the given char value and from an index
3 int lastIndexOf(String substring) returns last index position for the given substring
4 int lastIndexOf(String substring, int fromIndex) returns last index position for the given substring and from the index

Java String lastIndexOf() Method with Example

1. lastIndexOf(int ch)

This is the first variant of the Java String lastIndexOf() method. This method returns the index of the last occurrence of the specified character. If the specified character is not present there, then it will return -1.

Syntax:

The syntax of the first variant of Java String lastIndexOf() method is given below:

public String lastIndexOf(int ch)

Here, ch is a character whose index we want to return.

Java String lastIndexOf(int ch) Method Example

class lastIndexOf{
public static void main(String args[]){
String str = "String tutorial by Btechgeeks";
//returns the last index
//of specified character.
System.out.println(str.lastIndexOf('i')); //12
}
}

Output:

12

2. lastIndexOf(int ch, int fromIndex)

This is the second variant of the Java String lastIndexOf() method. This method returns the index of the first occurrence of the specified character, starting the search from the backward specified index. This method returns -1 if the specified character is not present there.

Syntax:

The syntax of the second variant of Java String lastIndexOf() method is given below:

public String lastIndexOf(int ch, int fromIndex)

Here, ch is a character and fromIndex is the index position at which point the search begins.

Java String lastIndexOf(int ch, int fromIndex) Method Example

class lastIndexOf{
public static void main(String args[]){
String str = "String tutorial by btechgeeks";
//returns the last index
//of 'i' before 15th index.
System.out.println(str.lastIndexOf('i', 15)); //12
}
}

Output:

12

3. lastIndexOf(String str)

This is the third variant of the Java String lastIndexOf() method. This method returns the index of the last occurrence of the specified substring. If the specified substring is not present there, it will return -1.

Syntax:

The syntax of the third variant of Java String lastIndexOf() method is given below:

public String lastIndexOf(String str)

Here, str is a substring whose index we want to return

Java String lastIndexOf(String str) Method Example

class lastIndexOf{
public static void main(String args[]){
String str = "String tutorial in java by btechgeeks";
//returns the last index of
//initial character of substring.
System.out.println(str.lastIndexOf("java")); //20
}
}

Output:

20

4. lastIndexOf(String str, int fromIndex)

This is the fourth variant of the Java String lastIndexOf() method. This method returns the index of the first occurrence of the specified substring, starting the search from the backward specified index. This method returns -1 if the specified substring is not present there.

Syntax:

The syntax of the fourth variant of Java String lastIndexOf() method is given below:

public String lastIndexOf(String str, int fromIndex)

Here, str is a substring and fromIndex is the index position at which point the search begins.

Java String lastIndexOf(String str, int fromIndex) Method Example

class lastIndexOf{
public static void main(String args[]){
String str = "String tutorial in java by btechgeeks";
//returns the last index of
//initial character of substring
//before index 30.
System.out.println(str.lastIndexOf("java", 30)); //20
}
}

Output:

20

Use of Abstract Class in Java | How to Create Abstract Class in Java? | Difference Between Interface and Abstract Class in Java

Abstract Class in Java

Data abstraction is defined as the process of hiding the internal details from the user and showing only functionality. Consider a real-world example of a man driving a car. When a man driving a car he pressing the accelerators to increase the car speed and applying the brake to stop the car but he doesn’t know how pressing the accelerators will increase the car speed and applying the brake will stop the car. The man doesn’t know the inner mechanism of a car. This is called abstraction. Data abstraction can be achieved through Abstract Class.

Before discussing Abstract Class in Java. We can recall you in C++ if a class has at least one pure virtual function then the class becomes an abstract class. We can make an abstract class in C++ with the help of the virtual keyword. But in java, there is no virtual Keyword.

How to Create Abstract Class in Java?

In Java, we can create an abstract class with the help of the abstract keyword. Like C++, in Java, an abstract class cannot be instantiated (instance cannot be created). But we can create a reference variable of an abstract class.

Syntax:

abstract class class_name { }

Important Points about Java Abstract class

  • We can create an abstract class with the help of the abstract keyword.
  • We cannot instantiate an abstract class. But we can create a reference for an abstract class.
  • Abstract class contains abstract and non-abstract methods.
  • If a class has an abstract method then it must be declared that class as abstract.
  • An abstract class contains a constructor.
  • An abstract class also has final methods. (methods can’t be overridden).
  • An abstract class is a way to achieve abstraction (not 100 percent).
  • Abstraction is an OOPs concept that is used to hide the implementation details from the user.

Do Read:

Rules to Declare Abstract Class in Java

There are certain pointers to be kept in mind while dealing with Abstract Class in Java and they are as mentioned below.

Abstract Class in Java Rules

Features of Abstract Class in Java

There are few characteristics of a Java Abstract Class and they are mentioned in detail below.

Template: Abstract Class in Java provides the best way to execute the data abstraction process and gives developers an option to hide the code implementation. In addition, it provides the end-user a template and explains the methods included.

Loose Coupling: Data Abstraction in Java enables loose coupling and reduces dependencies at an exponential level.

Code Reusability: Utilizing Abstract Class in the Code can save a lot of time as we can call the abstract method as and when the method is needed. It avoids the process of writing the same code again and again.

Abstraction: Java Data Abstraction helps the developers to hide the code complications from the end-users and reduces the project’s complete characteristics to necessary components.

Dynamic Resolution: Taking help from the dynamic method resolution developers can solve various complexities using one abstract method.

Abstract Class in Java Features

How to Achieve Abstraction in Java?

You can achieve abstraction in Java using two different methods one is through Abstract Class and the other is through Interface.

How to Achieve Abstraction in Java

Interface: Interface in Java is defined as a boundary between the method and the class implementing it. Interface in Java holds a method signature in it but not the implementation of the method. We use Interface to Achieve Abstraction in Java.

//Syntax:

interface <Class_Name>{

//Method_Signatures;

}

Difference between Interface and Abstract Class in Java

Although Interface and Abstract Class in Java Perform Similar Operations there are certain minute differences between the two and they are outlined as follows

Interface Abstract Class
Keyword used is interface Keyword used is abstract
Multiple interfaces can be implemented One abstract class can be extended
It Supports Multiple Inheritance It Cannot support Multiple Inheritance
Subclasses can implement an interface Subclasses need to extend abstract class

Now, that we are familiar with the basic differences between Interface and Abstract Class in Java let’s dive into the further sections and learn some of the advantages and disadvantages of Java Abstract Class.

Advantages of Abstract Class in Java

Go through the below-provided advantages of Java Abstract Class and they are as under

  • Abstract Class is necessary for writing shorter codes.
  • It helps you to avoid duplicate codes.
  • Abstract Classes enables code reusability.
  • You can make changes to Internal Code Implementation without affecting the Classes.

In addition to the numerous advantages that come with Java Abstract Class, there are quite a few disadvantages too that you need to pay attention to. Let’s get into them and learn the cons too.

Disadvantages of Abstract Class in Java

  • Abstraction in Java is Expensive as you need to handle cases and situations that aren’t always needed.
  • Object-relational impedance Mismatch in case of RDBMS.
  • In the case of frameworks like hibernate you will get Object Relational Mapping.

Abstract Method and Class in Java

  • An abstract class can include methods that contain no implementations (methods without body) is known as abstract
  • methods in java.
  • Like an abstract class, abstract methods must be declared with abstract keywords.
  • The abstract methods declaration must end with a semicolon rather than a block.
  • Abstract methods must be created and declared in an abstract class.
  • Abstract methods don’t have method implementation (method body) it has only method signature.
Example of abstract method: abstract void showMsg(); // Nobody

Why we Use Abstract Class in Java?

Let’s say we have a class Bank that has a method getRateOfInterest() and subclasses of it like OBC, SBI, and PNB. Since the Bank interest different from one bank to another bank, there is no point to implement this method in the Parent class (Bank class). This is because every child class ( like OBC class, SBI class, etc.) must override this method to give its own implementation details, like SBI class will say “SBI has 7 percent interest” and OBC class will say “OBC has 8 percent interest”.

So when we know that all the Bank child classes (SBI, OBC, and PNB, etc.) will and should override this method, then there is no point to implement this method in the parent class (Bank class). Thus, making this method abstract would be a good practice.

Now each Bank must have a rate of interest, by making this method abstract we made it compulsory to the child class (SBI, OBC, etc.) to give implementation details to this method. That’s why we use the Abstract Class.
Let’s understand this by a real-world scenario Bank Example:

Abstract Class in Java Example

abstract class Bank{
abstract int getRateOfInterest();
}
class OBC extends Bank{
int getRateOfInterest(){
return 7;
}
}
class PNB extends Bank{
int getRateOfInterest(){
return 8;
}
}
class SBI extends Bank{
int getRateOfInterest(){
return 9;
}
}
class Example{
public static void main(String args[]){
Bank obj;
obj = new OBC();
System.out.println("OBC Rate of interest is: " +obj.getRateOfInterest()+ "%");
obj = new PNB();
System.out.println("PNB Rate of interest is: " +obj.getRateOfInterest()+ "%");
obj = new SBI();
System.out.println("SBI Rate of interest is: " +obj.getRateOfInterest()+ "%");
}
}

Output:

Abstract Class in Java 1

Abstract Class with Constructor Example Program

Like any other class, an abstract class has a constructor, data members, and methods.

abstract class Car{
Car(){
System.out.println("Car is created");
}
abstract void running();
void changeColour(){
System.out.println("Car colour is changed");
}
}
class Maruti extends Car{
void running(){
System.out.println("Car is running safely");
}
}
class Practical{
public static void main(String args []){
Maruti obj = new Maruti();
obj.running();
obj.changeColour();
}
}

Output:

Abstract Class in Java 2

Abstract Class without Abstract Method Example

Abstract class contains a non-abstract method (normal method) with method definition.

abstract class Car{
public void running(){
System.out.println("Car is running");
}
}
class Practical extends Car{
public void marutiRunning(){
System.out.println("Maruti car is running");
}
public static void main(String args[]){
Practical obj = new Practical();
obj.running();
obj.marutiRunning();
}
}

Output:

Abstract Class in Java 3

Exception Handling in Java | Types of Exceptions in Java With Example Programs

Exception Handling in Java

Exception Handling in Java is one of the most powerful features that allow us to handle the runtime error so that the normal flow of the program can be maintained. In this tutorial, we will learn What is an exception, Types of exception, exception classes, how to handle the exception in Java, and the difference between error and exception. Before discussing exception handling in java in detail let’s first understand What is an exception.

This Java Exception Handling tutorial contains the following

What is Exception in Java?

Exceptions in Java are any abnormal, unwanted events, or extraordinary conditions that may occur at runtime. It interrupts the normal flow of the program. Exception terminated the program execution. When an exception occurs we get a system-generated error message. The good news is that exceptions can be handled in Java. Therefore we can provide a meaningful message to the user rather than the system generated an error message, which not understandable to a user.

Why an exception occurs?

Exceptions in Java can occur due to the following reasons:

  • Wrong data entered by the user.
  • Network Connection problem.
  • Hardware problem.
  • Opening a file which is not existing in your program.
  • Server down problem.

What is Exception Handling?

Exception Handling in Java is a powerful mechanism that is used to handle runtime errors, compile-time errors are not handled by exception handling in Java. If an exception occurs in your code (suppose in line 6), then the rest of the code is not executed. Therefore Java compiler creates an exception object and this exception object directly jumps to the default catch mechanism. Where there is a default message which is print on the screen and our program gets terminated.

Also See:

Advantages of Exception Handling in Java

It maintains the normal flow of the program. Suppose in your program there are many statements and an exception occurs midway then the statements after the exception will not execute and the program will terminate and we get system generated error message. Which are not understandable to a user.

By exception handling mechanism all the statements in your program will execute and do not break the normal flow of the program and it generated a user-friendly message rather than the system generated an error message.

Difference between Exception and Errors

Errors: Most of the time errors are not caused by our programs these are due to a lack of system resources. Errors are not recoverable (not handle).

For example, if an OutOfMemory error occurs during the execution of a program we can’t do anything and the program will be terminated abnormally.

Exceptions: Exceptions in Java are any abnormal, unwanted events, or extraordinary conditions that may occur at runtime. Exceptions are caused by our program and exceptions are recoverable.

Few instances of exceptions: ArithmaticException, NullPointerException, ClassNotFoundException, IOException, etc.

Hierarchy of Java Exception Classes

  • Throwable is the parent class of all exception classes in java.
  • Throwable has two child classes: Error and Exception.
  • The Exception class represents the exception that can be handled by our program using try and catch block.
  • RuntimeException is a child class of exception class. These types of exceptions may occur at runtime. ArithmeticException, NullPointerException, etc. are the example of runtime exception.

Exception Handling in Java - Types of Exceptions in Java

Java Exception Keywords

There are 5 keywords that are used for exception handling in Java:

1. try: In the java, try block we can write the code that might throw an exception. A try block in Java must be followed by either at least one catch block or one finally block.

2. catch: catch block in Java is used to handle the exception that may occur in our program. It must be used after try block only. We can use more than one catch block with a single try block.

3. finally: finally block in Java can be used to clean up code or release some resources that are utilized in the program. finally block is always run whether the exception handled or not.

4. throw: throw keyword in java can be used to throw an exception. It can throw exceptions explicitly. We can throw either checked or unchecked exceptions using the throw keyword.

Syntax:

throw an exception;

5. throws: throws keyword in java is used for declaring an exception. We can declare only checked exceptions using the throws keyword. So it’s the programmer’s responsibility to provide the exception handling code so that the normal flow of the program can be maintained.

Syntax:

return_type method_name() throws exception_class_name.

Exceptions Methods

From the below table, you will see the list of important methods obtained in the Throwable class:

Method Description
public String getMessage() Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor.
public Throwable getCause() Returns the cause of the exception as represented by a Throwable object.
public String toString() Returns the name of the class concatenated with the result of getMessage().
public void printStackTrace() Prints the result of toString() along with the stack trace to System.err, the error output stream.
public StackTraceElement [] getStackTrace() Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack.
public Throwable fillInStackTrace() Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace.

Java Exception Handling Example

Let’s take a look at the sample program on Java Exception Handling by using a try-catch statement to handle the exception:

public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}

Output:

Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...

Types of Exceptions in Java

There are two types of Exception in Java:

  1. Checked Exception
  2. Unchecked Exception

1. Checked Exceptions

All the classes which inherit the throwable class except RuntimeException and Error are known as Checked Exception. The checked exceptions are checked by the compiler at compile-time. In case of checked exceptions if programmers will not handle the exception then we will get a compile-time error. We will handle the checked exception by using a try-catch block or and declare using the throws keyword. For example, FileNotFoundException, ClassNotFoundException, IOException, SQLException etc.

Checked Exception Example:

In this example, we are reading the file abc.txt and displaying its content on the screen. Here we are using FileInputStream for reading the data from a file, it throws FileNotFoundException. The read() method which is used for reading the data from the input stream and the close() method which is used for closes the file input stream throws an IOException.

import java.io.*;
class ExceptionExample{
public static void main(String args[]){

FileInputStream fis = null;

//FileInputStream throws
//FileNotFoundException which is
// a checked exception.
fis = new FileInputStream("D:/abc.txt");
int i;

//read() method of FileInputStream
//class also throws an IOException.
while(( i = fis.read() ) != -1 ){
System.out.println((char)i);
}

//close() method used for
//close the file input stream
//it throws an IOException.
fis.close();
}
}

Output:

error: unreported exception FileNotFoundException
fis = new FileInputStream("D:/abc.txt");
error: unreported exception IOException
while(( i = fis.read() ) != -1 ){
error: unreported exception IOException
fis.close();

There are two ways to handle this error:

  1. Using try-catch.
  2. Using throws keyword.

Java try…catch block

The try-catch block is used to handle exceptions in Java. Below, we have given the syntax of try…catch block:

try {
// code
}
catch(Exception e) {
// code
}

In the above syntax, we have placed the code that might generate an exception inside the try block. Every try block is followed by a catch block.

Handle Checked Exception using a try-catch block

It is a good practice to handle the exception using a try-catch block Because you should give a meaningful message for each exception type so that it would be easy for someone to understand the error.

import java.io.*;
class ExceptionExample{
public static void main(String args[]){
FileInputStream fis = null;
try{
fis = new FileInputStream("D:/abc.txt");
}
catch(FileNotFoundException fn){
System.out.println("The file is not present at given path");
}
int i;
try{
while(( i = fis.read() ) != -1 ){
System.out.println((char) i);
}
fis.close();
}
catch(IOException ie){
System.out.println("IOException occured: " +ie);
}
}
}

Java throw and throws keyword

The throw keyword in java is utilized to explicitly throw a single exception.

Exception handling using Java throw

class Main {
public static void divideByZero() {

// throw an exception
throw new ArithmeticException("Trying to divide by 0");
}

public static void main(String[] args) {
divideByZero();
}
}

Output:

Exception in thread "main" java.lang.ArithmeticException: Trying to divide by 0
at Main.divideByZero(Main.java:5)
at Main.main(Main.java:9)

Declare the exception using the throws keyword

As we know that checked exception occurs inside the main() method. So you can declare the exception in the main() method using the throws keyword. You can declare the exception like this:

public static void main(String args[]) throws IOException;

IOException is the parent class of FileNotFoundException so that it by default handle the FileNotFoundException.

import java.io.*;
class ExceptionExample{

//handled exception using throws keyword.
public static void main(String args[]) throws IOException{
FileInputStream fis = null;
fis = new FileInputStream("D:/abc.txt");
int i;
while(( i = fis.read() ) != -1 ){
System.out.println((char) i);
}
fis.close();
}
}

All the above two programs are work fine and display file content.

Java finally block

In Java, the finally block is always performed no matter whether there is an exception or not. The finally block is optional. Moreover, for each try block, there can be only one finally block.

The basic syntax of finally block is as follows;

try {
//code
}
catch (ExceptionType1 e1) {
// catch block
}
finally {
// finally block always executes
}

2. Unchecked Exceptions

All the classes which inherit RuntimeException are known as Unchecked Exception. The Unchecked exceptions are not checked by the compiler at compile-time. But they are checked at runtime. In the case of an Unchecked exception if programmers will not handle the exception then we won’t get a compile-time error. Most of the time these exceptions occur due to the wrong data entered by the user (divide by zero). In such types of exceptions, the compiler will never force you to handle the exceptions. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBounds etc.

Example of Unchecked Exception:

In this example, we are dividing two numbers that are entered by the user. If the user enters the right data then our program will display a division of two numbers. If the user enters the wrong data then our program will display ArithmeticException. These exceptions will not occur at compile-time, it can occur at runtime.

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

//enter first number by user.
System.out.println("Enter the first number: ");
int num1 = sc.nextInt();

//enter second number by user.
System.out.println("Enter the second number: ");
int num2 = sc.nextInt();

//calculate result.
int result = num1/num2;
System.out.println("Division of two number is: " +result);
System.out.println("Program continues!");
}
}

Output: When a user enters the right data.

Enter the first number: 20
Enter the second number: 10
The division of two number is: 2
Program continues!

Output: When a user enters the wrong data.

Enter the first number: 20
Enter the second number: 0
error: exception in thread "main" java.lang.ArithmeticException: / by zero

Let’s see another example in this example we are taking an example of an array. Here my array has only 5 elements but we are trying to display the value of the 10th element. It should throw an exception ArrayIndexOutOfBoundsException.

class UncheckedException{
public static void main(String args[]){

/* This array has only 5 elements but
we are trying to display the value of the 10th element.
It should throw ArrayIndexOutOfBoundsException.
*/
int arr[] = {1,2,3,4,5};
System.out.println("The value of 10th element is:" +arr[10]);
}
}

Unchecked Exception handled using try and catch block:

class UncheckedException{
public static void main(String args[]){
try{
System.out.println(12/0);
System.out.println("We are in try block");
}
catch(ArithmeticException e){
System.out.println("Exception: " +e.getMessage());
}
System.out.println("Programs continues!");
}
}

Output:

Exception: / by zero.
Program continues!

Difference between Checked and Unchecked Exceptions

All the classes which inherit throwable class except RuntimeException and Error are known as Checked Exception while all the classes which inherit RuntimeException are known as Unchecked Exception.

The checked exceptions are checked by the compiler at compile-time while the Unchecked exceptions are not checked by the compiler at compile-time. But they are checked at runtime.

In case of checked exception, if programmers will not handle the exception then we will get a compile-time error while in case of Unchecked exception if programmers will not handle the exception then we won’t get a compile-time error.

FileNotFoundException, ClassNotFoundException, IOException, SQLException, etc. are the example of checked exception while ArithmeticException, NullPointerException, ArrayIndexOutOfBounds, etc. are the example of Unchecked exception.

Multiple Catch Blocks

If we want to perform a different task at the occurrence of different exceptions then we should go for multiple catch blocks. Let’s see an example of multiple catch blocks in Java.

class UncheckedException{
public static void main(String args[]){
try{
int arr[] = new int[5];
arr[3] = 12/0;
System.out.println("We are in try block");
}
catch(ArithmeticException ae){
System.out.println("Divide by zero exception");
}
catch(ArrayIndexOutOfBoundsException ae){
System.out.println("array elements outside limit");
}
catch(Exception e){
System.out.println("Other type of exception");
}
System.out.println("We are outside the try catch block");
}
}

Output:

Divide by zero exception
We are outside the try-catch block

Explicitly throw an Exception in Java

throw keyword in Java can be used to throw an exception. It can throw exceptions explicitly. We can throw either checked or unchecked exceptions using the throw keyword. Let’s understand with a simple example. In this example, we have created a two-variable balance and withdrawal amount. If the balance is less than the withdrawal amount then ArithmeticException has occurred. Therefore we throw an object of ArithmeticException and it will display a message on the screen “insufficient balance”.

class ExceptionExample{
public static void main(String args[]){
int balance = 5000;
int withdrawlAmount = 6000;

try{
if(balance < withdrawlAmount)
throw new ArithmeticException("Insufficient balance");
balance = balance-withdrawlAmount;
System.out.println(" Transactions successfully completed");
}
catch(ArithmeticException e){
System.out.println("Exception is: " +e.getMessage());
}
System.out.println("Programs continues!");
}
}

Output:

The exception is: Insufficient balance
Programs continue!

Throw vs Throws in Java:

throw keyword in Java can be used to throw an exception. It can throw the exception explicitly while throws keyword in java is used for declaring an exception

A throw is used inside the method while throws are used with the body signature.

A throw is used to throw only one exception while we can declare multiple exceptions using throws.

A throw is used in either checked exceptions or unchecked exceptions while throws only are used in a checked exception.

Final vs Finally vs Finalize in Java:

The Final is a modifier that is applicable for classes, methods, and variables. If a class declared as final then we can’t extend that class, if a method declared as final we can’t override that method in the child class, if a variable declared as final we can’t change the value of that variable.

Finally is a block always associated with try-catch to maintain the cleanup code. finally block is always run whether the exception handled or not.

Finalize() is a method that is always invoked by the garbage collector just before destroying an object to perform clean-up processing.