Servlets Assignments

#1. Develop below html and Java Servlet files, which performs the below specified functionality

When successfully logged in, forward to Welcome Servlet. When failed to login, include login.html.
WelcomeServlet need to start a new session, and store username in Session attribute.
Display username(from session) in all Servlets.
Provide hyper links to display a Servlet from any other Servlet.
Destroy session, when logout link is clicked. logout link need to be displayed in all Servlets.

If you try to open any servlet directly from url, without logging in, it need to display a message, “login to continue”.

#2. In the above problem, try to add session time out functionality, i..e when user does not send a request for 3 mins, session need to be timed out, and automatically destroyed.

#3. In Servlets RequestDispatcher, from processing servlet try to include two other resources separately, ensure that response received by Browser has output from Processing Servlet, and other two included resources as well.

#4. Try to retrieve Servlet Context initialization parameter values( from the deployment descriptor, web.xml) and print them. In the same web app, try creating another servlet, which can access same Servlet Context initialization parameters.

#5.In Servlet RequestDispatcher, from Processing Servlet, forward the request to some other Servlet, and this some other servlet need to include another resource(an HTML or Servlet)

#6.Use HttpSession to find number of seconds spent by user on each page. Update the details in database table.

#7.Use Cookie and display html page to user, and let user select his/her own back ground color, from drop down options provided in the html page. When user visits the page again later, the background of html page need to be the color which has been selected by user, in earlier session. Validity period of cookie can be one week.

#8. Write a Filter for a Servlet or JSP, which removes Parameters with certain name in the request.

#9. Write a Servlet1, which forwards request to other Servlet2. Servlet1 need to adds few parameters which can be retrieved and displayed by Servlet2.

#10. Write a Servlet, which has login and signup functionality. MySQL database can be used, to store login details. User Account need to get locked for 1 day after three unsuccessful login attempts due to wrong password.

#11. Write a Servlet, and using HttpSessionListener try to get total number of currently logged in to the site.

#12. Use JSP/Servlet to develop Shopping Cart.

#13.Use JSP/Servlet to develop simple Payment Gateway.

#14. Generate PDF Bill using JSP

#15.Use AJAX to validate each field in Signup Form, and display error if an entered value is invalid, and display error beside respective field if its value is invalid.

You may also like to read:

Array as parameters

Hope you already gone thru basic of arrays.
An array can be sent as parameter to a constructor or a method. Also an array can be returned by a method.
Below example shows the same.

class Student{
	int marks[];
	Student(int m[])
		marks = m;
	private int getTotal(){
		int sum = 0;
		for(int i=0;i

Below is an example showing a method returning an array.

public class StudentProgram {
	public static void main(String arg[])
		int gmp[] = getArray();
		for(int item:gmp)
	private static int[] getArray()
		int smp[] = {45,64,53,26};
		return smp;

You may also like to read:
array example
how to sort an array in java

Package and interface example

Assignment Problem:
Create a class named Circle which can take radius as constructor parameter, and has methods which calculates and returns diameter, circumference and surface area. Write another class named MainCircle, which has main method, and creates an object of Circle, and invokes all methods of Circle class, and print the return values?


package p2;

public interface ICircle {
public final float pi=3.14f;
   public float getDiameter();
   public float getcircumference();
   public  float getarea();    
package p1;
import p2.ICircle;
public class CircleImpl implements ICircle{
        float radius;
    public CircleImpl(float radius){
    public float getDiameter(){
        float diameter=2*radius;
        System.out.println("The diameter is: "+diameter);
        return diameter;
    public float getcircumference(){
        float circumference=2*pi*radius;
        System.out.println("The circumference is: "+circumference);
        return circumference;
    public float getarea(){
        float area=pi*radius*radius;
        System.out.println("The area is: "+area);
        return area;

Below is main method, which creates object of CircleImpl class, and invokes its methods

package p3;
import p1.CircleImpl;
public class MainCircle {
    public static void main(String[]args){
CircleImpl obj=new CircleImpl(3f);

Click here to download this code, on Eclipse
You may also like to read:
What is a package
What are access specifiers

Object oriented Assignments

1. Create a class named Circle which can take radius as constructor parameter, and has methods which calculates and returns diameter, circumference and surface area. Write another class named MainCircle, which has main method, and creates an object of Circle, and invokes all methods of Circle class, and print the return values.

2. Create a class named Rectangle, which can take width and height as constructor parameters, and has methods which calculates and returns perimeter, area, diagonal length od rectangle. Also expose a method which returns false if square, else true. Write another class MainRectangle, which creates object of Rectangle, and invokes methods, and prints return values.

3. Repeat above problem 2, with Rectangle in package com.p1, and MainRectangle class in package com.p2. Explore by making constructor and methods of Rectangle, as default and public Access Specifier, and observe.

4. Create an interface ICircle, which declares a constant PI with 3.14 value, and declares methods which returns diameter, circumference and surface area. Write a class CircleImpl which implements ICircle, and defines all methods of ICircle. Write another class named MainCircle, which has main method, and creates an object of CircleImpl, and invokes all methods of Circle class, and print the return values.

5. Repeat problem 4, with ICircle interface in com.p1, CircleImpl in com.p2 and MainCircle in com.p3.

6. Write a program in Java that inputs a long sentence or paragraph from user into a String and then displays how many times each alphabet appears in that string. How many spaces, full stops and commas are there in the string? Assume upper and lower case letters as same like A and a are considered to be as same character. In the end calculate and display the percentages of occurrence of each character. Also display the total number of characters in the string.

7.Write a class RectCoor, which has constructor taking width and height of a rectangle as parameters. Expose a set method, to receive starting x and y coordinates of the rectangle.Expose three more get methods, which prints each of the three rest of the co ordinates.

8.Repeat above problem by having a different class to represent a single coordinate. set method need to take parmeter, and get emthods need to return object of coordinate class.

9.For a given number(say i), find the multiple of 5, which is just less than i, and which is just greater than i. For example, if the number is 23, then output should be 20 and 25

10.A student class, which has an array that stores, marks in 5 subjects. A student class also has student name, age, etc…Create 10 objects of such student class, with sample data. Store these 10 objects in an array. Provide methods to print student names in alphabetical ascending order. Compute avg marks of each student and print in ascending order of avg marks. Print the least mark scored by student. Display ranking order and student name, based on total marks.

11.Print two dimensional arrays, in column major order i..e print first column numbers, then second column,etc…
12.print two dimensional array elements diagonal wise, starting from left(consider no. of rows are same as number of columns)
13.print two dimensional array elements diagonal wise, starting from left
14.print maximum element of elements stored diagonally, in an array
15.Write a class, which has a constructor accepting int array as parameter, also declare an array as data member. Write methods to find total, avg, max, min of array, also method to return the array. From main method create an obejct of the class, and invoke the methods.
16.Write a program, to print total of each row elements, of a two dimensional arrays.
17.Program to find max and min element in a two dimensional array.
18.Write a program to find how many times each word occurs, in a sentence. At end of program print each word along with number of times it appears in the sentence.
19.Write a program, with a class, with a method which can take two arrays(say arr1 and arr2) as parameters, and creates and returns third array(say arr3) with the elements of two arrays, such that all even elements are from arr1, and odd elements from arr2. In case arr1 and arr2 are of different lengths, then remaining elements of any array need to be put in arr3.
For eg. arr1 is {23,21,45,38}, and arr2 is {49,93,96,66,53,86,54}. Then arr3 need to be {23,49,21,93,45,96,38,66,53,86,54}

20.Write program to convert String to a InputStream

21.Write a program with two threads, initialize a String. Each thread need to display exactly one character in the String, and then goes to wait() after notifying second thread by invoking notify(). After second thread prints one character, it goes to wait(), after notifying First thread. This is done until all characters in the String are printed.

22.(a) Write a program to extend an interface.
(b) Can Generics be used with an interface? Can you give examples of in built interfaces using Generics, like Comparator,etc…

23.Create a jar file, which has a class exposing add, sub, mul, div methods. Create a project, to which add the above jar file. Create a class with the main method, load the class, which is in jar file. Now invoke the methods add, sub, mul and div classes.

24.Combine 4 input streams, into a single input stream, read data from combined input stream, and write to a file, while writing to a file ignore the words mango.

25.Develop a command line zip tool, which compresses all the files and folders in a specific path.
usage: myzip -p path -e .txt
path can be absolute or relative path
.txt is the extension of files which need to be zipped, remaining files with other extensions will not be included in zip file. Also assume that there is no possibility, to specify multiple extensions

if -e is not provided, then all files and folders in the specified path are zipped

26.Implement Download manager, to download a file.
mydm -d url_of_file -p dest_path
-d: url of file which need to be downloaded
-p: specify local path to where file need to be downloaded
Display error, if no network, or if url provided is not valid

It should be to Pause or Resume download.

27.Create Shape class, which exposes draw() method. Create the sub classes Rect, Square, Circle, which are sub classes of Shape. From the main method, create objects of different sub classes, which are referred by Shape class reference. Observe overriding of methods.

28. Write a program to print a String “abcdef” in below format
(i) fedcba

(ii) a


(iV) a

(V)a f

b e


29.Please create a Message Queue, and Four Threads, A, B, C and D. Thread A puts a string into Message Queue, and invokes Threads B,C and D. Thread B reads from Message Queue and displays to console, Thread C reads from Message Queue and displays reverse of actual String, Thread D reads from Message Queue, sorts each character of String, and displays. Hint: use wait() and notifyAll() methods.

30.Develop a Program, for a singleton, which is synchronized.

31.Write a Program, which computes an expression like 2+3*8/56-12
Hint: use Stack in Collection, to compute expressions

32.Display a swing window, and display a String, by blinking periodically, and display String in Random color, each time.

33.Develop MySequenceInputStream which extends from MySequenceInputStream need to provide below functionality, should allow to combine multiple InpuStreams into a single InputStream, and it should be possible to specify a String which should occur between each InputStreams, which are being combined into a single InputStream.

34.Write program to find if a given year is leap year?

35.A rectangular iron sheet with width 20, and height 15, need to be cut into small rectangular sheets of width 6 and height 7.5. How many pieces can be made, and what is the wastage. Write a program, which can take different dimensions, and prints the number of small rectangle sheets, which can be cut from big rectangular sheet?

Core java assignments
Core Java Assignments 2
Applets and Swings Assignments

for loop examples

Hope you had already gone through loops in java to get basic understanding of loop in Java.

Below are few examples which will make you hands on, and make you aware real use of loops. First let us consider solving below problem.

For loop example problem: Take two different arrays each of size 10. Concatinate each number of first array with each number of second array, and display each combination. Hint:Output generates 100 different numbers.
Solution: First declare & initialize two array a and b. Now each number of first array need to be concatinated with each number of second array. We need two different for loops, one to iterate thru first array, another to iterate thru second array. However, these two loops need to be nested, i..e outer for loop iterates thru first array, inner for loop iterates thru second array.

public class LoopExample{
public static void main(String args[])
int a[] = { 23,54,89,14,83,5,29,3,93,32};
int b[] = { 21,43,26,19,3,8,25,2,8,24};

for(int i=0;i < a.length;i++)
for(int j=0;j < b.length;j++)
String tmp = a[i]+""+b[j];

Also this problem can be solved using while loop or do while loops.

Another Problem: Repeat above problem, but print only the numbers which are multiples of 3.
Solution: As shown above, after the number gets created, it is in String format, to convert it to int, use Integer.parseInt() method, Further check if it is multiple of 3, using modulo operator.

public class LoopExample{
public static void main(String args[])
int a[] = { 23,54,89,14,83,5,29,3,93,32};
int b[] = { 21,43,26,19,3,8,25,2,8,24};

for(int i=0;i < a.length;i++)
for(int j=0;j < b.length;j++)
String tmp = a[i]+""+b[j];
int val = Integer.parseInt(tmp);

Note that each iteration does not create any entry on the Stack, but a method call creates an entry in Stack. For more details, refer what is stack memory and when an entry is added to stack memory
You may also like to read:
Core Java Interview Questions
List of Operators in java
Java Interview Questions
What are Wrapper classes
More for loop examples

Core Java Assignments

1. Create two String objects and assign with different strings. For eg.
String str1=”Hello”;
String str2=”mayi”;

Write a program to create a new String object, as odd characters for str1, and even characters from str2
Considering above example: output: Hmealylio

2.Take six different one digit integers. output the largest integer that can be created, by combining these six integers. NOTE: six digits can be same or different

3.Two dimensional arrays(with same number of rows and columns), each element stores an object of below class

class Abc{
int i;

Write a program to change rows to columns, and columns to rows.

4.serialize employee objects, and write a client which serializes employee objects to OutputStream, of a socket. Receive the object stream, at the server, and write to a file.

5. Take some String as below
String str=”Hello, how are you? Can you come here?”;

create two child threads, from main thread. Each child thread prints one character at a time. But the thread need to be locked until it completes printing the word. Hint: you can use synchronized method or block.

6. For a given integer value, for eg. 4823, print it in words, like four thousands, eight hundreds and twenty three.

7. Find transpose a matrix of given number of rows and cols?

8. multiply two matrices, and generate third matrix?

9. print factorial of a given number, using recursion?

10. Ask user to enter a name, if name is numeric, then throw NotaNameException. Create your own Exception called NotaNameException

11. Declare and initialize an array of size 5, each element can be any number between 0 and 9. Print each element in string equivalent with comma separated.
For eg. int arr[]={4,2,5,1,6}; need to print four,two,five,one,six

12. Billing amount is entered by shop keeper. If the bill amount is less than 5000, give 5% discount.
If bill amount between 5001 and 10000, give 8% discount.
If bill amount between 10000 and 20000, give 10% discount.
If bill amount between 20001 and 50000, give 15% discount.
If bill amount is greater than 50001, give 18% discount.

In all cases compute, the result bill amount, after giving discount.

13. Declare an array of Object elements. Store objects of different types in the array. Fetch each element(which is an object) from array, and print object’s class name, methods available, etc… by using Reflection.

14. A String is provided in the format 19,8,23 . Write a program to extract integers, check if these numbers occur in sequential order.

15. Declare an array of odd length. In this array swap only elements with even index.

16. Write a program to print a String “abcdef”
(1) fedcba
(2) a

(4) a
(5)a f

b e


17.Write a program to convert a decimal number to binary form, and print.

18.Write a program to convert a decimal number to octal form, and print.

19.Write a program to print multiples of 3 or 5 between 1000 and 1050.

20.Write a program to print multiples of 23 between 2000 and 1000, in reverse order.

21.Write a program to print all numbers having same digits between 10 and 999. For eg. 22 or 555,etc…

22.Display all prime numbers between 1 and 100. Note: A Prime number is a number whcih is divisible only by 1 or by itself. Eg. 3 is prime number.

23.Write a program to print all numbers, which has sequence digits, for eg. 234, 678, 1234, which are between 10 and 1000.

You may also like to read:
More Core Java assignments
Core Java assignments

Frequently asked Project interview Questions

Applet or Swings Assignments

1. Write a simple Applet to display your name as a Banner, that is scroll your name right to left. Scroll by one character at a time. A Thread may be used for smoother scrolling effect. You can use Thread.sleep() to cause delay, in scrolling.
2. Repeat above 1. assignment, except scroll two characters at a time
3. Repeat above 1. assignment, except scroll in opposite direction, i..e from left to right.
4. Repeat above 1. assignment, except scroll one word at a time, instead of one character at a time.
5. Develop an Applet with textarea and button. Which some Text is filled in textarea, the text content need to be save to file, when button is clicked.
6. Develop windows explorer kind of utility, using which user can explore, files/folders stored in file system.

You may also like to read:
Core Java assignments
Basic Java assignments

Core Java assignments 2

Below are few assignments on Core Java, which you can try out

1.Swap Numbers Without Using Third Variable Java Example*
2.Java program to find Palindrome Number or not. For eg. 12321 is palindrome, and 124869 is not palindrome
3.Program to create an outer and inner classes with some methods and then create an two objects to access both the methods in innner and outer class.
4.Write a program that shows how to access the private members of a class using inner class.
5.Program to create enum class in java
6.Write a Java program by using BufferedReader class to prompt a user to input his/her name from keyboard and then the display output, until done is given as input.(Hint use any loop)
7.Write a program in Java to print Fibonacci series up to given number? Write both iterative and recursive version
8.write a Java program to calculate factorial of an integer number ? Both iterative and recursive solution.
9.Write a program to extract each digit from an int. For example, if the int is 86543, the output shall be 8,6,5,4,3.
Hints: Use n % 10000 to extract first digit, and n = n / 10000 to remove first digit, and continue with this process, to get each digit.

10.Write a program to read an int, a float, and a String in text file called “abc.txt”, and output in below way
integer read is 12
decimal number read is 33.44
String read is “Hello”

11.Write a program to reverse an input String. For example:
Enter input String: wxyz
Reversed String is: zyxw

12.Write a program to print fibonacci series less than 100?

13.Write a program to print, if given number is armstrong number. For example 371 is armstrong number because 3*3*3+7*7*7+1*1*1 = 371

14.When a given string Hello, output need to be printed as H l o
That is only odd characters need to be printed, space need to be printed for even characters.

15.Explain difference between Compile time polymorphism and run time ploymorphism

16.Write program to display Greatest Common Factor, of given numbers.

17.To a TreeSet, add Employee objects, with below fields/data members
employee name, salary, age, department.
Store the employee objects in ascending order of salary. Get all employees with salary greater than 15,000
Hint:Use Comparator or Comparable interface

18.Repeat assignment 17, with descending order of salary.

19.Use 4 threads along with main thread to display each character of a given string. For eg. if “Hello, How are you” String is given, output can be something similar as below.
Thread 1: H
Thread 3: e
Main Thread: l
Thread 2: l
Thread 1: o
Thread 2:
and so on…..

20. Develop
(a) RMI Server object exposing methods, taking radius as parameter, and returns diameter, circumference, surface area,etc…
(b) Develop RMI Client which can lookup to above RMI Server object, and invoke the methods.

21. Develop a circular linked list, by implementing List interface.

(a) RMI Server object exposing a method, taking Collection of City objects as input parameter.A city object can have below fields city name, temperature. RMI Server object need to find average of temperatures in all City objects.
(b) RMI Client object, which can look up and invoke above method.

23. Simple Client and Server. A Client sends int or float to Server. Server need to multiply with 10, and send result back to Client. Client need to display final value.

24. Develop a console based Server and Client. Client need to send commands like current directory, change directory, list files & file properties(like modified date, etc…). Server program need to provide above details, when requested by client.

25. Implement a simple Web Server, which receives request, and serve the requested file, to the Client.

26. Develop a simple console based chat broadcast client, and chat server, using socket programming. Chat server need to serve multiple chat clients. Whenever a client sends a message, the message need to be received by all the chat clients running currently.

27. Can I pass array as parameter to a constructor?
Can an object be declared as static data member.Can u give an example of it, from built ib classes?

28. A method which can take any number of one dimensional arrays, write a program, then create and return an array, which removes duplicate elements.

29. Write program to take non english characters from keyboard, and print them.

30. Can we make a constructor synchronized?

31. Assume that sorted order of alphabets are different, which can be given as input. Given a String arrange characters of this String in customized alphabetical order?

32. What is the difference between Scanner and BufferedReader

33. How to convert Reader to InputStream, and viceversa?

34. What is the output of below program?
package p1;

class Alpha extends Beta{


class Beta extends Teta{


class Teta extends Alpha{


public class Misc1 {
public static void main(String[] args) {
Teta ot = new Teta();
System.out.println(“Everything works fine”);

35. A client program, having two threads, at atime only one thread can send a request to a server program. When one client thread is in the process of sending request, and if other client thread wants to send request, then it need to wait, until first thread completes sending request to server. Note that, the two client threads, can execute simultanesouly, but only one thread can interact with server at a time.

36. In InputStreams what is the purpose of mark and reset?

37. What is chain of responsibility Design Pattern?

38. Advantage of Facade Pattern?

39. Lets assume there is a framework, which is released to App developers. How do you ensure that old Apps are not affected with newer versions of Framework? i..e how do you take care of backward compatibility of already developed Apps, even though underlying components of framework may change. which design patterns do you suggest?

40. A program which receives an input thru network socket, based on the string received, a specific observer need to do some processing. All this can be performed with one thread.

There can be multiple observers, each of which can do one of the following
a. which reverses string
b. which replaces some character in string
c. which concatenates string

Hint: use Observer and Observable

41. Repeat above problem, by using separate thread for each Observer, and perform some long processing in each Observer thread.

42. Solve the same above problem using wait() notify()

43. Create a vehicle class, with below data members

String make_and_model;

String registration_number;

String registration_date; //in format dd-mm-yyyy

You can add appropriate constructor, setter & getter methods to above class. Then create about 10 objects of above class, with different values of data members. Now add these objects to a TreeSet, and ensure that the objects in TreeSet are arranged in ascending order of registration_date.

NOTE: use Comparator interface

44. Print your name 10 times, without using a loop. NOTE: use method recursion

You may also like to read:
Basic Core Java Assignments 1

Basic Java Assignments

Below are few Java assignments you can try to develop programs, and get more confidence in Java.
1a. Declare one dimensional array of primitive integers, of size 20.
Write a program to reverse the elements of array, and print reversed array.

1b. From a given integer, extract each digit, and display each digit. NOTE: integer can have any number of digits(ofcourse within integer range)

1c. Display all numbers between 1 and 40, except number, which is multiple of both 2 and 3.

2.Declare two dimensional arrays of primitive floats, with 6 rows and 8 columns.
Write a program to exchange row and column numbers, and print the final elements in rows and columns.

3.Write a class, with a method public void show(), and print Hello World message from this method.
In main method create object of above class, and invoke show() method.

4.In addition to above Assignment 3, add a default constructor[print message in constructor body] to the class.
In main method create object of above class, and invoke show() method. In output observe the order in which the messages are printed.

5.Write a class(say class A) with few data members, and methods.In another class write below methods which
a.takes object of class A as parameter,
b.create object of class A and return the object.

6.Method overload: write a class with 4 methods named add() with different number and type of parameters.add() methods need to return added value of parameters.
From main method invoke the 4 add() methods, get the return values, print them.

7.Write a class with four static methods(add, , each accepting 2 parameters )computes mathematical operation and prints the result.Invoke these static methods from main method.

8.Write a program with all usages of this keyword.
For eg. this(), this. , this

9.Invoke static method, and use static data members from another static method.
Also invoke non static method, and use non static data members from a static method.
observe the difference…

10.Serialization:Write an Employee class with id,name, father name, photo url as data members. use transient keyword for photo url. Serialize the object of Employee class and de serialize it. print data members of de serialized object.

11.Open file using FileInputStream, read one line at a time from file, and print lines on console.
Hint:use BufferedReader

12.Use SequenceInputStream, to combine input from four different files, and write all the content to fifth file.

13.Create a class with 2 data members of any type, along with get and set methods. Then declare an array of this class type, and store objects in the array. Now iterate(using for loop) through each object in array, print object details with get method. main method throw an exception, using throw keyword, catch the exception using catch block. In catch block, further throw the exception.Hint: use throws keyword also

15.Which is base class of all classes in Java?

16.Write a class which inherits from String class, observe it.Also try to inherit from StringBuffer, Integer, Float, classes also.

17.Write a program for Nested try blocks, and observe the execution flow.

18.In Collection, what is difference between Object based Collection and Generic version Collection? What are the scenarios in which each of them are preferred.

19.What is output of below program

public class Test{
    void sum(int i,int j)
        int k=0;

    public static void main(String args[])
        Test obj = new Test();
Ans: Exception in thread "main" java.lang.StackOverflowError occurs
20.Using printStackTrace(), get the stack trace into a String, instead of printing to console
21.There is a file with some data as shown below

f1,f2 means f1 is friend of f2, and so on. Write a program to read contents of this file and remove duplicate entries, and write non duplicated entries to another file.

22. Is it possible to change the current object to which this is reference? In other words, is below statement  valid in Java
this = new Xyz();//Xyz is some class

23. A two dimensional Array with 4 rows and 5 columns, and type float. Add elements of each row, display total and average of each row.

Servlets interview Questions

  1. Using Servlets develop page view counter, count value can be maintained in database. Use cookies to find unique visits to the web page
  2. JSP write Filter, with a specific url pattern. And check that Filter need to get invoked only when request url matches the pattern
  3. Write a Filter, for JSP, which checks the ip address from where request has originated, return without processing request if the request ip address is in a specific range
  4. On webpage provide option to select background color of the page, store this back ground color in cookie. Later, when user displays the cookie value(background color), to display the webpage with selected back ground color
  5. Create custom JSP tag, use this custom tag in your JSP code

You may also like to read:
Core Java Assignments 1