Spring MVC with MySQL and Junit - Finding Employees Based on Location
Last Updated :
23 Jul, 2025
In real-world scenarios, organizations are existing in different localities. Employees are available in many locations. Sometimes they work in different 2 locations i.e. for a few days, they work on location 1 and for a few other days, they work on location 2. Let's simulate this scenario via MySQL queries and prepare a Spring MVC application that interacts with MySQL and get the required details. And also let us see JUNIT test cases as well.
Required MySQL Queries:
DROP DATABASE IF EXISTS test;
CREATE DATABASE test;
USE test;
DROP TABLE test.employeesdetails;
CREATE TABLE `employeesdetails` (
`id` int(6) unsigned NOT NULL,
`Name` varchar(50) DEFAULT NULL,
`AvailableDays` varchar(200) DEFAULT NULL,
`location` varchar(50) DEFAULT NULL,
`qualification` varchar(20) DEFAULT NULL,
`experience` int(11) DEFAULT NULL,
`gender` varchar(10) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;
INSERT INTO `test`.`employeesdetails`
(`id`,`Name`,`AvailableDays`,`location`,`qualification`,
`experience`,`gender`) VALUES
(1,'EmployeeA','Monday,Tuesday,Friday','Location1','BE',5,'Female');
INSERT INTO `test`.`employeesdetails`
(`id`,`Name`,`AvailableDays`,`location`,`qualification`,
`experience`,`gender`) VALUES
(2,'EmployeeB','Monday,Wednesday,Friday','Location1','MCA',3,'Female');
INSERT INTO `test`.`employeesdetails`
(`id`,`Name`,`AvailableDays`,`location`,`qualification`,
`experience`,`gender`) VALUES
(3,'EmployeeC', 'Wednesday,Thursday','Location2','BE',5,'Female');
INSERT INTO `test`.`employeesdetails`
(`id`,`Name`,`AvailableDays`,`location`,`qualification`,
`experience`,`gender`) VALUES
(4,'Employees','Saturday,Sunday','Location2','MBA',4,'Male');
INSERT INTO `test`.`employeesdetails`
(`id`,`Name`,`AvailableDays`,`location`,`qualification`,
`experience`,`gender`) VALUES
(5,'EmployeeE','Tuesday,Thursday','Location2','MCA',3,'Female');
INSERT INTO `test`.`employeesdetails`
(`id`,`Name`,`AvailableDays`,`location`,`qualification`,
`experience`,`gender`) VALUES
(6,'EmployeeA','Wednesday,Thursday','Location2','BE',5,'Female');
SELECT * FROM test.employeesdetails;
Output of test.employeesdetails:
With this setup, let us start the Spring MVC project that interacts with MySQL and produce the details upon our queries
Implementation
Project Structure:
This is a Maven-driven project. Let's start with
pom.xml
XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.employees</groupId>
<artifactId>SpringMVCFindEmployee</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>SpringMVCFindEmployee Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<failOnMissingWebXml>false</failOnMissingWebXml>
<spring-version>5.1.0.RELEASE</spring-version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jasper -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jasper</artifactId>
<version>9.0.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring-version}</version>
</dependency>
</dependencies>
<build>
<finalName>SpringMVCFindEmployee</finalName>
<sourceDirectory>src/main/java</sourceDirectory>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<!-- This should be added to overcome Could not initialize
class org.apache.maven.plugin.war.util.WebappStructureSerializer -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.2</version>
</plugin>
</plugins>
</build>
</project>
Let's see some important java files.
Bean class
Employee.java
Java
public class Employee {
// All instance variables should
// match with the columns present
// in MySQL test.employeedetails table
private int id;
private String name;
private float salary;
private String availableDays;
private String location;
private String qualification;
private int experience;
private String gender;
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getQualification() {
return qualification;
}
public void setQualification(String qualification) {
this.qualification = qualification;
}
public int getExperience() {
return experience;
}
public void setExperience(int experience) {
this.experience = experience;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
public String getAvailableDays() {
return availableDays;
}
public void setAvailableDays(String availableDays) {
this.availableDays = availableDays;
}
}
EmployeeController.java
Java
import com.employees.beans.Employee;
import com.employees.dao.EmployeeDao;
import java.sql.SQLException;
import java.util.StringTokenizer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
@Controller
@SessionAttributes("employee")
public class EmployeeController {
@Autowired
EmployeeDao dao;
@Autowired public EmployeeController(EmployeeDao dao)
{
this.dao = dao;
}
@ModelAttribute("employee")
public Employee getEmployee()
{
return new Employee();
}
// for searchform
@RequestMapping("/employeesearchform")
public String searchform(Model m)
{
m.addAttribute("command", new Employee());
return "employeesearchform";
}
// It provides search of employees in model object
@RequestMapping(value = "/searchEmployee",
method = RequestMethod.POST)
public ModelAndView
searchEmployee(@ModelAttribute("employee")
Employee employee)
{
ModelAndView mav = null;
Employee employee1;
try {
employee1 = dao.getEmployeesByNameAndLocation(
employee.getName(), employee.getLocation());
mav = new ModelAndView("welcome");
if (null != employee1) {
System.out.println(
employee1.getId() + "..."
+ employee1.getName() + ".."
+ employee1.getAvailableDays()
+ "..chosen location.."
+ employee.getLocation());
StringTokenizer st = new StringTokenizer(
employee1.getAvailableDays(), ",");
boolean isAvailable = false;
while (st.hasMoreTokens()) {
// System.out.println(st.nextToken());
// if
// (st.nextToken().equalsIgnoreCase(employee.getAvailableDays()))
// {
isAvailable = true;
break;
//}
}
mav.addObject("firstname",
employee1.getName());
if (isAvailable) {
mav.addObject("availability",
"Available on");
}
else {
mav.addObject("availability",
"Not Available on");
}
mav.addObject("day",
employee1.getAvailableDays());
mav.addObject("location",
employee.getLocation());
}
else {
mav.addObject("firstname",
employee.getName());
mav.addObject("availability",
"Not Available ");
mav.addObject("location",
employee.getLocation());
}
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mav;
}
}
EmployeeDao.java
Java
import com.employees.beans.Employee;
import java.sql.SQLException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
public class EmployeeDao {
// We can straight away write SQL queries related to
// MySQL as we are using JdbcTemplate
JdbcTemplate template;
public void setTemplate(JdbcTemplate template)
{
this.template = template;
}
public Employee
getEmployeesByNameAndLocation(String employeeName,
String locationName)
throws SQLException
{
String sql
= "select * from employeesdetails where name=? and location = ?";
return template.queryForObject(
sql,
new Object[] { employeeName, locationName },
new BeanPropertyRowMapper<Employee>(
Employee.class));
}
public Employee
getEmployeesByGender(String gender,
String availabledays)
throws SQLException
{
String sql
= "select * from employeesdetails where gender=? and availabledays = ?";
return template.queryForObject(
sql, new Object[] { gender, availabledays },
new BeanPropertyRowMapper<Employee>(
Employee.class));
}
public Employee
getEmployeesByQualification(String qualification,
String availabledays)
throws SQLException
{
String sql
= "select * from employeesdetails where qualification=? and availabledays = ?";
return template.queryForObject(
sql,
new Object[] { qualification, availabledays },
new BeanPropertyRowMapper<Employee>(
Employee.class));
}
public Employee
getEmployeesByExperience(int experienceInYears)
throws SQLException
{
String sql
= "select * from employeesdetails where experience=?";
return template.queryForObject(
sql, new Object[] { experienceInYears },
new BeanPropertyRowMapper<Employee>(
Employee.class));
}
}
We need to have an important file called spring-servlet.xml. This will have the MySQL connectivity information
XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans/"
xmlns:context="http://www.springframework.org/schema/context/"
xmlns:mvc="http://www.springframework.org/schema/mvc/"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="
http://www.springframework.org/schema/beans/
http://www.springframework.org/schema/beans//spring-beans.xsd
http://www.springframework.org/schema/context/
http://www.springframework.org/schema/context//spring-context.xsd
http://www.springframework.org/schema/mvc/
http://www.springframework.org/schema/mvc//spring-mvc.xsd">
<context:component-scan base-package="com.employees.controllers" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
<!-- As we are using test database, it is given as test here
Modify it according to your database name useSSL=false
is required to overcome SSL errors -->
<property name="url" value="jdbc:mysql://localhost:3306/test?useSSL=false" />
<property name="username" value="root" />
<property name="password" value="*****" />
<!--Specify correct password here -->
</bean>
<bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds" />
</bean>
<bean id="dao" class="com.employees.dao.EmployeeDao">
<property name="template" ref="jt" />
</bean>
</beans>
Ok, now let us use JSP pages to search the employees by using the Spring MVC project and the available data present in the MySQL
index.jsp
Java
// Beautify the code if required,
// This will provide a hyperlink and
// it will go to the employeesearchform.jsp
<center> <a href="employeesearchform">Search Employees By Location</a></center>
employeesearchform.jsp
HTML
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://www.oracle.com/technetwork/java/index.html" prefix="c"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Search Employees</title>
</head>
<body>
<h1>Search Employees</h1>
<form:form method="post" action="/SpringMVCFindEmployee/searchEmployee" >
<table >
<tr>
<td>Employee Name : </td>
<td>
<form:input path="name"/>
</td>
</tr>
<tr>
<td>Choose a Location : </td>
<td>
<form:select path="location">
<form:option value="Location1" label="Location1"/>
<form:option value="Location2" label="Location2"/>
</form:select>
</td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Search" /></td>
</tr>
</table>
</form:form>
</body>
</html>
Output:
After entering details, the output is shown via
welcome.jsp
HTML
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome</title>
</head>
<body>
<table>
<tr>
<td> Employee Name :</td>
<td>${firstname}</td>
</tr>
<tr>
<td> Availability :</td>
<td>${availability} </td>
<td>${day}</td>
<td> at ${location}</td>
</tr>
<tr>
</tr>
<tr>
</tr>
<tr>
<td><a href="employeesearchform">Search Again</a>
</td>
</tr>
</table>
</body>
</html>
We can check the same via our test cases as well
EmployeeControllerTest.java
Java
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.employees.beans.Employee;
import com.employees.controllers.EmployeeController;
import com.employees.dao.EmployeeDao;
@ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/spring-servlet.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
public class EmployeeControllerTest {
@InjectMocks
private EmployeeController employeeController;
private MockMvc mockMvc;
@Autowired
private EmployeeDao dao;
@Autowired
WebApplicationContext webApplicationContext;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(employeeController).build();
}
@Test
// 404 error thrown when coming from invalid resources
public void testCreateSearchEmployeesPageFormInvalidUser() throws Exception {
this.mockMvc.perform(get("/"))
.andExpect(status().isNotFound());
}
@Test
// positive testcase
public void testSearchEmployeesByNameAndCheckAvailability() throws Exception {
Employee employee = new Employee();
employee.setName("EmployeeA");
employee.setLocation("Location1");
employee = dao.getEmployeesByNameAndLocation(employee.getName(),employee.getLocation());
Assert.assertEquals(1, employee.getId());
Assert.assertEquals("Monday,Tuesday,Friday", employee.getAvailableDays());
}
@Test
// Negative testcase
public void testSearchEmployeesByNameAndCheckAvailabilityWithNotEqualsValues() throws Exception {
Employee employee = new Employee();
employee.setName("EmployeeA");
employee.setLocation("Location2");
employee = dao.getEmployeesByNameAndLocation(employee.getName(),employee.getLocation());
Assert.assertNotEquals(10, employee.getId());
Assert.assertNotEquals("Tuesday,Thursday", employee.getAvailableDays());
}
@Test
//Negative testcase i.e. Given gender as Male and available days as Saturday
public void testSearchEmployeesByGender() throws Exception {
Employee employee = new Employee();
employee.setGender("Male");
employee.setAvailableDays("Saturday,Sunday");
employee = dao.getEmployeesByGender(employee.getGender(),employee.getAvailableDays());
Assert.assertEquals(4, employee.getId());
Assert.assertNotEquals("EmployeeB", employee.getName());
Assert.assertNotEquals(1, employee.getExperience());
}
@Test
// Negative testcase i.e. Given gender as Male and available days as Saturday
public void testSearchEmployeesByGenderWithCorrectResults() throws Exception {
Employee employee = new Employee();
employee.setGender("Male");
employee.setAvailableDays("Saturday,Sunday");
employee = dao.getEmployeesByGender(employee.getGender(),employee.getAvailableDays());
Assert.assertEquals(4, employee.getId());
Assert.assertNotEquals("EmployeeB", employee.getName());
Assert.assertNotEquals(1, employee.getExperience());
}
@Test
// Negative testcase i.e. giving experience as 4 years and checking
// as the name of the doctor to be DoctorE instead of DoctorD
public void testSearchEmployeesByExperience() throws Exception {
Employee employee = new Employee();
employee.setExperience(4);
employee = dao.getEmployeesByExperience(employee.getExperience());
Assert.assertEquals(4, employee.getId());
Assert.assertNotEquals("EmployeeF", employee.getName());
}
@Test
public void testSearchEmployeesByQualification() throws Exception {
Employee employee = new Employee();
employee.setQualification("MBA");
employee.setAvailableDays("Saturday,Sunday");
employee = dao.getEmployeesByQualification(employee.getQualification(),employee.getAvailableDays());
Assert.assertEquals(4, employee.getId());
Assert.assertEquals("EmployeeD", employee.getName());
Assert.assertNotEquals(15, employee.getExperience());
}
}
On executing the test cases, we can see the below output
One can simulate this kind of scenario, and prepare a spring MVC project along with JUNIT test cases.
Similar Reads
Basics
Introduction to JavaJava is a high-level, object-oriented programming language developed by Sun Microsystems in 1995. It is mostly used for building desktop applications, web applications, Android apps, and enterprise systems.Key Features of JavaPlatform Independent: Java is famous for its Write Once, Run Anywhere (WOR
4 min read
Java Programming BasicsJava is a class-based, object-oriented programming language that is designed to be secure and portable. Its core principle is âWrite Once, Run Anywhereâ (WORA), meaning Java code can run on any device or operating system that has a Java Virtual Machine (JVM).Java Development Environment: To run Java
9 min read
Java MethodsJava Methods are blocks of code that perform a specific task. A method allows us to reuse code, improving both efficiency and organization. All methods in Java must belong to a class. Methods are similar to functions and expose the behavior of objects.Example: Java program to demonstrate how to crea
7 min read
Access Modifiers in JavaIn Java, access modifiers are essential tools that define how the members of a class, like variables, methods, and even the class itself, can be accessed from other parts of our program. They are an important part of building secure and modular code when designing large applications. In this article
6 min read
Arrays in JavaIn Java, an array is an important linear data structure that allows us to store multiple values of the same type. Arrays in Java are objects, like all other objects in Java, arrays implicitly inherit from the java.lang.Object class. This allows you to invoke methods defined in Object (such as toStri
9 min read
Java StringsIn Java, a String is the type of object that can store a sequence of characters enclosed by double quotes and every character is stored in 16 bits, i.e., using UTF 16-bit encoding. A string acts the same as an array of characters. Java provides a robust and flexible API for handling strings, allowin
8 min read
Regular Expressions in JavaIn Java, Regular Expressions or Regex (in short) in Java is an API for defining String patterns that can be used for searching, manipulating, and editing a string in Java. Email validation and passwords are a few areas of strings where Regex is widely used to define the constraints. Regular Expressi
7 min read
OOPs & Interfaces
Classes and Objects in JavaIn Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent real-world concepts and entities. A class is a template to create objects having similar properties and behavior, or in other words, we can say that a class is a blueprint for objects.An
10 min read
Java ConstructorsIn Java, constructors play an important role in object creation. A constructor is a special block of code that is called when an object is created. Its main job is to initialize the object, to set up its internal state, or to assign default values to its attributes. This process happens automaticall
10 min read
Java OOP(Object Oriented Programming) ConceptsBefore Object-Oriented Programming (OOPs), most programs used a procedural approach, where the focus was on writing step-by-step functions. This made it harder to manage and reuse code in large applications.To overcome these limitations, Object-Oriented Programming was introduced. Java is built arou
10 min read
Java PackagesPackages in Java are a mechanism that encapsulates a group of classes, sub-packages and interfaces. Packages are used for: Prevent naming conflicts by allowing classes with the same name to exist in different packages, like college.staff.cse.Employee and college.staff.ee.Employee.Make it easier to o
7 min read
Java InterfaceAn Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. Key Properties of Interface:The interface in Java is a mechanism to
11 min read
Collections
Exception Handling
Java Exception HandlingException handling in Java is an effective mechanism for managing runtime errors to ensure the application's regular flow is maintained. Some Common examples of exceptions include ClassNotFoundException, IOException, SQLException, RemoteException, etc. By handling these exceptions, Java enables deve
8 min read
Java Try Catch BlockA try-catch block in Java is a mechanism to handle exceptions. This make sure that the application continues to run even if an error occurs. The code inside the try block is executed, and if any exception occurs, it is then caught by the catch block.Example: Here, we are going to handle the Arithmet
4 min read
Java final, finally and finalizeIn Java, the keywords "final", "finally" and "finalize" have distinct roles. final enforces immutability and prevents changes to variables, methods or classes. finally ensures a block of code runs after a try-catch, regardless of exceptions. finalize is a method used for cleanup before an object is
4 min read
Chained Exceptions in JavaChained Exceptions in Java allow associating one exception with another, i.e. one exception describes the cause of another exception. For example, consider a situation in which a method throws an ArithmeticException because of an attempt to divide by zero.But the root cause of the error was an I/O f
3 min read
Null Pointer Exception in JavaA NullPointerException in Java is a RuntimeException. It occurs when a program attempts to use an object reference that has the null value. In Java, "null" is a special value that can be assigned to object references to indicate the absence of a value.Reasons for Null Pointer ExceptionA NullPointerE
5 min read
Exception Handling with Method Overriding in JavaException handling with method overriding in Java refers to the rules and behavior that apply when a subclass overrides a method from its superclass and both methods involve exceptions. It ensures that the overridden method in the subclass does not declare broader or new checked exceptions than thos
4 min read
Java Advanced
Java Multithreading TutorialThreads are the backbone of multithreading. We are living in the real world which in itself is caught on the web surrounded by lots of applications. With the advancement in technologies, we cannot achieve the speed required to run them simultaneously unless we introduce the concept of multi-tasking
15+ min read
Synchronization in JavaIn multithreading, synchronization is important to make sure multiple threads safely work on shared resources. Without synchronization, data can become inconsistent or corrupted if multiple threads access and modify shared variables at the same time. In Java, it is a mechanism that ensures that only
10 min read
File Handling in JavaIn Java, file handling means working with files like creating them, reading data, writing data or deleting them. It helps a program save and use information permanently on the computer. With the help of File Class, we can work with files. This File Class is inside the java.io package. The File class
5 min read
Java Method ReferencesIn Java, a method is a collection of statements that perform some specific task and return the result to the caller. A method reference is the shorthand syntax for a lambda expression that contains just one method call. In general, one does not have to pass arguments to method references.Why Use Met
9 min read
Java 8 Stream TutorialJava 8 introduces Stream, which is a new abstract layer, and some new additional packages in Java 8 called java.util.stream. A Stream is a sequence of components that can be processed sequentially. These packages include classes, interfaces, and enum to allow functional-style operations on the eleme
15+ min read
Java NetworkingWhen computing devices such as laptops, desktops, servers, smartphones, and tablets and an eternally-expanding arrangement of IoT gadgets such as cameras, door locks, doorbells, refrigerators, audio/visual systems, thermostats, and various sensors are sharing information and data with each other is
15+ min read
JDBC TutorialJDBC stands for Java Database Connectivity. JDBC is a Java API or tool used in Java applications to interact with the database. It is a specification from Sun Microsystems that provides APIs for Java applications to communicate with different databases. Interfaces and Classes for JDBC API comes unde
12 min read
Java Memory ManagementJava memory management is the process by which the Java Virtual Machine (JVM) automatically handles the allocation and deallocation of memory. It uses a garbage collector to reclaim memory by removing unused objects, eliminating the need for manual memory managementJVM Memory StructureJVM defines va
4 min read
Garbage Collection in JavaGarbage collection in Java is an automatic memory management process that helps Java programs run efficiently. Objects are created on the heap area. Eventually, some objects will no longer be needed.Garbage collection is an automatic process that removes unused objects from heap.Working of Garbage C
6 min read
Memory Leaks in JavaIn programming, a memory leak happens when a program keeps using memory but does not give it back when it's done. It simply means the program slowly uses more and more memory, which can make things slow and even stop working. Working of Memory Management in JavaJava has automatic garbage collection,
3 min read
Practice Java
Java Interview Questions and AnswersJava is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Java Programs - Java Programming ExamplesIn this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read
Java Exercises - Basic to Advanced Java Practice Programs with SolutionsLooking for Java exercises to test your Java skills, then explore our topic-wise Java practice exercises? Here you will get 25 plus practice problems that help to upscale your Java skills. As we know Java is one of the most popular languages because of its robust and secure nature. But, programmers
7 min read
Java Quiz | Level Up Your Java SkillsThe best way to scale up your coding skills is by practicing the exercise. And if you are a Java programmer looking to test your Java skills and knowledge? Then, this Java quiz is designed to challenge your understanding of Java programming concepts and assess your excellence in the language. In thi
1 min read
Top 50 Java Project Ideas For Beginners and Advanced [Update 2025]Java is one of the most popular and versatile programming languages, known for its reliability, security, and platform independence. Developed by James Gosling in 1982, Java is widely used across industries like big data, mobile development, finance, and e-commerce.Building Java projects is an excel
15+ min read