Static keyword in Java

Static keyword can be used with

  1. Variables
  2. Methods
  3. Blocks
  4. Static inner class

lets see them one by one

Static Variable

Static variable can be create by adding static keyword in front of variable.

below count is static variable.

A static variable is shared among all objects of class.

Each class have their own instance variable but they all share static variables.

Static variable is also know as class variable because it belongs to class not specific to any object.

In diagram memory allocation for different variables are shown.

It also represents static variables are stored in MetaSpace( Java8 Onward ) from where all objects are sharing it.

Why Static variable required?

A static variable is shared amount all objects of class. So to share information amount objects static variable can used.

2. Static Method

To create a method static add static keyword before to method.

<access-specifier> static <return-type> <method-name>{
statements;
}

A static method can access only static fields and member functions.

It can not access not static fields and methods.

Why Static method can not access not static variables?

Static variable initialize when a class in loaded in JVM

Instance variable is initialized when object is created.

At the time when static method called Instance variables they are not created. Thats why static method can not access instance variable.

3. Static Block

A block is set of statements inside opening closing brackets {….}.

A static block is a block which contains static in front.

Why Static block is needed?

A static block can be used to initialize some values that a program required during load time or in throughout the program.

4. Static Inner class

A class inside a class in called nested class java supports both static and non static nested classes.

A static nested class is nested class with preceded static keyword.

Output

Java code for inserting data into database

Java code for inserting data into database is done using Jdbc(Java Database connectivity).

Jdbc is a API to connect java program to various databases like MySql, Oracle, MSAccess etc.

Here Step by step tutorial to insert data from java to database.

Here MySql or MariaDB database is used for this purpose.

So to insert data in database we need to set in two end

  1. Create Database and table
  2. Write Java (JDBC) code

Lets see them one by one

Create Database and table

Open phpMyAdmin click on home icon or left side

Click to SQL on middle menu.

Write create query given below

Copy and insert above code in SQL query box

create table query

After click on go button it will show below box if query is successfully executed.

created table query

You can see structure of table. which show below output.

table structure

Now table is created.

Write JDBC Code

Steps for JDBC is as below

  1. import JDBC classes
  2. Load and register JDBC Driver
  3. Open Database connection
  4. Create Statement object to pass query
  5. Execute Statement
  6. Get the result
  7. Close connections

File Structure of Program

file explorer

Importing JDBC classes

Load and register JDBC Driver

Here Class.forName() is used to load and register driver

Open Database connection

Create Statement object to pass query

Execute Statement and get result

Here ps.executeUpdate() execute query and get no of row affected.

Close connections

pre class=”theme:eclipse font:verdana toolbar:2 show-plain:3 lang:java decode:true”> con.close();

Insert a Student Object into database

Before proceeding add mysql-connector-java-5.1.14-bin.jar to your class path.

All file details are as below.

Student.java

Student object that contains basic properties of students like id, rollNo, name, branch,section, emailId,dob, mobileNo, addDate.

ConnectionFactory .java

This file is responsible to connect with MySql database, after getting connection this will return connection object

StudentJDBCInsert.java

This class will get connection from ConnectionFactory and insert data in database and return no of rows inserted in database.

Output

Insert multiple Student Objects into database

efficient way to insert multiple records in database is using batch processing

Steps to store multiple records in database

  1. Create multiple objects
  2. Add all to a List
  3. Add list item to batch
  4. executeBatch()

StudnetJDBCBatchInsert.java

this program will insert batch data to MySql database

Output

MySql Admin view

data in MySql table

Reading Data using JDBC

StudentJDBCRead .java

This program read student records from database table and show in java console.

Output

Download above code fron github

Employee details program in java

Employee detail program in java as as below.

Here two classes are created

  1. Employee class
  2. EmployeeMain class

Details of these two classes are as below

Employee.java

This class contains various field of employees like id, fname, lname, address etc.

Its corresponding getter and setter method is created in program.

Employee.java is a java bean and it good example of java encapsulation.

fields of Employee object can not be directly accessible outside the class to access this we need getter and setter methods.

Default and parameterized constructor are created to initialize employee object.

toString() of Object class is overridden to convert object to String.

Some fields like hra, providentFund and grossSalary are calculated from basicSalary.

So user provides only basicSalary value and other derived values are calculated based on it.

Two different methods are used to initialize values(Parameterised constructor and setter methods).

So calculation of derived values are done inside constructor and in setter method.

Providing addDate value is optional for user it user does not provide this value constructor or setter method does this.

EmployeeMain.java

This class contain public static void main() (java main method) inside main tho objects of Employee class is created.

First object is created using parameterized constructor and object’s value is printer by overriding the toString() of Object class.

Second object is created using default constructor of employee and values are assigned using setter methods of class.

To print value of object getter method is used. Insted of using getter method toString() can also be used.

Its up to used which method he wants to use to set values in object.

Result of above program is

If any one want to change value of any field then appropriate setter method needs to called

like want to update lname of employee object then use

employee.setLname("Verma");

this will assign new value to lname.

Learn database operations with employee details

Java program to swap two numbers

1 Swapping two numbers using third variable

Output

2. Swapping two numbers without using third variable

Output

3. Swapping two numbers in a single line using addition and subtraction

Output

4. Swapping two numbers in a single line using multiplication and division

Output

5. Swapping two numbers using multiplication and division

Here numbers must be non zero

Output

6. Swapping two numbers using XOR operator

above operation can also be written as

Output

Output

Write a java program to reverse a string

Using StringBuffer or StringBuilder class

Output

Using Loops(Iteration)

Copy and reverse the string

Here getting input from user

converted into character array using toCharArray() of String

Initialize the other character array with same length as c character array.

Loop char array c in reverse order and r in forward order.

this will copy character array c in reverse order to r.

converted char array r to String

print both character array

Output

Even or odd program in java

The number which is divisible by 2 is known as even number and the number which is not divisible by 2 is odd number.

in programming we use % operator to check divisibility.

The % operator returns the remainder of division. If a number is completely divisible its remainder is 0.

So any number is completely divisible by 2 then its remainder is zero.

4%2,20%2,60%2 all return zero.

5%2,45%2,51%2 its remainder is non zero.

Even or odd number program in java using if else

Scanner class is used to take input from standard input stream that is keyboard.

Then perform modulo operation with 2 if remainder is 0 than a even number else number is odd.

Output

Even or odd number program in java using switch case

switch(number%2) returns 0 or non zero value. So there should be two case statement case 0 for even numbers and default for non zero numbers.

Output

Even or odd number program in java using ternary operator

Output

String reverse program in java

String Reverse using StringBuilder

Leap Year Program in Java

A Leap Year is a year which has 366 days. This year February is of 29 days. Leap years occurs in every four years.

A leap year has following constraints.

We can check in programming as below

  • A year is divisible by 400 then it is a leap year
  • A year is divisible by 4 and not divisible by 100 then the year is leap year

See another program

MySql Jdbc Operations for beginner

Database connection with java is one of the essential feature of java, In java to connect with database we use java database connectivity(JDBC) programs.

JDBC is an Application Program Interface(API) that is used to interact with database and java program in database independent way.

So JDBC (full form Java Database Connectivity) code to interact with mysql, oracle database and with other database.

Here we used jdbc with mysql to connect it we need a mysql jdbc driver to connect mysql with java.

Here we will see a java jdbc project to perform all basic operations involved in Database interaction.

Using Employee details program in java using jdbc opetations.

Setting Up Project

JDBC project setup is in two part

  • create database
  • Write Java, Jdbc codes

Creating database

  • Create a database user name with password.
  • given all privileges to user.
  • created database and table for employee.

Above all details are set in following script.

Run this script before running java jdbc program

Writing Java Jdbc Code

  • Create Java Bean
  • Creating Main class (Execution starts from here)
  • Create Action class
  • Create DAO class

Java Bean

A Java Bean is a simple java class, that holds all properties, getter setter methods and constructors of the class.

Java Bean for Employee class is given below

Create Main Class

Below is main class for running all java jdbc examples

Here you find various examples like to insert in table, to update table ,delete a recored from mysql table and select a specific or all record from table.

To run below code see all actions and operations in below table

Sr No Operation and code Action
1 ADD (1) Add Employee records in database should be initialize only once. First time after creating database
2 UPDATE (2) Update a record in table, based on primary key id
3 DELETE (3) Insert a new record to table and delete it from database
4 FETCH BY ID (4) Fetch a record from table based on id
5 FETCH BY EMAIL (5) Fetch a record from table based on email
6 FETCH BY MOBILE NO (6) Fetch a record from table based on mobile number
7 SEARCH BY NAME (7) Fetch records from table based on Name
8 FETCH BY CITY (8) Fetch records from table based on city name
9 FETCH BY SALARY RANGE (9) Fetch records from table based on Salary Range
10 FETCH BY DOB (10) Fetch records from table based on date of birth
11 FETCH BY DOJ RANGE (11) Fetch records from table based on Date of Joining Range
12 FETCH ALL (12) Fetch all records from table
13 EXIT (0) EXIT FROM ALL OPERATION

Create Action Class

Above class will call method of below action class

Create DAO class

The above action class will call to below DAO class method

Here All JDBC Prepared statement are used to interact with mysql

Various JDBC operations used here are

  • Insert
  • Update
  • Delete
  • FetchById
  • FetchByEmailId
  • FetchByMobileNo
  • SearchByName
  • FetchByCity
  • FetchBySalaryRange
  • FetchByDob
  • FetchByDojRange
  • FetchAll

Download this Java Project with source code for github

How to Convert Java Object to/from JSON using GSON

Gson is Java JSON library that is used to convert Java object to/from JSON

GSON is developed by google.

GSON Maven dependency is as below

You can also download Gson Jar from here

Gson jar contains API to work with JSON

GOal of GSON is provide simple methods to convert and receive JSON, Provides extensive support for Generics, support complex objects

GSON provides simple functions to convert in to JSON it has toJSON() and from JSON to Java Object it has fromJSON()

Creating JSON Object

1. Gson gson=new Gson();
2. GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson1 = gsonBuilder.create();

Here Gson() is no argument constructor that will create Gson object.

Using GsonBuilder by calling create() we get Gson object

Converting Java to JSON value