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

  • One Super class and one sub class
  • Sub class inherits the features of super class

java single inheritance
Fig:java single inheritance

Write a program for single level inheritance.

Multi level Inheritance

In multi level inheritance inheritance exists in multiple level.

  • One Super Class
  • It has a child class
  • Child class has a child class

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

Multilevel Inheritance

program for Multi level inheritance.

Result

Hierarchical Inheritance

java hierarchical inheritance
java hierarchical inheritance

Hybrid  Inheritance

java Hybrid  Inheritance
java Hybrid Inheritance

Result

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

Write a program for Hierarchical Inheritance.

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

StringTokenizer in java- Constructor, method with example

1 What is StringTokenizer?

A StringTokenizer is a class in Java. It is used to divide strings in form of token based on some delimiters.

It is defined in java.util.stringtokenizer

2 StringTokenizer Constructors

Sr NoConstructor and Description
1StringTokenizer(String str) Construct a string tokenizer for given string
2StringTokenizer(String str, String delim) Construct a string tokenizer for given string and generate tokens based on delimiters
3StringTokenizer(String str, String delim, boolean returnDelims) Construct a string tokenizer for given string and generate tokens based on delimiters the returnDelims specify whether to include delim in token or not

Creating StringTokenizer object using first constructor

Creating StringTokenizer object using second constructor

3 StringTokenizer methods

A Java StringTokenizer countTokens() Method

This method is used to count the number of the tokens from current token position to the last token

Signature

public int countTokens()

Parameters

NA

Return

Return the number of tokens available from specific token position

Example

Initially token position was before the first word “Arise” so on calling st.countToken() returns 11.
on calling st.nextToken() position of token is incresed by one and it is on “Arise” from this position new token count is 10.

B Java StringTokenizer hasMoreElements() Method

This method checks for next token in StringTokenizer if the token exists then return true else return false. Work similar as
hasMoreToken()

Parameters

NA

Return

Return true if next token exists else return false

Example

Result

At starting object st is pointing before the first word(Java). on calling st.hasMoreElements it is checkin that the first word java is there so it is returning true.

C Java StringTokenizer hasMoreToken() Method

This method is used with StringTokenizer object to check whether there is more token or not
For example
StringTokenizer st=new StringTokenizer(“Hello Friends”);
There are two tokens Hello and Friends. At starting hasMoreToken() point before the Hello Token so calling this method will return true at first.
To get next token we use nextToken().
After getting token Friends, again calling hasMoreToken() it return false.

Signature

public boolean hasMoreToken()

Parameters

NA

Return

Return true if there is more token else return false

Example

Result

St object is pointing before the Hello so calling st.hasMoreTokens() will always return true.

D Java StringTokenizer nextElement() Method

This method returns next token from stringTokenizer object this method work same as nextToken() only the return type of this method is object instead of String

Signature

public Object nextElement()

Parameters

NA

Return

Return next token from StringTokenizer object

Throws

NoSuchElementException – If there is no token in StringTokenizer object then it throw this exception

Example

Lets see how to tokenize a string in java

Another Example

E Java StringTokenizer nextToken() Method

This method returns next token from stringTokenizer object

Signature

public String nextToken()

Parameters

NA

Return

Return next token from StringTokenizer object

Throws

NoSuchElementException – If there is no token in StringTokenizer object then it throw this exception

Example

Result

Primitive Data Types in Java

Primitive data types are primary and basic data types in java.

In Java there are 8 primitive data types.

List of primitive datatypes in java is as follows

  1. byte
  2. short
  3. int
  4. long
  5. float
  6. double
  7. char
  8. boolean

Details of all data types are below.

1 Java Integer Data Type

There are four integer data types (byte, short, int and long) in java that can hold integer values.

All four data types with default value size and minimum and maximum value range that can store  are shown below

TypeDefaultSizeMin Max Value
byte08 bits-27, 27 -1
short016 bits-215, 215 -1
int032 bits-231, 231 -1
long064 bits-263, 263 -1

A byte data type in Java

  1. Byte stores 8 bits signed integer value.
  2. byte stores data in range of -128 to 127.
  3. Default value of byte is 0.
  4. Byte data type can use where we have to save memory during data storage.

B short Data type in java

  1. short stores 16 bits signed integer value.
  2. short stores data in range of -32768 to 32767.
  3. Default value of short is 0.
  4. Short data type can use where we have to save memory during data storage.

C int Data type in java

  1. int stores 32 bits signed and unsigned integer value.
  2. int stores data in range of -2^31 to -2^31-1 for signed integer and 0 to 2^32-1 for unsigned integer.
  3. Default value of short is 0.
  4. Int data type can used to represent normal integer values.

D long Data type in java

  1. long stores 64 bits signed and unsigned long integer value.
  2. long stores data in range of -2^63 to -2^63-1 for signed integer and 0 to 2^64-1 for unsigned integer.
  3. Default value of short is 0.
  4. long data type can used to represent higher integer values.

Lets see a simple program to initialize and print integer data type in java.

Output

2 Float and Double Data Types

Floating point value (example  11.23, 333.3330 etc. ) can be stored in data type float and double.

Small floating value can be stored in float and large floating stored in double. 

java data types float and double contains real values.

TypeDefaultSize
float0.032 bits
double0.064 bits

A float data type in java

  1. float stores decimal values in 32 bits, represents data in single-precision IEEE754 floating point.
  2. floats stores fractional values in range of 3.4e-038 to 3.4e+038.
  3. Default value of float is 0.0.
  4. float data type can used to represent fractional values.

B double data type in java

  1. double stores decimal values in 64 bits, represents data in double-precision IEEE754 floating point.
  2. double stores fractional values in range of 1.7e-308 to 1.7e+308.
  3. Default value of double is 0.0.
  4. double data type can used to represent fractional values with more precision.

Write a program to demonstrate use of float data types.

Output

3 Java Character Data Type

Character data ( example ‘a’ , ‘b’ , ‘f’, ….. etc. ) is stored in “char” data type.

TypeDefaultSize
char\u000016 bits

B char data type in java

  1. char stores single 16 bit unicode character
  2. double stores fractional values in range of 1.7e-308 to 1.7e+308.
  3. Default value of double is 0.0.
  4. double data type can used to represent fractional values with more precision.

Write a program to demonstrate char data types.

Result

Program to print character using ASCII value

Result

4 Java Boolean Data Type

boolean data type in java store the true and false value.

By default value of boolean data type is false.

TypeDefaultSize
booleanfalse1 bit

Write a program to demonstrate boolean data types.

Result

Prime number program in java using while loop

1 What is a Prime Number

A prime number is whole number that has only two factor 1 and number itself.

For example 23 is a prime number, because it has only two factor 1 and 23.

Learn More about

  1. While Loop
  2. If Else Statements

2 Java program to check prime number

Java program to find prime number can be divided in following steps.

  1. Take a number
  2. start a loop from 2 to number/2 times
  3. check whether a number is divisible in between
  4. if divisible then increase count variable by one and break loop
  5. after loop check if count variable in zero then number is prime otherwise not a prime number.

Prime no in java can be checked very easily with above steps.

Output

3 Program to check prime number in java using java method

We have created a java static method to check prime number in java

This is another way to check Prime no program in java.

Here a method is created and specified the work to check prime no in this static method.

Output

4 Program to check prime numbers in Java with in range

To find prime numbers in java program we can use following source code.

Prime numbers program in java Takes two integer numbers for range and generate prime numbers between range.

java program for prime number check each number and print if it is prime.

Output

print prime numbers in java in specified range also checks that number2 must be greater than number1.

4 Java Method check prime numbers in range

Prime number java program in range takes two integer range and check each number is prime or not if it is prime then prime number method returns list of prime numbers to calling method.

java program for prime numbers code is same as above code we have only created function by using that code.

Output

In above programs we have seen different java program to print prime numbers.

Hope you learned easy way to how to check prime number in java.

Applet Life Cycle in Java with Example

Applet in Java

Applet in Java is a special Java program that are primarily used in a internet programming.

Applet Life Cycle is very important to know in Java Applet Programming. 

As we have already seen how to run program from command prompt, but there were no GUI.

To provide Graphical user interface(GUI) Java Applet is used.

Applet program runs on a web browser at client side. Applet program are used to make the web site more dynamic.

1 Applet Life Cycle Stages

When the applet program is loaded is passes through several stages:

Java Applet Life Cycle
Java Applet Life Cycle

A Applet Born State

Also known as initialization state.  

It is the first state of applet lifecycle.

Applet enters in a born/ initialization state when it is first loaded.  

Applet moves in a born state when init() method of Applet class executes.

Applet initialization occurs once in a  applet lifecycle.

Inside the init() method we initialize all the variables.

Syntax of init() method in Java Applet

B Applet Running State

  Applet enters in a running state from born state when a start() method of Applet class executes.  

Running sates call automatically when the initialization phase completes. 

Applet also comes in a running state from idle state when idle applet again get processor.

Running sates call automatically when the initialization phase completes. 

Applet also comes in a running state from idle state when idle applet again get processor.

Syntax of start()              

C Applet Idle State

A running appletenters in a idle sate from running state when execution of start complete.

In a another words when we leave the page of running applet then automatically it enters in a idle sate from running state.

Applet moves in idle state when  stop() method executes and it moves idle to running state when again start() calls.

Syntax of stop()               

D Applet Dead State

  An applet is moved to dead state when we quit the web browser.  When applet moves in a dead state it removed from memory. 

The Applet will be terminate when destroy () method calls. In a applet lifecycle, applet terminates/destroys ones.

Syntax of destroy()        

E Applet Display State

The Display state executes immediately after when applet enters in a running state.

In this state we display the information on the output screen using paint() method.

2 Applet Life Cycle in Java Method Example

Lets see one program to demonstrate the life cycle of applet.

Compile and Run

>javac AppletLifeCycle.java
>appletviewer AppletLifeCycle.java

Applet Life Cycle in Java Example
Fig: Java Applet Life Cycle Example

Output At Console

On running Applet It will print first 3 line from output.

On closing applet it will call stop and destroy method.

init() method can be used to initialize various values and objects that are going to use in program.

Similarly to release resource we can use destroy().

Example: Write a program to read file and show in java applet.

Output

Fig: Reading File in showing in applet

Simple Calculator in Java Applet

Diamond pattern in java

diamond pattern in java is one of the interesting pattern program for beginner and intermediate learners of programming.

If you see diamond pattern you will see it is combination of two triangle pattern that is upper and lower triangle.

Here we will see different diamond pattern programs in java.

We will start with basic pattern in java

1. Triangle Pattern

Let first see to draw upper pattern.

  • Get No of rows to print
  • loop to number or rows using outer loop for (int row = 1; row <= rows; row++)
  • print odd numbers of * in each column for (int col = 1; col <= 2 * row - 1; col++)
  • Go to next Line and repeat step 1 to 3

Output

This will Print above pattern.

But we require pattern should be at center.

2. Triangle Pattern at center

Lets modify above program and add appropriate space so that we can print center triangle.

  • Get No of rows to print
  • loop to number or rows using outer loop for (int row = 1; row <= rows; row++)
  • Print number of spaces using this loop for (int col = 1; col <= rows-row; col++)
  • print odd numbers of * in each column for (int col = 1; col <= 2 * row - 1; col++)
  • Go to next line and repeat step 1-3

Output

This will print correct start pattern.

3. Lower Triangle Pattern

Lets see another program to print lower triangle program.

This program is similar to upper triangle only we have to reverse the outer loop

Output

This is printing a good lower start triangle.

4. Diamond Pattern

Lets combine both upper and lower star triangle to make diamond.

Our AIM is to print diamond pattern of stars.

Lets see java program to print diamond pattern of stars .

Here Upper triangle is as it is only in lower triangle we started outer loop from one less position that is row=rows-1

for (int row = rows - 1; row > 0; row--)

Output

After combining upper and lower triangle we got our diamond pattern.

5. Diamond Pattern with variation

As we know the concept of creating upper and lower triangle pattern.

we can replace * with any numbers les dive in with combining other symbols.

Output

Let combine other symbols.

Output

6. Diamond Pattern altering column

6.1 Altering Lower Triangle columns

Here upper triangle printing one time less then upper triangle.

Output

6.2 Altering Complete diamond pattern

Here two symbols are changed alternately in lower triangle.

Output

7. Diamond Pattern with row alteration

7.1 Altering lower triangle

Output

7.2 Altering all triangle row

Output