CallableStatement in Java | How to use a CallableStatement in Java to Call a Stored Procedure?

CallableStatement in Java

CallableStatement in JDBC is an interface present in a java.sql package and it is the child interface of Prepared Statement. Callable Statement is used to execute the Stored Procedure and functions. The driver software vendor is responsible for providing the implementations for the Callable Statement interface. This tutorial explains in detail how to create, set input parameters as well as execute a CallableStatement in Java.

Stored Procedure vs Function

The difference between stored procedure and function is given below:

CallableStatement in Java

Creating a CallableStatement

You can create an object of the CallableStatement (interface) by utilizing the prepareCall() Method of Connection Interface. This particular method accepts a string variable denoting a query to call the stored procedure and returns a CallableStatement Object.

Callable Statements can have different types of parameters such as IN, OUT, INOUT. In order to pass these input parameters to the procedure call you can use place holder and set values to these by using the setter methods (setInt(), setString(), setFloat()) given by the CallableStatement Interface.

Setting Values to the Input Parameters

You can set values to the input parameters of the procedure call by taking the help of setter methods. They accept two arguments. One is an integer value denoting the placement index of the input parameter and the other is int, string, float, etc. to represent the value you need to pass as an input parameter to the procedure.

Note: Other than Index you can even pass the name of the parameter in String format.

Do Read:

Executing the Callable Statement

After you create a CallableStatement Object you can execute it using one of the execute() methods.

Types of Parameters in CallableStatement

Parameter Description
IN The parameter in which the value is unknown when the SQL Statement is created. Bind Values to IN Parameters using the setXXX() Methods.
OUT This is the parameter whose value is supplied by the SQL Statement it returns. You can retrieve values from the OUTParemeter by taking the help of getXXX() methods.
INOUT This parameter provides both input and output values. Bind variables using the setXXX() methods and retrieve values using the getXXX() methods.

How to Call Stored Procedure using CallableStatement?

1. Make sure the stored procedure available in the database:
create procedure add proc(num1 IN number,num2 IN number,num3 OUT number)as

BEGIN
num3=num1+num2;
END;

2. Create a callable statement with the procedure call:

CallableStatement cst = con.preparecall("{call addproc(? ? ? )}");

3. provides values for every IN parameter by using a corresponding setter method

cst.setInt(1,100);
cst.setInt(2,100);

4. Register every out parameter with JDBC types:
if the stored procedure has OUT parameter then to hold that output value we should register every OUT parameter by using the following method.

public void registerOutParameter(int index,int jdbc type)

eg:

cst.registerOutParameter(3,Type.INTEGER)

note: Before executing the stored procedure call, all input parameters should set with values, and for every OUT parameter, we have to register with JDBC types.

5. Execute procedure call:
To execute the procedure, we used the execute method.

cst.execute ();

6. Get the result from OUT parameter by using the corresponding getXXX() method:

int result = cst.getInt(3);

Example to Call a Stored Procedure using JDBC

To call the stored procedure, make the sure stored procedure available in the database. Here we are assuming that the stored procedure looks like this:
create procedure getempinfo(id IN number, name OUT varchar, sal OUT number) as
BEGIN

select ename, esal, into name, sal from employee where eno=id;

END;

In this example, we are going to call the stored procedure getempinfo that receives employee no: as an input and provides the corresponding name and salary of the employee.

import java.sql.*;
class EmployeeInfo
{
public static void main(String args[]) throws Exception
{
Connection con = DriverManager.getConnection("jdbc.mysql://localhost:3306/emp", "root", " ");
CallableStatement cst = con.prepareCall("{call getempinfo(? ? ?)}");
cst.setInt(1,100);
cst.registerOutParameter(2,Types.varchar);
cst.registerOutParameter(3,Types.Float);
cst.execute();

System.out.println("Employee name is" , +cst.getString(2));
System.out.println("Employee salary is" , +cst.getFloat(3));
}
}

How to compare two Strings using equalsIgnoreCase() Method in Java?

How to compare two Strings using equalsIgnoreCase Method in Java

In the last tutorial, We have learned how to compare two strings using the equals() method. But there is one limitation of the equals() method. By default equals() method checks the content including the case also i.e. The comparison is case sensitive. If the comparison is case insensitive it returns false. To overcome this problem we can use the equalsIgnoreCase() method in Java. Let’s first see the example of, what the problem to use the equals() method.

class StringCompare{
public static void main(String args[]){
String str1 = "Javastudypoint";
String str2 = new String("JAVA");
String str3 = new String("Javastudypoint");
String str4 = "Java";
System.out.println(str1.equals(str3)); //true
System.out.println(str2.equals(str4)); //false
System.out.println(str1.equals(str2)); //false
}
}

Output:

true
false
false

The problem with the above code is it check the case also. In the above code, the str2 and the str3 have the same content but the case is different therefore the equals() method returns false.

equalsIgnoreCase() in Java Definition & Usage

To overcome the above problem, we can use the equalsIgnoreCase() method. This method is used to perform the comparison that ignores the case differences. When it compares two strings, it considered A-Z the same as a-z.

Syntax: The syntax of the equalsIgnoreCase() is given below:

public boolean equalsIgnoreCase()

Also, Read: How to compare two Strings in Java using equals() Method?

Pictorial Representation of Comparison of Strings using equalsIgnoreCase() Method

How to compare two Strings using equalsIgnoreCase() Method in Java

How to Compare two strings in Java Using the method equalsIgnoreCase()?

Let’s understand the equalsIgnoreCase() method in Java with an example.

class StringCompare{
public static void main(String args[]){
String str1 = "Javastudypoint";
String str2 = "javaSTUDYpoint";
String str3 = "JAVASTUDYPOINT";
String str4 = "Java Tutorial";
//true because content and case are same
System.out.println(str1.equalsIgnoreCase(str3));
//false because content and case are not the same.
System.out.println(str2.equalsIgnoreCase(str4));
//true because content and case are same
System.out.println(str1.equalsIgnoreCase(str2));
}
}

Output:

How to compare two Strings using equalsIgnoreCase() Method in Java

Example Illustrating Use of .equalsIgnoreCase in String Comparison

// Java program to demonstrate
// use of .equalsIgnoreCase operator in Java

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

// Get some Strings to compare
String s1 = "A";
String s2 = "A";
String s3 = "a";
String s4 = new String("A");

// Compare s1 and s2
// It should return true as they both
// have the same content
System.out.println(s1 + " .equalsIgnoreCase " + s2
+ ": " + s1.equalsIgnoreCase(s2));

// Compare s1 and s3
// It should return true as they both
// have the same content being case insensitive
System.out.println(s1 + " .equalsIgnoreCase " + s3
+ ": " + s1.equalsIgnoreCase(s3));

// Compare s2 and s3
// It should return true as they both
// have the same content being case insensitive
System.out.println(s2 + " .equalsIgnoreCase " + s3
+ ": " + s2.equalsIgnoreCase(s3));

// Compare s1 and s4
// It should return true as they both
// have the same content
System.out.println(s1 + " .equalsIgnoreCase " + s4
+ ": " + s1.equalsIgnoreCase(s4));
}
}

Output:

A .equalsIgnoreCase A: true
A .equalsIgnoreCase a: true
A .equalsIgnoreCase a: true
A .equalsIgnoreCase A: true

Java String isempty() Method with Example – Syntax, Definition, Usage

Java String isempty() Method with Example

In the last tutorial, we have learned how to compare two strings in Java. In this tutorial, we will learn how to check if the string is empty or not using the String isempty(). Learn about the syntax, parameters of the String isempty() and how it works internally and the implementation code used, etc.

String isempty() Definition & Usage

The isEmpty() method of the String class is used to check whether the string is empty or not. If the string is empty then the isEmpty() method returns true otherwise it returns false. In other words, we can say that this method returns true if the string length is 0.

Syntax: The syntax of the isEmpty() of string class is given below

public boolean isEmpty()

How isEmpty Works Internally and Implementation Code?

isEmpty internal code is much straightforward. Check the below code to know about its internal implementation and how it works internally.

public boolean isEmpty() {
return value.length == 0;
}

Check the String Length and If the String Length is 0 return true or else return false. This method will not check for blank spaces.

Do Read:

Example of String isEmpty() Method in Java

class StringEmpty{
public static void main(String args[]){
// Non-empty string.
String str1 = "Javastudypoint";
//empty string.
String str2 = "";
//returns false.
System.out.println(str1.isEmpty());
//retuens true.
System.out.println(str2.isEmpty());
}
}

Output:

Java String isempty() method with Example

String isEmpty Method Example Program to check if the String is Null or Not

package examples.java.w3schools.string;

public class StringisBlankExample {
public static void main(String[] args) {
// String 1 - null string - no value assigned
String nullString = null;

// String 2
String valueString = "value string";

// printing values
System.out.println("nullString :: " + nullString);
System.out.println("valueString :: " + valueString);

// Use case : Using if condition.

if (nullString == null || nullString.isEmpty()) {
System.out.println("nullString is null or blank");
} else {
System.out.println("nullString is having some value");
}

if (valueString == null || valueString.isEmpty()) {
System.out.println("valueString is null or blank");
} else {
System.out.println("valueString is having some value");
}

}
}

Output:

nullString :: null
valueString :: value string
nullString is null or blank
valueString is having some value

Comparable vs Comparator in Java with Example | When to Use Comparable and Comparator in Java?

Comparable vs Comparator in Java with Example

Comparable in Java is an interface that is present in java.lang package. A comparable object is used to comparing itself with other objects. The objects of classes that implement the Comparable interface can be ordered. In other words, classes that implement the Comparable interface contain an object that can be compared in some meaningful manner. It contains only one method named compareTo(Object obj).

Method Used in Comparable

public int compareTo(Object obj): The compareTo(Object obj) method is used to compare the current object with the specified object.

  1. It returns a positive integer value if the current object is less than the specified object.
  2. It returns a negative integer value if the current object is greater than the specified object.
  3. It returns zero if the current object is equal to the specified object.

Example to Demonstrate compareTo(Object obj) Method

class compareToExample{
public static void main(String args[]){
System.out.println("A".compareTo("B"));
System.out.println("B".compareTo("A"));
System.out.println("A".compareTo("A"));
}
}

Output:

-1
1
0

When to Use Comparable in Java with Example?

If we want to sort the elements according to the default natural sorting order then we should go for Comparable interface. If we go for default natural sorting order then the object should be homogeneous and comparable. An object is said to be comparable if its corresponding class implement the Comparable interface. All the String and Wrapper classes by default implement the Comparable interface. Therefore if you want to sort the String element then you don’t need to implement a Comparable interface.

Read More Articles:

Comparable Example in Java

Suppose you have a class Employee and you want to sort employee id on the basis of natural sorting order which is ascending order for numbers and alphabetical order for String then you can implement Comparable interface with the Employee class and override the CompareTo(Object obj) method of Comparable interface. We can sort the element of the String object, wrapper class object, and user-defined class object. Here we have discussed the user-defined class object.

import java.util.*;
class Employee implements Comparable{
int eid;
String name;
int age;

//constructor for initialize the value
Employee(int eid,String name,int age){
this.eid=eid;
this.name=name;
this.age=age;
}

//compareTo() method.
public int compareTo(Employee emp){
if(eid==emp.eid)
return 0;
else if(eid>emp.eid)
return +1;
else
return -1;
}
}

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

ArrayList al=new ArrayList();
al.add(new Employee(101,"Amit",23));
al.add(new Employee(106,"Ajay",27));
al.add(new Employee(102,"Vijay",29));
al.add(new Employee(120,"Sumit",32));
al.add(new Employee(105,"Rahul",28));

//call sort() method of collection interface
Collections.sort(al);

//for each loop to print the employee details
for(Employee emp:al){
System.out.println(emp.eid+" "+emp.name+" "+emp.age);
}
}
}

Output:

Comparable vs Comparator in Java with Example 1

Comparators in Java

Comparators in Java is an interface that is present in java.util package. Sometimes we do not satisfy with the default natural sorting order then we should go for Customized sorting order. For customized sorting order we need to specify a Comparator when you construct a tree set. The comparator interface contains two methods:

Method Used in Comparator

1. public int compare(Object obj1, Object obj2): This method is used to compare the first object with the second object. It is similar to the compareTo(Object obj) method of Comparable interface. This method returns a positive integer value if obj1 is greater than obj2, and returns a negative integer value if obj1 is less than obj2. If the obj1 and obj2 are equals then it returns 0. A ClassCastException has occurred if the types of the objects are not compatible for comparison.

2. public boolean equals(Object obj): This method is used to compare the current object with the specified object. Overriding equals() method is optional because it is already available in every Java class from Object class through inheritance.

Comparator Example in Java

In this example, we are going to show you how we use a comparator for customized sorting order. Here we are trying to insert integer value in the tree set according to descending order(own customized order). Let’s understand this with a simple example

import java.util.*;
class ComparatorDemo{
public static void main(String args[]){
TreeSet tset = new TreeSet(new MyComparator());
tset.add(10);
tset.add(40);
tset.add(20);
tset.add(30);
tset.add(60);
tset.add(50);

//displaying custom sorted order
System.out.println("Custom sorted order is: " +tset);
}
}

//our own class implements comparator interface
class MyComparator implements Comparator{
public int compare(Object obj1, Object obj2){

//typecast to an integer.
Integer I1 = (Integer)obj1;
Integer I2 = (Integer)obj2;
if(I1<I2) return +1; else if(I1>I2)
return -1;
else
return 0;
}
}

Output:

Comparable vs Comparator in Java with Example 2

What is the Difference Between Comparable and Comparator in Java?

Comparable vs Comparator in Java with Example 3

TreeSet in Java with Example – Methods, Constructors, Operations | How TreeSet Works Internally in Java?

TreeSet in Java with Example

TreeSet in Java is an implementation class of the SortedSet interface that uses a tree for storage. Java TreeSet is the most important part of the collection framework. TreeSet class in Java came in Java 1.2 version. In Java TreeSet objects are stored in sorted and ascending order, therefore, access and retrieval time are quite fast, which makes TreeSet is the best choice when storing a large amount of sorted information that must be found very quickly.

Hierarchy of TreeSet Class

TreeSet in Java with Example 1

The important points about TreeSet in Java:

  1. The underlying data structure for TreeSet is Tree.
  2. Java TreeSet doesn’t allow you to store duplicates elements.
  3. In Java TreeSet insertion order is not preserved.
  4. Java TreeSet doesn’t allow you to store heterogeneous objects, it will give you ClassCastException if you are trying to insert heterogeneous elements.
  5. If you are depending on the default natural sorting order then objects should be homogeneous and comparable. If the objects are not comparable and homogeneous then it will give you a runtime exception.
  6. Java TreeSet allows you to insert the null element but only once till Java 6 version.
  7. Java TreeSet is the best choice for storing large amounts of sorted information.

Constructors in Java TreeSet

There are 4 constructors are defined in Java TreeSet, which are described below

Constructor Description
TreeSet() The first constructor creates an empty tree set where elements are sorted in ascending order according to the default natural sorting order.
TreeSet(Comparator comp) The second constructor creates an empty tree set where elements will be inserted according to the customized sorting order using a comparator object.
TreeSet(Collection c) The third constructor creates a tree set that contains the elements of collection c.
TreeSet(SortedSet ss) The fourth constructor creates a tree set that contains the elements of SortedSet ss.

Treeset Methods in Java

Java TreeSet defines all the methods which are available in NavigableSet, SortedSet, and collection interface. Some of them are discussed below:

Method Description
void add(Object obj) This method is used to add the elements in TreeSet according to some sorting order.
Object first() This method returns the first element from TreeSet if TreeSet is not null else it will give you a runtime exception NoSuchElementException.
Object last() This method returns the last element from TreeSet if TreeSet is not null else it will give you a runtime exception NoSuchElementException.
boolean contains(Object obj) This method returns true if TrreeSet contains the specified object else it returns false.
void clear() This method is used to remove all the elements from TreeSet.
int size() This method is used to return the size of the set.
boolean remove(Object obj) This method is used to remove the specified element from TreeSet.
boolean isEmpty() This method returns true if the set contains no elements.
Object clone() This method returns the shallow copy of the TreeSet instance.

Operations on TreeSet Class

Let us discuss in detail the various commonly performed operations on TreeSet

Adding Elements

To add elements to the TreeMap we use the add() method. However, Treeset will not retain the Insertion Order. Internally for each and every element, the values are compared and then sorted in ascending order. Remember duplicate elements aren’t allowed and duplicate elements are ignored. Null Values aren’t accepted by the TreeSet.

// Java code to demonstrate
// the working of TreeSet
import java.util.*;

class TreeSetDemo {

public static void main(String[] args)
{
Set<String> ts = new TreeSet<>();

// Elements are added using add() method
ts.add("Geek");
ts.add("For");
ts.add("Geeks");

System.out.println(ts);
}
}

Output:

[For, Geek, Geeks]

Accessing the Elements

After adding the elements if you want to access the elements you can use the inbuilt methods such as contains(), first(), last(), etc.

// Java code to demonstrate the workings of TreeSet
import java.util.*;
class TreeSetDemo {

public static void main(String[] args)
{
NavigableSet<String> ts = new TreeSet<>();

// Elements are added using add() method
ts.add("Geek");
ts.add("For");
ts.add("Geeks");

System.out.println("Tree Set is " + ts);

String check = "Geeks";

// Check if the above string exists in
// the treeset or not
System.out.println("Contains " + check + " "
+ ts.contains(check));

// Print the first element in
// the TreeSet
System.out.println("First Value " + ts.first());

// Print the last element in
// the TreeSet
System.out.println("Last Value " + ts.last());

String val = "Geek";

// Find the values just greater
// and smaller than the above string
System.out.println("Higher " + ts.higher(val));
System.out.println("Lower " + ts.lower(val));
}
}

Output:

Tree Set is [For, Geek, Geeks]
Contains Geeks true
First Value For
Last Value Geeks
Higher Geeks
Lower For

Removing Values

We can remove the values from the TreeSet using the method remove(). There are several methods to use in order to remove the first or last value.

// Java code to demonstrate
// the working of TreeSet

import java.util.*;
class TreeSetDemo {

public static void main(String[] args)
{
NavigableSet<String> ts = new TreeSet<>();

// Elements are added using add() method
ts.add("Geek");
ts.add("For");
ts.add("Geeks");
ts.add("A");
ts.add("B");
ts.add("Z");

System.out.println("Initial TreeSet " + ts);

// Removing the element b
ts.remove("B");

System.out.println("After removing element " + ts);

// Removing the first element
ts.pollFirst();

System.out.println("After removing first " + ts);

// Removing the last element
ts.pollLast();

System.out.println("After removing last " + ts);
}
}

Output:

Initial TreeSet [A, B, For, Geek, Geeks, Z]
After removing element [A, For, Geek, Geeks, Z]
After removing first [For, Geek, Geeks, Z]
After removing last [For, Geek, Geeks]

Iterating through the TreeSet

There are a number of ways to iterate through the Treeset. Of all those one of the popular methods is to use the enhanced for loop.

// Java code to demonstrate
// the working of TreeSet

import java.util.*;
class TreeSetDemo {

public static void main(String[] args)
{
Set<String> ts = new TreeSet<>();

// Elements are added using add() method
ts.add("Geek");
ts.add("For");
ts.add("Geeks");
ts.add("A");
ts.add("B");
ts.add("Z");

// Iterating though the TreeSet
for (String value : ts)
System.out.print(value + ", ");
System.out.println();
}
}

Output:

A, B, For, Geek, Geeks, Z,

Features of a TreeSet

  • Treeset Implements Sorted Interface. Thus, duplicate values are not permissible.
  • TreeSet Objects are stored in a sorted and ascending order.
  • It doesn’t preserve the insertion order of elements. However, elements are sorted by keys.
  • If we depend on the default natural sorting order then the object being inserted into the tree needs to be homogeneous and comparable.
  • Treeset doesn’t allow heterogeneous object insertion. If we try to add heterogeneous objects it will throw a classCastException during the Runtime.
  • It accepts only generic types that are comparable.

Also, Read:

How Treeset Works Internally in Java?

Treeset is an implementation of the self-balancing binary search tree. Thus operations such as add, remove, and search takes O(log(N)) time. It is because in a self-balancing tree the height is always made sure that O(log(N)) for all kinds of Operations. Thus, Treeset is considered to be an almost efficient data structure in order to store huge sorted data as well as perform operations on it. Operations such as Printing N elements in the sorted order take O(N) time.

Synchronized TreeSet: Treeset Implementation isn’t synchronized. It means if multiple threads access a set concurrently then at least one of the threads modifies the set and it must be synchronized externally. This is obtained by synchronizing some objects that naturally encapsulate the set. If there are no such objects then the set needs to be wrapped using the Collections.synchronizedSortedSet Method. It is done at the time of creation so as to prevent accidental unsynchronized access to the set.

TreeSet ts = new TreeSet(); 
Set syncSet = Collections.synchronziedSet(ts);

TreeSet in Java with Example

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

//creating a tree set
TreeSet tset = new TreeSet();

//adding elements in the tree set
tset.add("Ajay");
tset.add("Vijay");
tset.add("Amit");
tset.add("Sumit");
tset.add("Rahul");

//displaying elements
System.out.println("The tree set elements are: " +tset);
}
}

Output:

TreeSet in Java with Example 2

Java TreeSet Example to Add a Heterogeneous Element

Java TreeSet doesn’t allow you to store heterogeneous objects, it will give you ClassCastException if you are trying to insert heterogeneous elements.

import java.util.*;
class Person
{
public static void main(String args[])
{
//creating a tree set
TreeSet tset = new TreeSet();

//adding elements in the tree set
tset.add("Ajay");
tset.add("Vijay");
tset.add("Amit");
tset.add("Sumit");
tset.add("Rahul");

//add heterogenos element
tset.add(new Integer(10));

//displaying elements
System.out.println("The tree set elements are: " +tset);
}
}

Output:

TreeSet in Java with Example 3

Java TreeSet Example to Insert a Null Element in the Non-Empty TreeSet

If we are trying to insert the null element as a non-empty tree set, it will give you a runtime exception because the null element compared to the existing elements, and the null value can’t be compared to any element.

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

//creating a tree set
TreeSet tset = new TreeSet();

//adding elements in the tree set
tset.add("Ajay");
tset.add("Vjay");
tset.add("Amit");
tset.add("Sumit");
tset.add("Rahul");

//add heterogenos element
tset.add(null);

//displaying elements
System.out.println("The tree set elements are: " +tset);
}
}

Output:

TreeSet in Java with Example 4

Note: Insert the new value in the tree set till all 6 versions of Java were allowed but after Java version 6 it was considered a null pointer exception.

Java TreeSet Example to Insert String Buffer Type of Elements

If we are depending on the default natural sorting order then the object should be comparable and homogeneous, An object is said to be comparable if its corresponding class implements the Comparable interface. In this example, the Ist condition is satisfied nut 2nd condition is not satisfied because the StringBuffer class does implement the Comparable interface.

import java.util.*;
class Person { public static void main(String args[]) { 
//creating a tree set TreeSet tset = new TreeSet(); 
//adding elements in the tree set 
tset.add(new StringBuffer("Ajay")); 
tset.add(new StringBuffer("Vjay")); 
tset.add(new StringBuffer("Amit")); 
tset.add(new StringBuffer("Sumit")); 
tset.add(new StringBuffer("Rahul")); 
//displaying elements 
System.out.println("The tree set elements are: " +tset); 
} 
}

Output:

TreeSet in Java with Example 5

Java String Class charAt() Method with Example | How to Use String charAt() in Java?

Java String Class charAt() Method with Example

The charAt() method of the String class is used to return the char value at the specified index. An index ranges from 0 to length() – 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing. If the specified index is not there then you will get StringIndexOutOfBoundExceptions: string index out of range.

Syntax: The syntax of the String class charAt() method is given below.

public char charAt(int index)

Parameter:

index- Index of the character to be returned.

Here, the index is the index of the character that you want to obtain.

Return:

The charAt() method returns the character at the specified position.

Exception:

StringIndexOutOfBoundsException - You will get this exception if the index is negative or greater than the length of the string.

Also, See:

Java String charAt() Method Example

Let’s understand the String charAt() method with an example.

class charAtExample{
public static void main(String args[]){
String str = "Javastudypoint";
char ch = str.charAt(7); //returns the char value at 7th index.
System.out.println("The value at 7th index is: " +ch);
}
}

Output:

The value at the 7th index is: d

StringIndexOutOfBoundsException with charAt() Method

The charAt() method of the String class throws StringIndexOutOfBoundsException if the specified index argument is negative or the greater of the length of the string. Let’s see the example.

Case 1: When the index argument is greater than the length of the string.

class charAtExample{
public static void main(String args[]){
String str = "Javastudypoint";
char ch = str.charAt(20); //StringIndexOutOfBoundsException
System.out.println("The value at 7th index is: " +ch);
}
}

Output:

Java String Class charAt() Method with Example 1

Case 2: When the index argument is negative. Let’s see the example.

class charAtExample{
public static void main(String args[]){
String str = "Javastudypoint";
char ch = str.charAt(-10); //StringIndexOutOfBoundsException
System.out.println("The value at -10th index is: " +ch);
}
}

Output:

Java String Class charAt() Method with Example 2

Key Points to Remember regarding Java charAt() Method

  • It takes an argument that is always int type
  • Java MethodCharAt() returns the Character as Char for the int argument given. Int value specifies the index starting at 0.
  • If the index value of the string is negative or higher than the string length then the IndexOutOfBounds Exception occurs.
  • Index Range needs to be between 0 to string_length-1.

How to Convert a String into Lowercase in Java? | Variants of toLowerCase() Method

How to Convert a String into Lowercase in Java

In the last tutorial, we have learned Java String’s lastIndexOf() method. We have learned all the four variants of this method with an example. In this tutorial, we will learn how to convert a string into a lowercase in java. We can convert all the characters of a string into lowercase by using the toLowerCase() method of the Java String Class.

Types of toLowerCase() Method

There are two variants of the toLowerCase() method in Java. In this tutorial, we will discuss all the two variants of this method.

1. toLowerCase()

This is the first variant of toLowerCase() method of string class. This method converts all the characters of a string into lowercase. This is equivalent to calling toLowerCase(Locale.getDefault).

Syntax: The syntax of the first variant of the toLowerCase() method is given below

public String toLowerCas()

Java Program to Convert String to Lowercase

class toLowerCase{
public static void main(String args[]){
String str = "String Tutorial BY BTechGeeks";
//converting all the characters of
//a string into lowecase.
System.out.println(str.toLowerCase());
}
}

Output:

string tutorial by btechgeeks

2. toLowerCase(Locale locale)

This is the second variant of the Java String toLowerCase() method. It converts all the characters in this String to lower case using the rule of the given locale.

Syntax: The syntax of the second variant of the toLowerCase() method is given below:

public String toLowerCase(Locale locale)

Also, Check:

Java String toLowerCase(Locale locale) Method Example

import java.util.Locale;
class toLowerCase{
public static void main(String args[]){
String str = "StrIng TutorIal BY JavaStudyPoint";

//Locales with the language "tr"
//for turkish and "en" for english.
Locale turkish = Locale.forLanguageTag("tr");
Locale english = Locale.forLanguageTag("en");

//converting string str into lowercase
//using turkish and english language.
String str1 = str.toLowerCase(turkish);
String str2 = str.toLowerCase(english);
System.out.println(str1);
System.out.println(str2);
}
}

Output:

How to Convert a String into Lowercase in Java

Java Control Statements – Jump, Looping, Iteration | Decision Making Statements in Java

Java Control Statements

A programming language uses control statements to control the flow of execution of a program. In Java programming, we can control the flow of execution of a program based on some conditions. In this tutorial, we will learn about the Classification of Control Statements in Java, their Syntax, Flowcharts, Example Programs, etc.

Control Statements in Java

Java control statements can be put into the following three categories: selection, iteration, and jump.

Selection Statements: The Selection statements allow your program to choose a different path of execution based on a certain condition.

Iteration Statements: The Iteration statements allow program execution to repeat one or more statements.

Jump Statements: Java Jump Statements transfer the control to other parts of the program.

Java Control Statements

Do Check:

Java Selection Statements | Decision Making Statements in Java

The Java selection statements allow your program to choose a different path of execution based on a certain condition. Java selection statements provide different type of statements such as:

  • if statement
  • if-else statement
  • nested if statement
  • if-else-if ladder statement
  • Switch case

Simple if Statement

It is the most basic one among all other java control flow statements. It determines whether a code should be executed or not depending on the condition.

Syntax:

if (condition) { 
Statement 1; //executed if condition is true
}
Statement 2; //executed irrespective of the condition

Flowchart:

If Statement Flowchart

if Condition Example Program

public class Student {  
public static void main(String[] args) {  
int x = 10;  
int y = 12;  
if(x+y > 20) {  
System.out.println("x + y is greater than                               20");  
}  
}  
  
  
}

Output:

x + y is greater than 20

if else Statement

In this statement, if the condition is met if block is executed otherwise else block is executed.

Syntax:

if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}

Flowchart:

If Else Statement Flowchart

if else Statement Example Program

public class Student {  
public static void main(String[] args) {  
int x = 10;  
int y = 12;  
if(x+y < 10) {  
System.out.println("x + y is less than      10");  
}   else {  
System.out.println("x + y is greater than 20");  
}  
}

Output:

x + y is greater than 20

Nested if Statement

An if statement present inside an if block is known as nested if block. It is similar to if.. else statement just that they are defined in another if.. else statement.

Syntax:

if (condition1) {
Statement 1; //executed if first condition is true
if (condition2) {
Statement 2; //executed if second condition is true
}
else {
Statement 3; //executed if second condition is false
}
}

Flowchart:

Nested If Statement Flowchart

Nested if Example

public class Student {  
public static void main(String[] args) {  
String address = "Delhi, India";  
  
if(address.endsWith("India")) {  
if(address.contains("Meerut")) {  
System.out.println("Your city is meerut");  
}else if(address.contains("Noida")) {  
System.out.println("Your city is noida");  
}else {  
System.out.println(address.split(",")[0]);  
}  
}else {  
System.out.println("You are not living in india");  
}  
}  
}

Output:

Delhi

Switch Statement

Switch Statement is used to execute a single statement from multiple conditions. We can use this with short, long, enum, int, byte, etc. Key points to remember while using the Switch Statement is provided below.

      • We can specify one or N number of Case Values for a Switch Expression.
      • Case Values that are duplicates are not permissible and the compiler returns a compile-time error if unique values aren’t used.
      • Case value needs to be either literal or constant and variables aren’t allowed.
      • You can use a break statement to terminate the statement sequence and it is optional. If you don’t specific it next case would be executed.

Syntax:

switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}

Flowchart:

Switch Case Flowchart

Switch Case Example Program

public class Student implements Cloneable {  
public static void main(String[] args) {  
int num = 2;  
switch (num){  
case 0:  
System.out.println("number is 0");  
break;  
case 1:  
System.out.println("number is 1");  
break;  
default:  
System.out.println(num);  
}  
}  
}

Output:

2

if-else-if Ladder

In this case, the user can decide among multiple options. If Statements are Executed from top down. If any one of the conditions controlling the if is true then the statement associated with it will be executed and the rest of the ladder is bypassed. If no condition is true then the final else statement is executed.

Syntax:

if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;

Flowchart:

if else if Ladder Flowchart

if-else-if Ladder Example

// Java program to illustrate if-else-if ladder
class ifelseifDemo
{
public static void main(String args[])
{
int i = 20;

if (i == 10)
System.out.println("i is 10");
else if (i == 15)
System.out.println("i is 15");
else if (i == 20)
System.out.println("i is 20");
else
System.out.println("i is not present");
}
}

Output:

i is 20

Iteration Statements in Java | Looping Statements in Java

Java Iteration statements allow program execution to repeat one or more statements. Java Iteration statements provide different type of statements such as:

      • While loop
      • Do While loop
      • For loop

While Loop

It is known as the most common loop used in programming languages. While Loop evaluates a particular condition. If the condition is true then the code is executed or else the process is continued till the specific condition is false.

The Condition you specify in the while loop needs to be a Boolean Expression. You will get an error if you use int or string.

Syntax:

while (condition)
{
statementOne;
}

Flowchart:

While Loop Flowchart

While Loop Example Program

public class whileTest
{
public static void main(String args[])
{
int i = 5;
while (i <= 15)
{
System.out.println(i);
i = i+2;
}
}
}

Output:

5
7
9
11
13
15

Do While Loop

Do While Loop is the same as While Loop. The only difference is that the condition in the do-while loop is executed after the execution of the body. That is the loop is executed at least once.

Syntax:

do{
//code to be executed
}while(condition);

Flowchart:

Do While Flowchart

Do While Loop Example Program

public class Main 
{ 
public static void main(String args[]) 
{ 
int i = 20; 
do 
{ 
System.out.println(i); 
i = i+1; 
} while (i <= 20); 
} 
}

Output:

20

For Loop

We use For Loop in Java to iterate and evaluate a code multiple times. If you are aware of the number of iterations you can use a for loop.

Syntax:

for (initialization; condition; increment/decrement)
{
statement;
}

Flowchart:

For Loop Flowchart

For Loop Java Control Statements Example

public class forLoop
{
public static void main(String args[])
{
for (int i = 1; i <= 10; i++)
System.out.println(i);
}
}

Output:

5
6
7
8
9
10

Jump Statements in Java | Branching Statements

Branching Statements are used to jump from one statement to another statement. Java Jump statements transfer the control to other parts of the program. java Jump statements provide different type of statements such as:

      • break statement
      • continue statement
      • return statement

Break

In Java Break Statement is used to terminate a sequence in a switch statement or to exit a loop. It can also be used as a civilized form of goto.

We can use the break for immediate termination of a loop, bypassing the conditional expression and any code leftover in the body of the loop. If you use to break in a set of nested loops will break out of the innermost loop.

Syntax:

break; or break <label>;

Flowchart:

Break Flowchart

Break Statement Usage Example Program

public class BreakExample {  
  
public static void main(String[] args) {  
// TODO Auto-generated method stub  
for(int i = 0; i<= 10; i++) {  
System.out.println(i);  
if(i==6) {  
break;  
}  
}  
}  
}

Output:

0
1
2
3
4
5
6

Continue

In order to jump to the next iteration of the loop we use the continue statement. This Statement continues the current flow of the program and skips a part of the code at the given condition.

Syntax:

continue; or continue<label>;

Flowchart:

Continue Flowchart

Continue Statement Usage Example Program

// Java program to illustrate using
// continue in an if statement
class ContinueDemo
{
    public static void main(String args[])
    {
        for (int i = 0; i < 10; i++)
        {
            // If the number is even
            // skip and continue
            if (i%2 == 0)
                continue;
  
            // If number is odd, print it
            System.out.print(i + " ");
        }
    }
}

Output:

1 3 5 7 9

Return

We use a return statement to explicitly return from a method. It causes a program control to transfer back to the caller of the method.

Return Statement Example Program

// Java program to illustrate using return
class Return
{
    public static void main(String args[])
    {
        boolean t = true;
        System.out.println("Before the return.");
      
        if (t)
            return;
  
        // Compiler will bypass every statement 
        // after return
        System.out.println("This won't execute.");
    }
}

Output:

Before the return.

 

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

Servlet API in Java | Interfaces and Classes in java.servlet Package and javax.servlet.http package

Servlet API in Java

Servlet uses classes and interfaces from two packages: javax.servlet and javax.servlet.http.They constitute servlet API. Keep in mind that these packages are not part of the Core java packages. Instead, they are a standard extension. Therefore, they are not included in the Java software development kit. you must download tomcat to obtain their functionality.

Every Servlets must implement the javax.servlet.Servlet interface. Most servlet implements this interface by extending one of two special classes javax.servlet.GenericServlet or javax.servlet.http.HttpServlet.

A GenericServlet class provides the implementation of the basic life cycle method of the servlet. The service() method of GenericServlet class accepts two parameters: a request object and a response object. The request object is used to read the data from a client request and the response object is used to write data to a client request.

In contrast, an HTTP servlet usually does not override the service() method. Instead, it overrides the doGet() method to handle the GET request and the doPost() method to handle the post requests. An HTTP servlet can override either or both of these methods, depending on the type of requests it needs to handle. An HTTP servlet can override doPut() and delete() methods to handle PUT and DELETE requests respectively. However,HTTP servlet generally don’t touch doTrace() or doOption().

java.servlet Package

java.Servlet Package has several interfaces and classes that provide the framework in which servlet operates. Classes and interfaces within the package are protocol-independent.

The ServletRequest and ServletResponse classes in javax.servlet is used to read the data from a client request and write the data to client response, While HttpServletRequest and HttpServletResponse in javax.Servlet.http package also contains an HttpSession class that provides built-in session tracking functionality and a cookie class that allows you to quickly set up and process HTTP cookies.

javax.servlet Package

Interfaces in javax.servlet package

There are various interfaces in javax.servlet package and they are listed in the following fashion

  1. servlet
  2. servletRequest
  3. servletResponse
  4. servletConfig
  5. servletContent
  6. servletThreadModel
  7. RequestDispatcher
  8. Filter
  9. Filterchain
  10. FilterConfig

Also, Refer: What is Servlet in Java?

Classes in javax.servlet package

There are many classes in javax.servlet package and they are listed as follows

  1. GenericServlet
  2. ServletInputStream
  3. ServletOutputStream
  4. servletRequestWrapper
  5. servletResponseWrapper
  6. ServletException
  7. unavailabale Exception
  8. ServletRequestEvent
  9. servletContentEvent
  10. servletRequestAttributeEvent

Interfaces in javax.servlet.http package

There are several interfaces in javax.servelt.http package and they are in the below fashion

  1. HttpServletRequest
  2. HttpServletResponse
  3. HttpSession
  4. HttpSessionContext
  5. HttpSessionAttributeLIstner
  6. HttpSessionActivationListner
  7. HttpSessionBindingListner

Classes in javax.servlet.http package

There are many classes in javax.servlet.http package and they are in the following way.

  1. HttpServlet
  2. cookie
  3. HttpServletRequestWrapper HttpServletResponseWrapper
  4. HttpSessionEvent
  5. HttpSessionBindingEvent
  6. Httputils