Exception Handling try catch finally blocks in Java

What is try block

A try block is used to surround a set of statements where exceptions may occur.

A try block used with catch and finally block

Also Read

Exception Handling in Java: Hierarchy Example and Types

What is a catch block

A catch block is created followed by a try block.

Whenever an exception is thrown from try block it catches in the appropriate catch block

There can be more than one catch block for a try block.

Syntax of try catch block

Java finally block

Java finally block is also associated with a try block.

Finally block is used to release resources that are used in a try block.

like closing a file. closing database connection

Finally block gets always executed when there is exception or not in try block.

We can use try and finally or try catch and finally.

Syntax of try-catch and finally

1 try and finally

2 try catch and finally

try catch java examples

ArithmeticException Example in Java

Output

Exception occurs at the line “a = 42 / d; “ , then this exception is thrown, program control transfer from  try block to catch block.

Once  catch block has executed program control continue with the next line in a program following entire try/catch statement.

In the line “catch (ArithmeticException e) “  e is a reference of exception “ArithmeticException”.

When we print the value of “e “ it will print  ( java.lang.ArithmeticException:/by zero                                                                    at  Test.main(Test.java:6) )

  • ArithmeticException is an exception class which resides in java.lang package.
  • “/by zero”  is a type of arithmetic exception (divided by zero).
  • “Test” is the name of the class.
  • “main” is a method in which an exception occurs.
  • 6 is line number in which exception occured.

Java try catch multiple exceptions

1 Try and multiple catch blocks

In java programming, when within a try block multiple exceptions occur then for handling those multiple exceptions we use multiple catches with a single try block.

When we pass no command line argument (during run time) than the length of command line argument (args.length) is zero means value of variable “a” is 0.

Than the output is:

When we pass one or more command line argument ( in this program one command line argument is passed “test” during run time) than the length of command line argument (args.length) is one means value of variable “a” is  1.

Than the output is:

2 Java try catch multiple exceptions

Unreachable Code in Exception Handling

In Java programming, in a sequence of catch statement exception subclass must come before its super class.

In a series, if exception super class comes before  its subclass than exception sub class would never be reached.

It is known as unreachable code. In Java programming, unreachable code is an compile-time error.    

Example unreachable code in Exception Handling

If we will try to compile this program we will receive an error message stating that the second catch statement is unreachable because ArithmeticException is a subclass of the Exception class. 

     Then the first catch statement will handle all exception-based errors, including Arithmetic Exception therefore second catch statement will never execute.

 To solve the problem, reverse the order of the catch statement.  

Nested try catch Java statements

In java programming, it is possible to create a try block within another try block. Such try block is known as nested try.

Nested try catch Example

If there is no command line argument present then the output.

If there is no command line argument present then the output.

Read More

User-Defined Exception in Java with Examples

Q : When a statement within a try block causes an exception, the remaining statements in the try block

Ans: Will Not be executed

Q: In a try/catch construct, after the catch statement is executed:

Ans: Statement just after the catch is executed

Q: Can you have multiple catch blocks on a try statement

Ans: Yes, as per the need we can have multiple catch blocks on a try statement

Q: To catch an exception, the code that might throw the exception must be enclosed in a ____________

Ans: try block

Q: If an exception occurs in a try-catch block, the code in the finally clause ________.

Ans: Get Executed. If with try block finally is associated then it always gets executed no matter it throws an exception or not.

Q: A try block may be followed by a finally block, without a catch block (Java try without catch).

Ans: Yes we can use try and finally without a catch block.

Q: Exceptions can be thrown by ________.

Ans: Throw statement is used to throw an Exception

Q: When is the code within a catch block executed?

Ans: If an exception occurs within the code in the try block then matched exception in the catch block gets executed.

Java unreported exception How to Handle it

The unreported exception is due to you have checked exception in your program and you are not handling it.

You can handle it

  1. By using try catch block
  2. By using throws keyword in method

unreported exception

Which of the following Throwables needs to be declared?

  1. Error
  2. RuntimeException
  3. CheckedException 
  4. Exception

Answer is 3

More MCQ

Throw and Throws Keywords in Java

In java programming, If the exception occurs within the try block it is thrown.

a throw keyword is used to throw an exception

A system-generated exception is automatically thrown by the java run time system but if we want to manually throw an exception, we can do so by using the throw keyword. 

Exception Handling try catch finally blocks in Java

Syntax of throw

           throw    ThrowableInstance;

here, ThrowableInstance must be an object of type Throwable or subclass of Throwable.

Example of throw keyword

In this program new is used to create an instance of NullPointerException and we get two chance to deal with the same error.

In the line  “throw new NullPointerException(“demo”);” 

throw keyword is used to throw  NullPointerException(“demo”). Here we set “demo” is a name of exception.

This NullPointerException(“demo”) catch by catch() method which resides in a demo() method.

 Line “throw e;”  re-throw the exception which is catch by catch() method which resides in a main() method.

Throws Keyword in Java

In a java programming, throws keyword list the type of exception that a method might throw.

throws keyword inform that method throws mentioned exceptions

In the throws clause, we declare all the exceptions that a method can throw.

  Syntax of throws:         

                                               

Here, exception1, exception2 are comma, list of the exception that a method can throw.

Example of throws

Explaination: We throws NullPointerException in the line “throw new NullPointerException(“demo”);” .

Here we set “demo” is a name of thread.

This line “throw new NullPointerException(“demo”);” throw the exception which is handled by catch block associated with try within main().

Difference between throw and throws in Java (throw vs throws)

throw keyword is used to throw an exception from method or from a block

throw is used inside method

throw new NullPointerException("demo");

throws keyword is used to inform that a method throws exception(s)

thorws keyword i s used in method header

public Scanner​(File source) throws FileNotFoundException

What is the purpose of the throw statement?

Throw is used to throw an exception from a method or from block of code

what is the difference between throwing an exception and catching an exception?

Throwing an exception can use to throw an exception using the throw keyword.

this can be implicit or explicit

45/0 <- throw ArithmeticException 

throw ArithmeticException(“Denominator can not be zero”);

To catch an exception one or more catch blocks can be used so that program executes properly.

The ______ keyword is used to manually throw an exception in java

The Throw keyword is used to manually throw an exception.

Read More

User Defined Exception in Java with Examples

Reference

How to Throw Exceptions

            

User Defined (Custom) Exceptions in Java with Examples

In Java programming, it is possible to create our own exception and such exception are called user defined exception in Java.

Exception class is a predefined class. Any user defined exception created by us must be a subclass of the predefine Exception class and created by extending the Exception class.

What is user defined (custom) exception in java

An Exception that is defined by the user/ programmer is known as user defined or custom exception.

example

  1. Checking user age if not valid age throw an exception
  2. If not in a specified time period then throw an exception
  3. If the user name and password is incorrect then throw an exception

All above exceptions are created by the user and throw when required.

How to throw user defined exception in java

 The throw and throws keyword are used for implementing user defined exception. 

throw: throw keyword is used to throw an exception explicitly from a method or from a block.   

for instance

 Here new NumberIsGreaterException();

is creating new exception and throwing it.

throws: throws keyword is used with method signature that informs that the method can throw mentioned exception.   

Here Scanner is class and above mentioned Scanner represents the constructor call, On the constructor call of above we have to handle File not found Exception.

how to create user defined exception in java

  1. Create a class
  2. Extend the Exception class
  3. Create a String argument constructor to pass custom message.

Examples of User Defined Exception in Java

Example1:   write a program to take a number from user by using command line argument during run time. if user will enter  more than 100 then grnerate user defined exception MyException.

Explaination: In the above program, name of user define exception is NumberIsGreaterException. 

In the above program user enter  the number 111 during run time using command line argument.

Here value of “m” is greter than 100 therefore  “throw  newNumberIsGreaterException ();” this throw statement throw the exception and catch by catch block, but before thorw “NumberIsGreaterException ()” constructer will call.

User defined exception in java program to check age is valid or not

InvalidAgeException.java

CheckAge.java

Output

user defined exception in java example to check a time is in range or not, if time is not in range then throw custom exception

InvalidTimeException.java

CheckTime.java

Output

Example: Write a program to create user defined exception in Java to check a given name exists or not. If name doesn’t exists then throw a custom exception.

InvalidNameException.java

CheckName.java

Output

How to write custom exception in java?

or

How to create custom exception in java?

or

How to create your own exception in java?

  1. Create a class
  2. Extend Exception class
  3. Create a constructor to show/pass custom message

Thread Life Cycle in Java

Thread Life Cycle in Java tells the various information of thread form born to terminate.

Thread life cycle contains the several stages and at a time any thread can be present  in a single state.

States of Thread life cycle

  1. Born
  2. Ready
  3. Running
  4. Blocked
  5. Sleep
  6. Wait
  7. Dead
Java Thread Life Cycle
Java Thread Life Cycle

Ready:  In this state thread is ready to execute but not running. 

When the start() method calls thread enters from born to ready state.

Running:  When a run() method executes highest priority ready thread assigned a processor and enter in a running state for execution.

Thread can visit more than ones in a running state.

Blocked: When a running thread has a input-output issue it enters in a blocked state from running state and when input-output issue solves it again comes in a running thread.

Sleep : A running thread enter in a sleep state for a specified number of milliseconds when a sleep() method calls.

When sleep time expires then thread moves to ready state.

Wait : When a low priority thread executing and high priority thread comes then high priority thread get preference and enter in a running state. Then low priority thread leaves a running state and moves to wait state for indefinite time.

When a high priority thread execution completes it calls waiting thread for execution by notify () & notifyall () method.

Dead: A running thread is enter in a dead state when its execution completes (run() method completes)   or terminate for any reason.

Multithreading in java example programs

  1. Created a class Thread1 that extends Thread class
  2. main() creates two thread t1 and t2.
  3. To start thread start method is called t1.start() and t2.start()
  4. Start method calls the run method to execute the work
  5. Thread.sleep() send thread to sleep state for 500 milliseconds
  6. From sleep state thread come back to ready then running state
  7. After completing work thread get dead.

Read More

Multithreading in Java

Multithreading in Java Thread Creation Method Use Example

Multithreading in Java

1 What is a Thread in Java

A thread is light weight process that can execute simultaneously. Multithreading in java allows multiple threads to run simultaneously.

  • A program can be divided into two or more parts that can run concurrently and each part of such program is known as thread.
  • In a simple word, thread is a lightweight sub-process.
  •  It is a smallest unit of processing.
  • When these threads execute concurrently for accomplishing a task is known multithreading.
  • In multithreading, each thread defines a separate path of execution. 
  • In multithreading, every thread has a priority between 1 to 10. Thread with highest priority get preference over lower priority thread for execution.
Java Process and Thread Diagram
Fig: Java Process and Thread Diagram

 In a java programming, Thread is a predefined class within a java.lang package.

Operating system (OS) can contain multiple process, in the above figure, there are three process  P1,P2 & P3, within OS and within P3 process there are three threads T1, T2& T3. There is context-switching between the threads.  

2 Difference between Process and Thread

Difference between Process and Thread
ProcessThread
A process has their own virtual address space.Threads are entities within a process it uses its virtual address space of process.
Two processes running on the same system at the same time do not uses address space.Two threads running within a process uses the same address space.
Every process has its own data segmentAll threads within the process uses the same data segment of process.
In multiprocessing, processes use inter process communication techniques to interact with other processes.In multithreading, threads do not uses inter process communication techniques because they not uses separate address spaces. They share the same address space therefore, they can communicate directly with other threads within process.
Processes have considerable overhead.Threads have almost no overhead;
Process is heavy weight.Threads are light weight process (LWP).
Process contains much information about system, resource.Threads carry less state information than process
When we create a child process from a parent process then it requires duplication of the resources of parent process.No duplication of resources is required when we create a child thread from main thread.

3 How to create a thread in Java

We can create a thread by two ways:

  1. By extending Thread
  2. By implementing Runnable interface
How to create a thread in Java
Fig: How to create a thread in Java

Lets see multithreading in java with example

A Creating Thread By Implementing Runnable Interface

  1. We can create a thread by creating a class that implements the Runnable interface.
  2. To implement Runnable, a class only need to implement a single method called run().
  3. Inside run () we will define the code that constitute the new thread.    
  4. When a new thread creates, it do not executes until we call its start () method. When start () method executes it call to run() method.  

Below is the multithreading program in java with implementing runnable interface

Example: Print hello to illustrate multithreading example in java

Output

Creating more than one thread in java :- multithreading in java example

Output

Another Example of Thread is

Result

Description:

Passing “this” as a argument, “DemoThread” is the name of the thread.  

In this program, main thread fineshes last because the main thread sleeps for 1000 milliseconds (1 seconds) between iteration, but the child thread sleeps for only 500 milliseconds.

This cause the child thread terminates earlier than main thread.

B Creating Thread By extending Thread class in java

  1. To create a thread we will create a thread a class that extends Thread class.
  2. To extend Thread class, a class only needs to implement a single method called run (). This extending class must override the run() method
  3. Inside run () we will define the code that constitute the new thread.                                                                                 
  4. When a new thread creates, it do not executes until we call its start () method. When start () method executes it call to run() method.

Simple Thread example in java

Example: Write a thread program in java by extending thread class.

Multithreading in Java example programs

Example: Write a program to show multithreading in java by extending thread class

Multithreading in java example using Thread class

Result

4 Thread Methods in Java

Commonly used methods of Thread class are as follows

Sr NoMethod and Description
1void run()
Work execute as a thread is defined in this method .
2void start()
Used to start a thred which Calls the run() method of the thread or child class.
3static void sleep(long miliseconds)
Suspend the thread for specified amount of time.
4static void sleep(long miliseconds,int nanos)
Suspend the thread for specified amount of time.
5void join()
This method is used to pause the ececution of current thread until it die. void join().
6 void join(long miliseconds)
Pause the execution of current thread for the pecified miliseconds.
7void join(long miliseconds,int nanos)
Pause the execution of current thread for the pecified miliseconds and nano seconds.
8 boolean isAlive()
To checks a thread is alive or not.
9 String getName()
Returns the name of the thread.
10 setName(String name)
Used to set the name of thread.
11 int getPriority()
Get the priority of the thread.
12 void setPriority(int priority)
Set the priority of thread.
13 static Thread currentThread()
Returns the reference of currently executing thread
14 long getId()
Returns the id of the thread.
15 static void yield()
Temporarily pause the currently executing thread and allow other threads to execute.
16 void suspend()
Used to suspend the thread.
17 void resume()
Used to resume the suspended thread.
18 void stop()
Used to stop the thread.
19 void interrupt()
Interrupts the thread.
20 boolead isInterrupted()
Check whether the thead is interrupted or not

Use of thread in java

  1. To Reduce the time of execution of a program
  2. To achieve parallel execution

Read More

Thread Life Cycle in Java

How many ways to create thread in java

There are two ways to create thread in java

  1. By Extending Thread class
  2. By Implementing runnable Interface.

Types of thread in java

  1. Daemon thread provide services to other threads
  2. User defined threads Created by User

How to perform two tasks by two threads ?

Real time example of multithreading in java

  1. When two or more I/O operations are not dependent of each other then we can perform them by different threads.
  2. When tow or more Database read/write operations are not dependent then we can perform using multithreads.
  3. Sending OTP on mobile and email id at same time.
  4. Adding post on social media (fb, twitter, pintrest etc) on one click using publisher software.
  5. Servers are multithreaded they create separate thread to handle each request.

Java multithreading programming exercises

  1. Create Two threads using Thread class.
  2. Create Two threads using runnable Interface.
  3. Implement Produces consumer problem in Java.

Packages in Java -Types Sub Packages and Examples

Packages in Java is one of the important concept. All Java classes and interfaces are arranged in package structure.

What is package in java

Packages is a namespace which contains related classes and Interfaces.

The methods and field of class define inside the package can be accessible in package outside package and in child classes based on access specifier.  

Packages are stored in a hierarchical manner and explicitly imported into a new class definition.

Types of packages in java

Java packages are classified into two types

  1. Predefined or Built-in package
  2. User defined package

1 Java API(Application Programming Interface) packages or Predefined packages or Built-in packages

These packages are defined by the system. Some example of system defined packages are

  1. java.lang: It contains fundamental classes like System, String Math, Number etc. This is the default package in java.
  2. java.util: This package contains collections framework, legacy collection classes, event model and other features.
  3. java.io: Provides system input output with stream classes and files
  4. java.awt: Contain classes for creating user interface graphic and Image classes.
  5. java.net: Contains classes related to networking and sockets
    The Java 1.3 contains nearly 60 predefined packages

Importing packages in Java with Example

import java.util.Scanner; -To import Scanner class

import java.util.*; To import all classes in util package

Here we import is used to import java.util.Scanner;

2 User defined packages in java

These packages are defined by the user.

How to create package in java

Defining as packages: To define a package, place “package” command as the first statement in the source file.

The syntax of packages creation :-

  • The class that is defined in the package must be public. So that is can be accessible by any another of them.
  • Java uses the file system file directories to store packages. We save the program with number.java and compile the package is as javac_d/number.java. Due to this compilation Mypackage directory is automatically created and .class file is stores in that directory.

Once the package creation has completed. Then the package information is including with the help of “import” keyword.  import keyword links the package with our program.

Java Package Example

It is place before the class definition:

Java Package
Java Package Example
  • In this program, package is within x folder and main program is within y folder in c drive.
  • Package name in this program is x.
  • File name and package class name must be same ex: (number.java- source file).

How to compile package in java

c:\> javac folder/filename.java

c:\>java package.filename

Note: If we want to access all the classes of information then the classes are stored in different files with the same package name.

Sub Packages

In Java, it is possible to create a sub packages for the main packages.

Syntax

                 package  pack1.pack2;  

Where pack1 is the main package and pack2 is the sub package.

Java packages sub package example

Result

How many predefined packages in java

As per different java versions there are different packages and classes this SO question is also helpful.

We Inspected javase 14 and find there are 225 predefined packages / sub packages in java.

Which Package is default package in java

The package which is not required to import explicitly is known as default package.

If we write simple program to print hello then there we use System, String class we don’t need to import that. These are defined in java.lang package.

Default Package in Java is java.lang

Which keyword is used for accessing the features of a package

The import keyword is used for accessing the features of a package.

We can import classes and interfaces in our current file using import.

What is Import in Java

Import in a keyword in java. We use import statement to import class or all classes from a package.

How to import a package in java

import java.util.Date; or
import java.util.*;

How to create a package in java (Steps to create package in java with example)

  1. Create a folder with package name
  2. Create java files inside folder
  3. each java files include package definition package packagename;

packages in java with example program 

How to run package program in java (How to execute package in java)

compile d:\>javac foldername/filename.java
run d:\>java packagename.filename

What is java lang package in java

java lang (java.lang) is default package in Java. It contains fundamental classes.

Use of packages in java

  1. Group related classes and interfaces
  2. To avoid Naming conflicts
  3. To provide Access Control

Example of predefined packages in java

Predefined packages are defend by Java Team like

  1. java.lang (default package)
  2. java.util
  3. java.io
  4. java.net
  5. java.math
  6. java.sql
  7. java.time
  8. java.awt
  9. java.text

view all

The package which should be created to categorize the package further

The package which should be created to categorize the package further is sub package

java package java.

sub packages java.land, java.util etc.

Which of the following is used to avoid naming conflicts?

  1. class
  2. Interface
  3. package
  4. templet

Answer is package

Reference

Java Package


JTable Pagination in Java JDBC and MySQL Database

JTable Pagination in Java JDBC and MySQL Database

Here we will see how to develop JTable Pagination in java.

We will use JDBC prepared statement and MySQL Database.

We used NetBeans IDE and Jdk 1.8 to develop this project.

Our Project Structure is as below

Pagination in JTable
Fig: Pagination in JTable

To develop this project we used Book Example.

Project Development Steps are

  1. Create table in MySQL Database
  2. SetUp Pagination Project
  3. Create Model (Pojo) Class
  4. Create a DAO class to Perform JDBC Operations
  5. Create Frame to show data in JPanel
  6. Implement Pagination Concepts.

1 Create Table in MySQL Database

We created ebhor database and table called book as below

Inserted 100 records on it.

You can use any “MySQL Data Generator like generatedata.com generate 100 rows or as many as you want.

How to import data in MySQL database
Fig: How to import data in MySQL database

In above figure screen when you scroll down you will find Go button click on it.

Go to browse to see data in table .

After uploading data check you data by clicking on browse in PHPMyAdmin.

Browse the PhpMyAdmin database
Fig: Browse the Book table

Book table created and 100 Records are uploaded in table.

2. SetUp Pagination Project

Create a new Java Project in Netbeans IDE

Select Java in categories and Java Applications in Project.

Fig: New Project Start in NetBeans
Fig: New Project Start in NetBeans

Provide name “Pagination” to your project

Click on Use Dedicated Folder for Storing Libraries.

How to assign Project Name in NetBeans
Fig: Assign Project Name in NetBeans

Now at left side on project explorer

click on Pagination Project.

there create packages

ebhor.model
ebhor.dao
ebhor.frame
ebhor.pagination

Now right click on library and and click on menu Add Jar/Folder…

Now include mysql-connector-java-5.1.14-bin.jar Jar file

How to add mysql-connector-java-5.1.14-bin.jar in NetBean IDE
Fig: Adding mysql-connector-java-5.1.14-bin.jar in NetBean IDE

Next we will create a Pojo class.

3 Create a Model to hold Data

Inside ebhor.model package create a POJO Class Book

Book class contains field id, name, author publication, addDate field.

All fields getter setter , constructos and toString()

Book.java

4 Create a DAO Class to Perform JDBC Operations

Here establish a connection with database.

Extracting data from database are handling .

Inside ebhor.dao following classes are there

ConnectionFactory.java

This class contains a method getConnection() creates connection with MySQL database using database username, password and database name.

getConnection() returns connection Object.

BookDAO.java

This class contains two methods

1 fetchBySize() – This method takes two integer arguments

  1. start is used to select start row in book table.
  2. size is used to select specified number of elements from start.

If you pass parameter fetchBySize(11,10) then it will select 10 records from MySQL with starting table row of 11.

Result set values are stored in DefaultTableModel Object.

DefaultTableModel value can easily represent data in JTable.

2. getRowCount() this method is used to find total number of rows in table.

5 Create Frame to show data in JPanel

UI designing and Action handling work is done here.

BookFrame.java is created in ebhor.frame package

BookFrame.java contains following methods

1 A Default Constructor –

Here a main JPanel is created with GridLayout.

Two other JPanel is created.

tablePanel -to place JTable and pagingPanel to place Paging buttons.

Inside this getCount() and getPageData() is called.

2 getCount() –

This method work is to find book table record count by calling getRowCount() from BookDAO.java.

It also calculate the total pages for pagination based on PAGE_SIZE field.

3. getPageData() –

Work of this method is to get records from Book Table. and set it to JTable based on page number.

To update pagination details getPaginationDetails() is get called.

4 getPaginationDetails() –

This method is used to get dynamic page numbers from Pagination.java.

According to numbers it generates buttons and add actionListeners to buttons.

Also handle button disable and enable features for first and last page number.

5 ActionPerformed()-

Handle the click actions of dynamically generated buttons.

6 public static void main() –

This function is starting execution point for our program.

6 Implement Pagination Concepts

ebhor.pagination.Pagination class is created to implement pagination concept.

public static int[] getPageNos(int currentPage, int totalPages) is used to implement pagination concept.

it takes two argument currentPage and totalPages to get next set of page numbers and return integer array.

Pagination.java

Read More

Login form in Java Swing and MySql Database with source code

Registration Form in Java Swing with MySql Database

How to find String length in java with and without string method

String length in java

Get String length with String length() method

To find String length in java there is a method length().

This method is used to get length of string.

Signature of length method is:

Length method returns the length of the string. it counts the number of unicode in string.

This is very simple way to get length of a string in java.

Output

Finding the length of unicode string in java

Here we are considering hindi language stored in String. We use length() to get the string length.

You can take any unicode character to check length string length() works properly.

Output

Finding the String length in java of unicode characters

Here we have stored a unicode value in String and finding its length.

Output

Using toCharArray() to find String length in java

toCharArray() is another method in String class to convert String to character array.

Signature of toCharArray() is

In above program String is converted to character array using toCharArray().

Character array is have a field length. This length property finds the length of character array.

Output

Using Function to find the String length in java

In above program you find length of Java String in main method.

Here we have created two static methods length() and length1().

these two methods are accepting string and getting its length.

Using Recursion to find String length

Here we are using recursion to find the length of string.

When a function is called it is checking the lenth of string if string is empty then return zero else call again itself with adding one to return value.

On each recursive call we are eliminating first character from string.

Output

Hope you learn and understand how to get length of string as we discussed different ways to find string length.

Keep Reading other topics.

Inheritance in Java-Types and Examples

Inheritance in Java is the process of acquiring the properties of one class object into another class object.

It allows the hierarchical classification. Inheritance also provides the facility of reusability.

In Java programming, a class that is inherited is called a superclass or sub class or parent class and class that does the inheriting is called sub class or child class.     

If we want to inherit a class, we simply incorporate the definition of one class into another class by using extends keyword.

General form of a class declaration that inherits a super class

Type of Inheritance in Java

There are following type of inheritance

  1. Single level Inheritance
  2. Multi-level Inheritance
  3. Hierarchical Inheritance
  4. Hybrid Inheritance

Note: Java does not support multiple inheritance.        

Single level Inheritance

Property of single level inheritance is as below

Single level Inheritance in Java
Fig:java single inheritance
  • One Super class and one sub class
  • Sub class inherits the features of super class

Write a program for single level inheritance.

Output

Multi level Inheritance

In multi level inheritance inheritance exists in multiple level.

Multi level Inheritance  in Java
Multilevel Inheritance
  • One Parent Class
  • It has a child class
  • Child has again child class

This process may continue and each child class inherits feature of all parent class.

program for Multi level inheritance in Java

Result

Hierarchical Inheritance

One Parent class can have multiple child class this type of inheritance is known as Hierarchical Inheritance.

  • One Parent class
  • Multiple Child class
  • Each Child Inherits the feature of Parent
hierarchical inheritance in Java
java hierarchical inheritance

Write a program for Hierarchical Inheritance.

Result

Hybrid  Inheritance

Combination of two or more Inheritance type is known as Hybrid Inheritance

Hybrid  Inheritance in Java
java Hybrid Inheritance

Note: A subclass can access the public member of super class. A subclass can’t access the private member of super class.

Super Class Cant Access Sub Class Member

A sub class can access all the public member of super class but reverse is not true. Super class cannot access sub class data.

Result

A sub class can’t access the private member of super class.   

Result

String in Java- Constructor methods and examples

Java String is defined in java.lang.String.

Java String is a sequence of characters quoted in double quote (” “).

Java String Constructors

Sr NoConstructor and description
1String()
Create a new empty string object
2String(byte[] bytes)
Construct a string object with byte array
3String(char[] value)
Construct a string object with character array
4String(String original)
Create a string with another string
5String(StringBuffer buffer)
Create a string with StringBuffer object
6String(StringBuilder builder)
Create a string with StringBuilder object

Java String Methods

There are many methods avaible in string class few common and widely used methods are

Java String Method charAt()

This method takes one integer argument and return a character specified at index position.

For any string the index value starts from 0 to string length -1 position.

If passed index value not in valid range then it throws IndexOutOfBoundsException.

For example string Hello Friends contains 13 characters starting from 0 to 12 H is first position with index value 0, F is in seventh position with index value 6 and s is in 13 position with index value 12.


Using number other then 0 to 12( 0 to length()-1) will result in IndexOutOfBountException

Signature:

public char charAt(int index)

Parameters:

index -Integer index value to get character at specified index position.

Return:

Character at passed index value.

Exception Throws:

IndexOutOfBoundsException If index value in not between 0 to String length()-1

Example

Result

Now Print all characters with its index value

Example

Result

Java String Method compareToIgnoreCase()

This method is used to compare two string with case ignorance and compare both string lexicographically. If both strings are same then it returns 0. If first string is greater then another then it returns positive integer, if second string is greater then first then it returns negative integer value.

Signature

public int compareToIgnoreCase(String str)

Parameters

str – String value that will compared with string.

Return

Integer value. if string is greater then passed str value then it returns positive integer if both strings are equal then it returns zero if passed str is greater then string then this method returns negative integer value.

Example1

Result

In above program comparing same string is returning 0. In second println() statement A is lexicographically smaller then b so it is returning -1. In third println() statement C is lexicographically greater then b so it is returning 1 and so on.

Example2

Result

Java String Method indexOf with int parameter

indexOf(int ch) method is used to get the first occurrence of a character in given string. This method takes a character input (in Unicode code units) and return the index value of character in string, if character not found in string then it returns -1.

Signature

public int indexOf(int ch)

Parameters

A charcter value in unicode code point.

Return

Returns the int value that represents the first occurance of the character in string, if character not fount in string then it returns -1.

Example

Java String Method indexOf()

indexOf method is used to get the first occurrence of a sub string in given string. This method takes a string input and return the index value of it in given string object, if sub string not found in string then it returns -1.

Signature

public int indexOf(String str)

Parameters

str is sub string value to find in specified string.

Return

Returns the int value that represents the first occurrence of the sub string in string, if sub string not fount in string then it returns -1.

Example

Result

Java String Method lastIndexOf()

This method take a string parameter as input and return the last index value of parameter string in specified string. If string not found then it returns -1.
The second overloaded method find the string from fromindex position.

Signature

public int lastIndexOf(String str)
public int lastIndexOf(String str, int fromIndex)

Parameters

str- to search in String
fromindex- to search str from specified index

Return

Return the last index value of parameter str in specified string. If str not found then it returns -1

Example

Result

Java String substring() method

This method takes a int argument to generate sub string of string. It returns sub string starting from beginIndex value to last of string.
The second overloaded method allows to specify the ending index value also.
beginIndex parameters is inclusive and endIndex is exclusive.

Signature

public String substring(int beginIndex)
public String substring(int beginIndex,int endIndex)

Parameters

beginIndex –generate substring from this index value(inclusive).
endIndex-generate substring up to endIndex-1 value(exclusive).

Return

A substring

Throw

IndexOutOfBoundsException: If beginIndex is negative or endIndex is greater then length of string or if beginIndex is greater then endIndex.

Example

Result

Java String concat() method

String concat() is used to concatenate two strings. The parameter str string is appended to specified string and new string object is returned by this method.
Example
“Hello ”.concat(“Friends”)
This will generate a new string object “Hello Friends”

Parameters

Str – is string parameter used to concatenate with specified string

Example

Here str is concatenated with ” ” then it is concatenated with str1 and result is assigned to str3 String object.

Read More