Accepting Request Input using @RequestParam, @PathVariable and Form Handeling Spring MVC
In our last SPRING MVC article we explained you how you can create and dynamic Spring MVC web project with MAVEN without using web.xml with java based configuration and also explained you the flow of request through dispatcher servlet to controller and then back to view.
But any web application is not complete if it cannot accept input from the client. So in this article we will show you how you can get the input from the client using Spring MVC
Spring MVC provides three ways in which you can get the input from a by request from a client inside a controller method.
1. By Request Parameters 2. By Path Variables 3. Form Parameters1. Getting Input from request parameters with @RequestParam
Suppose we are making a GET request which has url like - /home?userId=123
Then in this url userId is the request parameter with value 123.
And to capture this value in our @Controller annotated method we use @RequestParame annotated method parameter as shown in the example below.
@RequestMapping(value= "/home", method=RequestMethod.GET)
public String home (@RequestParam("userId") int id){
System.out.println(id);
return "home";
}
Now if controller gets a request with query parameter with name userId it will be captured by id variable which is of type int.
Using default value for @RequestParamWe can also define a default value for @RequestParam annotated variable using defaultValue as shown in the next example.
@RequestMapping(value= "/home", method=RequestMethod.GET)
public String home (@RequestParam(value="userId", defaultValue="255") int userId){
System.out.println(userId);
return "home";
}
So if we do not provide any query parameter just simple /home url then userId variable will have a default value 255. We have provided 255 as a String because query parameters are always of type String , but later it will get converted into int because userId variable is an int.
2. Getting Values from request as Path Variable using @PathVariable
Path variables are another way of getting data as path variable, here in the url we do not use key value pair like query parameter to pass the value but the value is sent as the part of the url path.
Like for url - /home/jonney
Here we can get the name jonney as part variable in spring controller using @PathVariable annotated method parameter.
For identifying the variable portion of the Url path we use a variable inside the url of the @RequestMapping annotated url, which is surrounded by curly braces.
For url - /home/jonney , to get the path variable jonney we can use the following controller method.
@RequestMapping(value= "/home/{userName}", method=RequestMethod.GET)
public String home (@PathVariable("userName") String name){
System.out.println(name);
return "home";
}
In above example name String parameter has been used to capture the path variable which has been passed to the variable part of @RequestMapping url {userName}
3. Accessing The Form Data In Spring MVC
There are two parts of this process, first is to display the form with some object bound to the form and other is getting the values from the form after form is submitted.
To bind the data of form to an object we will send an empty Object say User in model and bind the form with this Object using modelAttribute
Controller method for Displaying the form -
@RequestMapping(value="register-emp", method=RequestMethod.GET)
public ModelAndView registerEmployeeForm(){
ModelAndView model = new ModelAndView("register_employee", "user", new Employee());
return model;
}
In above method we are sending an Employee class Object with Model as attribute name 'user' and the view name is 'register_employee'
register_employee.jsp<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <div style="text-align:center"> <form:form method="post" modelAttribute="user"> <table> <tr> <td>User Name</td> <td><form:input path="name" type="text" /> <!-- bind to user.name--></td> </tr> <tr> <td>User Email</td> <td><form:input path="email" type="text" /> <!-- bind to user.email--></td> </tr> <tr> <td>User Phone</td> <td><form:input path="phone" type="number" /> <!-- bind to user.name--></td> </tr> <tr> <td>User Password</td> <td><form:input path="password" type="password" /> <!-- bind to user.name--></td> </tr> <tr> <td><button type="submit">SUBMIT</button> <!-- bind to user.name--></td> </tr> </table> </form:form> </div>
As you can notice from above form we have not used action attribute because we want to submit the form to the same url.
Controller Method to get the form Values
@RequestMapping(value="register-emp", method=RequestMethod.POST)
public ModelAndView registerEmployee(@ModelAttribute("user") Employee emp){
ModelAndView model = new ModelAndView("emp_details");
model.addObject("user", emp);
return model;
}
As you can see we have used @ModelAttribute annotated method parameter, this is used to get the Model attribute with key ‘user’ which is obviously the user object we want to access.
After we get the values we are sending it to another jsp emp_details.jsp with model to show them.
For any questions or query, feel free to leave comments below. Thanks!
Create Spring MVC web application without web.xml and with Java Configuration using MAVEN
First of All we have to create a web project which we will create with the help of maven tool. We will not go into the details of creating a web project with MAVEN in eclipse, just follow the given steps below to create a WEB project with MAVEN
* First of all open the command line and check whether MAVEN is installed or notmvn -v
if you see the following line, then follow the next steps, otherwise install maven first.Apache Maven 3.3.9 (bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-11-10T22:11:47+05:30) Maven home: C:\maven\apache-maven-3.3.9\bin\.. Java version: 1.7.0_79, vendor: Oracle Corporation Java home: C:\Program Files\Java\jdk1.7.0_79\jre Default locale: en_IN, platform encoding: Cp1252 OS name: "windows 7", version: "6.1", arch: "amd64", family: "windows"
* Type the following command for creating the project folder at the current location
C:\Users\jonney\maven-project>mvn archetype:generate -DgroupId=com.tutorials.sample -DartifactId=SampleSpringMaven -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false* Once the project folder is created, step inside the folder and type the following command for making it importable in eclipse
C:\Users\jonney\maven-project\SampleSpringMaven>mvn eclipse:eclipse -Dwtpversion=2.0* Now import the project in your eclipse and open the pom.xml for adding dependencies for the project. Update the pom.xml as given below.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorials.sample</groupId>
<artifactId>SampleSpringMaven</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>SampleSpringMaven Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<spring.version>4.2.4.RELEASE</spring.version>
<jdk.version>1.7</jdk.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
</dependencies>
<build>
<finalName>SampleSpringMaven</finalName>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<configuration>
<url>http://localhost:8080/manager/text</url>
<server>my-tomcat</server>
<path>/SampleSpringMaven</path>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
* Once you are done with adding dependencies, again type in the following command for downloading and adding dependencies in the project.
C:\Users\jonney\maven-project\SampleSpringMaven>mvn eclipse:eclipse -Dwtpversion=2.0
Now you are ready to start developing your project in eclipse.
Note :If you are using servlet 3.0 or above then you can skip web.xml file and configure all the configurations inside a java file, this is the must requirement if you want to skip web.xml.
Before we start writing any code lets understand the flow of the application and its components -
1. When application gets a request from some client , it goes to the DispatcherServlet which works as a front end controller and based on the url of the request , it forwards the request to the Spring MVC controller.
2. Spring MVC controller gets the request and based on the url of the request one of its method gets called , here request can leave its payload for some time and so that controller can perform some business calculations using service classes. After different operation are done, controller sends a logical view name wrapped with some data which we want to show the user and sends it back to the dispatcher servlet.
3. Now controller consults the ViewResolver and gives the logical view name to the ViewResolver which then gets resolved into some jsp or html, this is the last stop of the request and the data gets rendered by the view.
Now we will see how all these above steps are performed one by one write our application for showing the home page of application.
Setting up Dispatcher Servlet without web.xml file
In spring web projects Dispatcher Servlet works as a single from end controller and based on the url of the coming http request it distributes the requests to different mvc controllers. Since we are not using web.xml file here so we will configure this servlet in a java class WebAppInitializer and this class will extend AbstractAnnotationConfigDispatcherServletInitializer. Any class that extends AbstractAnnotationConfigDispatcherServletInitializer is automatically used to configure DispatcherServlet and Spring application context in application’s servlet context.
WebAppInitializer.java
package com.hellospring.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
@Override
protected Class[] getRootConfigClasses() {
return new Class []{RootConfig.class};
}
@Override
protected Class[] getServletConfigClasses() {
return new Class []{WebConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
}
As we can see that WebAppInitializer has two methods for configuring java configuration classes.
When DispatcherServlets starts it creates an spring application context and this application context loads its configuration from WebConfig.class which has been provided by getServletConfigClasses() method declared above in WebAppInitializer class.
But in spring web application one another Application context is created by ContextLoader- Listener and this Application context loads its configurations from RootConfig.class class provided by the method getRootConfigClasses() defined above.
DispatcherServlet is supposed to load beans basically for web components like controllers and view resolvers , whereas ContextLoader listener is expected to load other beans usually data-tier beans and and middle-tier beans.
And the last method provides the url which needs to be associated with the dispatcher servlet
Now we are done with creating a dispatcher servlet for our web application, but what about enabling mvc and component scanning which we used to do in our configuration files earlier ?
@EnableWebMvc - Annotate your configuration class with this annotation to enable annotation driven Spring MVC in your application.
@ComponantScan(“package”) - Annotate your java config class with this annotation to enable component scanning for the package.
package com.hellospring.config;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Import;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.hellospring.model, com.hellospring.web")
public class AppConfig extends WebMvcConfigurerAdapter {
@Bean
public ViewResolver viewResolver(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/jsp/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
In above configuration class we have annotated the class with @Configuration
@EnableWebMvc and @ComponentScan and the purpose has already been explained.
We have also defined a ViewResolver bean which we used to define in an xml file earlier.
Now another thing to notice is this, that we have extended WebMvcConfigurerAdapter which allow us to override configureDefaultServletHandling() method. By overriding this method we are saying the DispatcherServlet to forward the requests for static resources to the default servlet of servlet container.
Now as we are done with writing our configuration file, let’s take our request one step forward which is a controller.
Writing a Simple Controller
In spring MVC controller is noting but just a simple java class annotated with @Controller mapping and methods annotated with @RequestMapping.
Given below we have written a simple controlled for our home page of our application.
package com.hellospring.web.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.hellospring.web.service.CommonService;
@Controller
public class HomeController {
@RequestMapping(value = "/home", method = RequestMethod.GET)
ModelAndView home (){
return “home”;
}
}
@Controller - We have annotated our Class with this mapping to make sure that this class gets defined as a bean in our Application context. We can also use @Component annotation to define a class as a bean in application but using the @Controller annotation gives extra information about what kind of component this class is.
@RequestMapping - In this method we have defined the url for which this method will be called and the type of HTTP method which is GET in this case.
@RequestMapping(“home”,”welcome”)-
We can also define multiple urls for which this method will get called, because it can take an array of strings
@RequestMapping("/home") - We can also set class level mapping which will be used for all the methods inside that controler. Just annotate the class with @RequestMapping annotation like methods.
Rendering the View
As we can see that the only method inside the controller class is not doing much except returning a string “home”. This is the logical view name which will be provided to ViewResolver which we have configured as a bean in WebConfig configuration file. And as we can see in the ViewResolver configuration this view name will be resolved as a jsp at /WEB-INF/jsp/home.jsp.
This is a simple jsp file for now just Welcoming User.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ page session="false" %> <html> <head> <title>Home Page</title> </head> <body> <h1>Hello, Welcome User</h1> </body> </html>
Passing Data To View
In above controller , we are not sending anything to the jsp we are sending a logical view name to the view resolver which is rendering the jsp page, but in real world applications this very unlikely. To bind the data to the view there are various methods but the one which we are going to use is easy and used most of the time.
We create a ModelAndView object in the controller , which is nothing special but a simple map of key and values, which we want to send to the View. And if the view is a Jsp , the model data is copied into the request as the request attributes. Now because the modal data is now accessible as request attributes so we can easily use it in jsp using JSTL or el.
Controller Version 2
package com.hellospring.web.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.hellospring.web.service.CommonService;
@Controller
public class HomeController {
@RequestMapping("/home")
ModelAndView home (){
ModelAndView model = new ModelAndView("home");
model.addObject("userName", “JOHN WICK”);
return model;
}
}
The above method binds a string “JOHN WICK” with key “userName” and set the view name “home” As an argument to the ModelAndView constructor. Now this data can be rendered on /WEB-INF/jsp/home.jsp page
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
<title>Home Page</title>
</head>
<body>
<h1>Hello, Welcome <c: out value=${userName}></h1>
</body>
</html>
home page with SimpleController,
home page with SimpleController and model data,So, this was all about setting up Spring MVC project with Servlet 3 and with JAVA config./p>
Create Custom Linked List - JAVA with Examples | Tutorials - Scratcharound
What is Linked List -
Like arrays Linked list is a linear data structure, but elements in a linked list are not stored in a contiguous location. Elements in a linked list are linked together with some pointer ie. each element in Linked list has a pointer to the next element(singly linked list). In this article we will create our own custom Linked with some basic operations like insertion, deletion and printing a linked list.
You can easily understand the basic structure of a linked list with the help of below diagram.
It has different nodes, each node has data and pointer to the next node element. The very first node is called Head Node. If there are no more elements in the Linked list then next will be be null.
Simple Linked list in JAVA:
package com.ds.linkedlist;
public class CLinkedList {
Node head;
static class Node{
int data;
Node next;
Node(int d){
data = d;
next = null;
}
}
}
We have created a custom linked list ClinkedList, it has a inner static class Node and can hold integer type data. Node has two member variables int to contain the integer type data and next which will hold the next node of the linked list. ClinkedList has a head member variable which is a Node. Head is the first node of a CLinkedList.
Inserting elements in a LinkedList
We can insert elements insdie a linked list at different positions.
1. Insertion at the beginning of the LinkedList
2. Insertion at the end of the LinkedList 3. Insertion in middle of the LinkedList after some given Node. 1. Inserting at the Beginning of the LinkedList
If we add the element in the beginning of the list, then 'head' variable will refer to the newly created Node and the next of this New Node will refer to the old Head node.
// adds an element in the beginning of list
public void push(int data){
Node n = new Node(data);
if(head == null){
head = n;
return;
}
n.next = this.head;
this.head = n;
}
2. Inserting at the End of the LinkedList
First we have to find out the last element of the LinkedList and then set the new Node as the next of this last node of the LinkedList.
// insert element at the end
public void append(int data){
Node new_node = new Node(data);
if(this.head == null){
head = new_node;
}
Node lastNode = this.head;
while(lastNode.next != null){
lastNode = lastNode.next;
}
lastNode.next = new_node;
}
3. Inserting after a given Node in LinkedList
We will just set the next of the given node to the Newly creater Node.
// insert after a node
public void insertAfter(Node n, int data){
if(n == null){
System.out.println("Previous node cannot be null");
return;
}
Node new_node = new Node(data);
new_node.next = n.next;
n.next = new_node;
}
Delete an element from LinkedList
We will find the previous and next node for the given element. Set next of previous node to the next of deleted node and set next of deleted element to null
// delete an element
public void delete(int data){
Node prevNode = null;
Node temp = head;
if(head!=null && head.data == data){
head = temp.next;
temp = null;
return;
}
while(temp != null && temp.data != data){
prevNode = temp;
temp = temp.next;
}
if(temp==null){
System.out.println("element not found");
return;
}
prevNode.next = temp.next;
temp.next = null;
}
Printing a LinkedList
//print list
public void printList(){
if(head == null){
System.out.println("List is empty");
return;
}
Node pNode = head;
while(pNode != null){
System.out.print(pNode.data+" ");
pNode = pNode.next;
}
}
Count elements of LinkedList
This count function will return the total number of elements in the CLinkedList.
public int count(){
int count = 0;
if(head == null) return count;
Node temp = head;
while(temp!=null){
temp = temp.next;
count += 1;
}
return count;
}
So these were some basic operations we can perform with our Custom Linked List in java. This whole ClinkedList will look something like the code given below:
Custom Linked List Full Code
package com.ds.linkedlist;
public class CLinkedList {
Node head;
static class Node{
int data;
Node next;
Node(int d){
data = d;
next = null;
}
}
// adds an element in the beginning of list
public void push(int data){
Node n = new Node(data);
if(head == null){
head = n;
return;
}
n.next = this.head;
this.head = n;
}
public void insertAfter(Node n, int data){
if(n == null){
System.out.println("Previous node cannot be null");
return;
}
Node new_node = new Node(data);
new_node.next = n.next;
n.next = new_node;
}
public void append(int data){
Node new_node = new Node(data);
if(this.head == null){
head = new_node;
}
Node lastNode = this.head;
while(lastNode.next != null){
lastNode = lastNode.next;
}
lastNode.next = new_node;
}
// delete an element
public void delete(int data){
Node prevNode = null;
Node temp = head;
if(head!=null && head.data == data){
head = temp.next;
temp = null;
return;
}
while(temp != null && temp.data != data){
prevNode = temp;
temp = temp.next;
}
if(temp==null){
System.out.println("element not found");
return;
}
prevNode.next = temp.next;
temp.next = null;
}
public int count(){
int count = 0;
if(head == null) return count;
Node temp = head;
while(temp!=null){
temp = temp.next;
count += 1;
}
return count;
}
//print list
public void printList(){
if(head == null){
System.out.println("List is empty");
return;
}
Node pNode = head;
while(pNode != null){
System.out.print(pNode.data+" ");
pNode = pNode.next;
}
}
}
Now lets try to perform these operations with this CLinkedList
Example 1: Inserting element inside the LinkedList
package com.ds.linkedlist;
import com.ds.linkedlist.CLinkedList.Node;
public class Test {
public static void main(String[] args) {
CLinkedList l = new CLinkedList();
l.head = new Node(1);
l.append(2);
l.append(3);
l.append(4);
l.push(5);
l.insertAfter(l.head, 6);
l.append(7);
l.append(9);
l.printList();
}
}
Above example pushes the element 5 which makes it the head element. Then we have inserted the element 6 after the head element
5 which maked 6 the second element in the list. Output : 5 6 1 2 3 4 7 9
Example 1: Deleting element from the LinkedList
package com.ds.linkedlist;
import com.ds.linkedlist.CLinkedList.Node;
public class Test {
public static void main(String[] args) {
CLinkedList l = new CLinkedList();
l.head = new Node(1);
l.append(2);
l.append(3);
l.append(4);
l.push(5);
l.insertAfter(l.head, 6);
l.append(7);
l.append(9);
l.delete(3);
l.printList();
}
}
Output : 5 6 1 2 4 7 9 Example 1: Count total elements LinkedList
package com.ds.linkedlist;
import com.ds.linkedlist.CLinkedList.Node;
public class Test {
public static void main(String[] args) {
CLinkedList l = new CLinkedList();
l.head = new Node(1);
l.append(2);
l.append(3);
l.append(4);
l.push(5);
l.insertAfter(l.head, 6);
l.append(7);
l.append(9);
System.out.println("Size is "+l.count());
l.delete(3);
System.out.println("Size is "+l.count());
l.printList();
}
}
Output :Size is 8 Size is 7 5 6 1 2 4 7 9
These were some basic operations performed with our Custom Linked list. Now as we have seen the things in action, we can point out some advantages and discadvantages of linked list over Array.
Linked List VS Array
Some advantages of LinkedList over array are that we can easily insert or delete an element in the liked list, whereas if want to delete or insert an element in an Array, we will have to shift all other next elements in the Array, which is a complex process and time consuming.Another advantage of LinkedlIst over array is that its size is not fixed like arrays, we can insert more elements inside it without declaring its size.
There are also some drawbacks of using LinkeList, like if we need extra memory space for the pointer. Also we cannot access elements randomly , we will have to start from the head to get the desired element.
So these were some advantages and disadvantages of LinkedList over Arrays. If you have any questions please feel free to write in the comments below.
What is Linked List -
Like arrays Linked list is a linear data structure, but elements in a linked list are not stored in a contiguous location. Elements in a linked list are linked together with some pointer ie. each element in Linked list has a pointer to the next element(singly linked list). In this article we will create our own custom Linked with some basic operations like insertion, deletion and printing a linked list.
You can easily understand the basic structure of a linked list with the help of below diagram.
It has different nodes, each node has data and pointer to the next node element. The very first node is called Head Node. If there are no more elements in the Linked list then next will be be null.
Simple Linked list in JAVA:
package com.ds.linkedlist;
public class CLinkedList {
Node head;
static class Node{
int data;
Node next;
Node(int d){
data = d;
next = null;
}
}
}
We have created a custom linked list ClinkedList, it has a inner static class Node and can hold integer type data. Node has two member variables int to contain the integer type data and next which will hold the next node of the linked list. ClinkedList has a head member variable which is a Node. Head is the first node of a CLinkedList.
Inserting elements in a LinkedList
We can insert elements insdie a linked list at different positions.
1. Insertion at the beginning of the LinkedList
2. Insertion at the end of the LinkedList 3. Insertion in middle of the LinkedList after some given Node. 1. Inserting at the Beginning of the LinkedList
If we add the element in the beginning of the list, then 'head' variable will refer to the newly created Node and the next of this New Node will refer to the old Head node.
// adds an element in the beginning of list
public void push(int data){
Node n = new Node(data);
if(head == null){
head = n;
return;
}
n.next = this.head;
this.head = n;
}
2. Inserting at the End of the LinkedList
First we have to find out the last element of the LinkedList and then set the new Node as the next of this last node of the LinkedList.
// insert element at the end
public void append(int data){
Node new_node = new Node(data);
if(this.head == null){
head = new_node;
}
Node lastNode = this.head;
while(lastNode.next != null){
lastNode = lastNode.next;
}
lastNode.next = new_node;
}
3. Inserting after a given Node in LinkedList
We will just set the next of the given node to the Newly creater Node.
// insert after a node
public void insertAfter(Node n, int data){
if(n == null){
System.out.println("Previous node cannot be null");
return;
}
Node new_node = new Node(data);
new_node.next = n.next;
n.next = new_node;
}
Delete an element from LinkedList
We will find the previous and next node for the given element. Set next of previous node to the next of deleted node and set next of deleted element to null
// delete an element
public void delete(int data){
Node prevNode = null;
Node temp = head;
if(head!=null && head.data == data){
head = temp.next;
temp = null;
return;
}
while(temp != null && temp.data != data){
prevNode = temp;
temp = temp.next;
}
if(temp==null){
System.out.println("element not found");
return;
}
prevNode.next = temp.next;
temp.next = null;
}
Printing a LinkedList
//print list
public void printList(){
if(head == null){
System.out.println("List is empty");
return;
}
Node pNode = head;
while(pNode != null){
System.out.print(pNode.data+" ");
pNode = pNode.next;
}
}
Count elements of LinkedList
This count function will return the total number of elements in the CLinkedList.
public int count(){
int count = 0;
if(head == null) return count;
Node temp = head;
while(temp!=null){
temp = temp.next;
count += 1;
}
return count;
}
So these were some basic operations we can perform with our Custom Linked List in java. This whole ClinkedList will look something like the code given below:
Custom Linked List Full Code
package com.ds.linkedlist;
public class CLinkedList {
Node head;
static class Node{
int data;
Node next;
Node(int d){
data = d;
next = null;
}
}
// adds an element in the beginning of list
public void push(int data){
Node n = new Node(data);
if(head == null){
head = n;
return;
}
n.next = this.head;
this.head = n;
}
public void insertAfter(Node n, int data){
if(n == null){
System.out.println("Previous node cannot be null");
return;
}
Node new_node = new Node(data);
new_node.next = n.next;
n.next = new_node;
}
public void append(int data){
Node new_node = new Node(data);
if(this.head == null){
head = new_node;
}
Node lastNode = this.head;
while(lastNode.next != null){
lastNode = lastNode.next;
}
lastNode.next = new_node;
}
// delete an element
public void delete(int data){
Node prevNode = null;
Node temp = head;
if(head!=null && head.data == data){
head = temp.next;
temp = null;
return;
}
while(temp != null && temp.data != data){
prevNode = temp;
temp = temp.next;
}
if(temp==null){
System.out.println("element not found");
return;
}
prevNode.next = temp.next;
temp.next = null;
}
public int count(){
int count = 0;
if(head == null) return count;
Node temp = head;
while(temp!=null){
temp = temp.next;
count += 1;
}
return count;
}
//print list
public void printList(){
if(head == null){
System.out.println("List is empty");
return;
}
Node pNode = head;
while(pNode != null){
System.out.print(pNode.data+" ");
pNode = pNode.next;
}
}
}
Now lets try to perform these operations with this CLinkedList
Example 1: Inserting element inside the LinkedList
package com.ds.linkedlist;
import com.ds.linkedlist.CLinkedList.Node;
public class Test {
public static void main(String[] args) {
CLinkedList l = new CLinkedList();
l.head = new Node(1);
l.append(2);
l.append(3);
l.append(4);
l.push(5);
l.insertAfter(l.head, 6);
l.append(7);
l.append(9);
l.printList();
}
}
Above example pushes the element 5 which makes it the head element. Then we have inserted the element 6 after the head element
5 which maked 6 the second element in the list. Output : 5 6 1 2 3 4 7 9
Example 1: Deleting element from the LinkedList
package com.ds.linkedlist;
import com.ds.linkedlist.CLinkedList.Node;
public class Test {
public static void main(String[] args) {
CLinkedList l = new CLinkedList();
l.head = new Node(1);
l.append(2);
l.append(3);
l.append(4);
l.push(5);
l.insertAfter(l.head, 6);
l.append(7);
l.append(9);
l.delete(3);
l.printList();
}
}
Output : 5 6 1 2 4 7 9 Example 1: Count total elements LinkedList
package com.ds.linkedlist;
import com.ds.linkedlist.CLinkedList.Node;
public class Test {
public static void main(String[] args) {
CLinkedList l = new CLinkedList();
l.head = new Node(1);
l.append(2);
l.append(3);
l.append(4);
l.push(5);
l.insertAfter(l.head, 6);
l.append(7);
l.append(9);
System.out.println("Size is "+l.count());
l.delete(3);
System.out.println("Size is "+l.count());
l.printList();
}
}
Output :Size is 8 Size is 7 5 6 1 2 4 7 9
These were some basic operations performed with our Custom Linked list. Now as we have seen the things in action, we can point out some advantages and discadvantages of linked list over Array.
Linked List VS Array
Some advantages of LinkedList over array are that we can easily insert or delete an element in the liked list, whereas if want to delete or insert an element in an Array, we will have to shift all other next elements in the Array, which is a complex process and time consuming.Another advantage of LinkedlIst over array is that its size is not fixed like arrays, we can insert more elements inside it without declaring its size.
There are also some drawbacks of using LinkeList, like if we need extra memory space for the pointer. Also we cannot access elements randomly , we will have to start from the head to get the desired element.
So these were some advantages and disadvantages of LinkedList over Arrays. If you have any questions please feel free to write in the comments below.
Reading A Simple CSV file in java and putting it into a Map-java code
the csv file has the country code and country name in this form-
ID,"Indonesia" IE,"Ireland" IL,"Israel" IM,"Isle of Man" IN,"India" IO,"British Indian Ocean Territory" IQ,"Iraq" IR,"Iran, Islamic Republic of" IS,"Iceland" IT,"Italy" JE,"Jersey"
package com.tutorialsinn.javatutorials;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class CsvReader {
private static String line = "";
private static String cvsSplitBy = ",";
public static Map<String, String> csvToMap(String csvFile) {
Map<String, String> map = new HashMap<String, String>();
BufferedReader br=null;
try {
br = new BufferedReader(new FileReader(csvFile));
line = br.readLine();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (line != null) {
String[] splitArr = line.split(cvsSplitBy);
map.put(splitArr[0], splitArr[1].replace("\"",""));
try {
line = br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return map;
}
}
The code will take take a csv-file location as argument inside the static method csvToMap which will return a HashMap with keyvalue pair ,where key is the country code and value is the country name, both are string.
How To Sort Array Of Objects Using Comparator Interface In java
sort(array,comparator)
This method takes two arguments one ,the array we want to sort and the other one is the instance of Comparator.
Comparator interface has a method compare() which compares two objects and returns an integer value based on the following table-
int compare(object1,object2)
| if object1<object2 | negative value |
| if object1>object2 | positive value |
| if object1=object2 | zero(0) |
Now we are ready to write the code, so here are the classes we are going to write-
- First create a class which objects we need to put in the Array for sorting
- Comparator instances used for sorting based on different instace variables of the Class objects we created..
- A test class where lies the main method to start the execution.
Class 1-Student.java
package in.blogger.tutorialsinn;
public class Student {
private int id;
private String name;
private int age;
//constructor
public Student(int id, int age, String name) {
super();
this.id = id;
this.name = name;
this.age = age;
}
//overriding toString() method for printing the object values
@Override
public String toString() {
return ("id is " + id + " name is " + name + " age is " + age);
}
//setters and geters
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Class-2 StudentIdComparator.javaThis comparator instance implements java.util.Comparator interface and is used to sort the student objects based on the id.
package in.blogger.tutorialsinn;
import java.util.Comparator;
import in.blogger.tutorialsinn.Student;
public class StudentIdComparator implements Comparator {
@Override
public int compare(Object o1, Object o2) {
Student s1 = (Student) o1;
Student s2 = (Student) o2;
if(s1.getId()>s2.getId()){
return 1;
}
else if(s1.getId()<s2.getId()){
return -1;
}
else
return 0;
}
}
Class 3 StudentNameComparator.javaThis is another comparator which is used to sort the objects on the basis of name which is a string.For comparing String we can use compareTo() method of Comparable interface,which does the same thing as compare() in Comparator.
package in.blogger.tutorialsinn;
import java.util.Comparator;
import in.blogger.tutorialsinn.Student;
public class StudentNameComparator implements Comparator {
@Override
public int compare(Object o1, Object o2) {
Student s1 = (Student) o1;
Student s2 = (Student) o2;
return s1.getName().compareTo(s2.getName());
}
}
Class-4 Testing.java In this class we have created a Array of student objects and put some values using constructor.First we have printed the objects without sorting and then we will print the objects after sorting based on id and name respectively.
package in.blogger.tutorialsinn;
import java.lang.reflect.Array;
import java.util.*;
import in.blogger.tutorialsinn.StudentIdComparator;
import in.blogger.tutorialsinn.StudentNameComparator;
public class Testing {
public static void main(String[] args) {
Student s1=new Student(1,21,"Alan");
Student s2=new Student(22,21,"Bob");
Student s3=new Student(14,22,"Leo");
Student s4=new Student(4,18,"Merry");
Student s5=new Student(56,31,"Sam");
Student s6=new Student(33,41,"Zues");
Student s7=new Student(44,11,"Rock");
Student s8=new Student(2,27,"John");
Student students[]={s1,s2,s3,s4,s5,s6,s7,s8};
for(int i=0;i<students.length;i++){
System.out.println(students[i]);
}
//sorting based on id
Arrays.sort(students,new StudentIdComparator());
for(int i=0;i<students.length;i++){
System.out.println(students[i]);
}
//sorting based on name
Arrays.sort(students,new StudentNameComparator());
for(int i=0;i<students.length;i++){
System.out.println(students[i]);
}
}
}
Output-id is 1 name is Alan age is 21
id is 22 name is Bob age is 21
id is 14 name is Leo age is 22
id is 4 name is Merry age is 18
id is 56 name is Sam age is 31
id is 33 name is Zues age is 41
id is 44 name is Rock age is 11
id is 2 name is John age is 27
id is 1 name is Alan age is 21
id is 2 name is John age is 27
id is 4 name is Merry age is 18
id is 14 name is Leo age is 22
id is 22 name is Bob age is 21
id is 33 name is Zues age is 41
id is 44 name is Rock age is 11
id is 56 name is Sam age is 31
id is 1 name is Alan age is 21
id is 22 name is Bob age is 21
id is 2 name is John age is 27
id is 14 name is Leo age is 22
id is 4 name is Merry age is 18
id is 44 name is Rock age is 11
id is 56 name is Sam age is 31
id is 33 name is Zues age is 41
So this was the simple program showing how to sort an Array of objects using Comparator interface.We can also use comparable interface for this kind of sorting but there are some limitations in that, which you will learn in our next article.
Bubble Sort in java
Suppose we have an array of some integers and we want to sort it in ascending order ie. smallest to the largest integer.In bubble sort we will compare each element of the array with its adjacent next element, and there could arise two conditions either the element will be greater then the next adjacent element or it will be less then the next adjacent element.
If the element is greater then the next adjacent element then we will swap the elements and move to the next step.
If the element is less then the next adjacent element then without doing anything we will move to our next step.
We will keep on doing this until all the elements are sorted.
Now as we have understood the flow of the program , we can start writing the code.
Program-
package in.blogger.tutorialsinn;
public class BubbleSort {
public static void main(String[] args) {
int arr[] = { 4, -3, 2, 6, 1 };
for (int n = 1; n <= arr.length; n++) {
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
}
}
for (int i = 0; i < arr.length; i++) {
System.out.print(" " + arr[i]);
}
}
}
Output- -3 1 2 4 6
I hope you have understood the bubble sort for an integer array,it was a very basic sorting algorithm and we will add some more important sorting algorithms in our next articles so stay in touch.
Difference Between Method Overloading And Method overriding In java
First we will discuss the properties of both individually and then we can easily find out the major and minor differences between these two.
What is method overloading-
Definition-"When two or more then two methods in the same class have the same name but different parameters,then this phenomenon is known as method overloading".The definition of method overloading above sounds pretty simple,but it becomes complicated if we talk about the term "different parameters", how we will identify when the parameters of two methods are different?
To answer the above problem there are two rules,and any one or both of these these rules should be satisfied for method overloading.Here are the rules-
Conditions for method overloading in java
- For method overloading in java the number of parameters in methods should be different.
- Type of the parameters should be different be different
OR
Example of method overloading using different number of parameters-
Program-
package in.blogger.tutorialsinn;
class MethodOverloading {
// first method
static int addNumbers(int a, int b) {
System.out.println("sum of the numbers is " + (a + b));
return (a + b);
}
// second method
static int addNumbers(int a, int b, int c) {
System.out.println("sum of the numbers is " + (a + b + c));
return (a + b + c);
}
}
public class Testing {
public static void main(String[] args) {
// it will call first method
MethodOverloading.addNumbers(1, 2);
// it will call second method
MethodOverloading.addNumbers(1, 2, 3);
}
}
How to not overload methods-
- If return type is the only thing that we have changed of two methods with same name in the same class then it is not a method overloading.
- If we only change the name of the parameters in the methods with same name in the same class, then it is not a method overloading
What if we only change the return type or name of parameters as explained not to do above-
Method overloading is compile time phenomenon and its the duty of compiler to determine whether a method is overloaded correctly,so if we do any of the things recommended above not to do then we will get a compile time error.
Now as we are completely aware about method overloading,so now we will cover our next topic "method overriding".
Method Overriding In java-
Definition-"If we redefine a method in the subclass with the same name,same return type,same number of parameters and same type of the parameters as it was in the super class then this phenomenon is called method overriding".Method overriding is a run-time phenomenon not a compile time phenomenon like method overloading.
Example of method overriding-
Program-
package in.blogger.tutorialsinn;
//super class
class Animal{
String sound(){
return "some sound";
}
}
//sub class
class Dog extends Animal{
String sound(){
return "barking";
}
}
Now as we have discussed both method overloading and method overriding , so now is the time to point out some differences between the two-
| Method Overloading | Method Overriding |
|---|---|
| Method overloading is a compile-time phenomenon | Method overriding is a run-time phenomenon |
| All the overloaded methods are in the same class. | One method is in super class and another is in sub class. |
| Parameters must be different in method overloading. | Parameters must be same in method overriding. |
| In method overloading return type could be same or different. | In method overriding return-type should be same |
So these were some of the basic differences between method overloading and method overriding,i hope you understood both the topics easily and perfectly.This is a very important question which is asked in interviews, specially at fresher level so be prepared.
In our next articles we will discuss some other important java topics so stay in touch.
Iterating ArrayLIst in java using for loop,while loop and Iterator
- Iterating ArrayList using while loop in java
- Iterating ArrayList using for loop in java
- Iterating ArrayList using advance for loop in java
- Iterating ArrayList using Iterator in java
package in.blogger.tutorialsinn;
import java.util.ArrayList;
import java.util.Iterator;
public class ArraylistIterator {
public static void main(String[] args) {
//creating an ArrayList
ArrayList<String> arr=new ArrayList<String>();
arr.add("java is");
arr.add("platform");
arr.add("independent");
//using while loop
int i=0;
System.out.println("using while loop");
while(i<arr.size()){
System.out.println(arr.get(i));
i++;
}
//using for loop
System.out.println("using for loop");
for(i=0;i<arr.size();i++){
System.out.println(arr.get(i));
}
//using advance for loop
System.out.println("using advance for loop");
for(String str:arr){
System.out.println(str);
}
//using Iterator interface
System.out.println("Using Iterator interface");
Iterator<String> itr=arr.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Sorting A String Array In Java
I am writing this article because sometimes it is really hard for some beginners to be aware about the complete java API and they get confused while doing such things and try to write their own code which is really painful. Program-
package in.blogspot.tutorialsinn;
import java.util.Arrays;
public class SortingStringArray {
public static void main(String[] args) {
// creating an array of string
String[] arr = { "java", "apple", "orange", "banana", "monkey" };
// using sort method for sorting arr array
Arrays.sort(arr);
// printing the values of sorted array using loop
for (String sort : arr) {
System.out.println("" + sort);
}
}
}
Though it was the simplest example of sorting , which has nothing to do more , but there are many problems on sorting which are not really easy like sorting an number array using loop,finding the longest string in an array and many more.But don't worry you will find the answers of all these problems in our upcoming articles.
Java Program For Checking A Number Palindrome
Now after knowing the definition of a palindrome number we can write our code easily.So here is the algorithm we will appy for writing the program-
- Get the user input,the number which we are going to check for palindrome, for this purpose we will use Scanner class in java
- Store that number in a int variable
- Reverse the scanned number and store it in an another int variable
- Compare the values of both int variables and print the result accordingly
package in.blogger.tutorialsinn
import java.util.Scanner;
public class NumberPalindrome {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number you want to check");
int number = sc.nextInt();
int temp = number;
// calculating length of number
int length = (int) (Math.log10(temp) + 1);
// calculating reverse number
int rev = 0;
for (int i = 1; i <= length; i++) {
int rem = temp % 10;
temp = temp / 10;
rev = (rev * 10) + rem;
}
System.out.println("reverse number is " + rev);
// checking for equality and printing result
if (number == rev) {
System.out.println("Given number is a palindrome");
} else {
System.out.println("Given number is not a palindrome");
}
}
}
Output-
Enter the number you want to check
121
reverse number is 121
Given number is a palindrome
I hope that you now understood the flow of whole program and can use your own logic for writing another palindrome program.
Java program For Checking A Palindrome
What is not a palindrome? A string like "java" is not palindrome because on reversing the sequence of its alphabet it becomes "avaj" which is different from "java". Logic we are going to apply for writing our program is this- first we will read the user input from keyboard using java Scanner class and store it in a String variable.Then we will reverse the string and store it in another String variable and at last we will compare both the strings using equals method, and print a message on the screen according to the result, and we are done. Program-
package in.blogger.tutorialsinn.classes;
import java.util.Scanner;
class Palindrome{
public static void main(String args[]) {
// scanning the user input
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string you want to check");
String orig = sc.next();
// reversing the string
String rev = "";
for (int i = orig.length() - 1; i >= 0; i--) {
rev = rev + orig.charAt(i);
}
System.out.println("reverse string is " + rev);
// checking for equality and printing the result
if (orig.equals(rev))
System.out.println("Given string is a palindrom");
else
System.out.println("string is not palindrom");
}
}
Program output-
Enter the string you want to check
civic
reverse string is civic
Given string is a palindrom
This is one of the important questions asked in java interviews as a fresher.
This was the java code for checking a word for palindrome what if someone asks you for checking a number for palindrome?
Don't worry here is the code for checking whether a given number is palindrome or not