Servlets Assignments

#1. Develop below html and Java Servlet files, which performs the below specified functionality
login.html
Servlet1.java
WelcomeServlet.java
Servlet2.java
logout.java

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:
object-oriented-assignments
core-java-assignments
applet-or-swings-assignments
basic-java-assignments

Android Photo Album Application

Below is an example, on how to develop a photo Album on Android

Activity file


import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.*;
import android.widget.FrameLayout;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {
    int count = 1;
    FrameLayout frame;
    ImageView imageview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        frame = (FrameLayout) findViewById(R.id.framelayout);
    }

    public void btn2click(View v) {

        imageview = (ImageView) frame.findViewWithTag(String.valueOf(count));
        imageview.setVisibility(View.INVISIBLE);
        count++;
        if (count > 6)
            count = 1;

        // Show next image
        imageview = (ImageView) frame.findViewWithTag(String.valueOf(count));
        imageview.setVisibility(View.VISIBLE);
    }

    public void btn1click(View v) {
        imageview = (ImageView) frame.findViewWithTag(String.valueOf(count));
        imageview.setVisibility(View.INVISIBLE);

        count--;
        if (count < 1)
            count = 6;

        imageview = (ImageView) frame.findViewWithTag(String.valueOf(count));
        imageview.setVisibility(View.VISIBLE);

    }
}

XML Layout file

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.bikash.imageviewexcelgyan.MainActivity">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:id="@+id/framelayout">

        <ImageView
            android:src="@drawable/image"
            android:layout_width="match_parent"
            android:layout_height="373dp"
            android:id="@+id/imageView"
            android:layout_gravity="center_horizontal|top"
            android:tag="1"/>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Next"
            android:id="@+id/btn2"
            android:layout_gravity="right|bottom"
            android:onClick="btn2click" />

        <ImageView
            android:src="@drawable/img"
            android:layout_width="match_parent"
            android:layout_height="373dp"
            android:id="@+id/imageView2"
            android:layout_gravity="center_horizontal|top"
            android:tag="2"
            android:visibility="invisible"/>

        <ImageView
            android:src="@drawable/imagec"
            android:layout_width="match_parent"
            android:layout_height="373dp"
            android:id="@+id/imageView3"
            android:layout_gravity="center_horizontal|top"
            android:tag="3"
            android:visibility="invisible"/>

        <ImageView
            android:src="@drawable/imaged"
            android:layout_width="match_parent"
            android:layout_height="373dp"
            android:id="@+id/imageView4"
            android:layout_gravity="center_horizontal|top"
            android:tag="4"
            android:visibility="invisible"/>

        <ImageView
            android:src="@drawable/imagee"
            android:layout_width="match_parent"
            android:layout_height="373dp"
            android:id="@+id/imageView5"
            android:layout_gravity="center_horizontal|top"
            android:tag="5"
            android:visibility="invisible"/>

        <ImageView
            android:src="@drawable/imagef"
            android:layout_width="fill_parent"
            android:layout_height="373dp"
            android:id="@+id/imageView6"
            android:layout_gravity="center_horizontal|top"
            android:tag="6"
            android:visibility="invisible"/>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Previous"
            android:id="@+id/btn1"
            android:layout_gravity="left|bottom"
            android:onClick="btn1click"/>

    </FrameLayout>
</RelativeLayout>

ImageViewAlbum
Android Photo Album App Download(on Android Studio)

Below are the screen shots, of the app

Android Simple Photo Album
Android Photo Album

Android Photo Album
Android Photo Album

You may also like to read:
permission in androidmanifest file
calculator app in android
Android difference between px and sp

This App is contributed by, Bikash Paul

Why Hibernate Query Language(HQL)?

Hibernate Query Language:
Hibernate Query Language (HQL) is same as SQL (Structured Query Language).Hibernate created a new language named Hibernate Query Language (HQL), the syntax is quite similar to database SQL language. The main difference between is HQL uses class name instead of table name, and property names instead of column name.

Advantage of HQL:-
1) database independent:
2) HQL fully supports polymorphic queries. That is, along with the object to be returned as a query result, all child objects (objects of subclasses) of the given object shall be returned.
3) HQL is suitable for executing Static Queries.
4) HQL doesn’t support pagination concept.
5) HQL is to perform both select and non-select operations on the data.

Clauses in the HQL are:
• from
• select
• where
• order by
• group by
FROM Clause:-
• String hql = “FROM Employee”;
• Query query = session.createQuery(hql);
• List results = query.list();
SELECT Clause:
• String hql = “SELECT E.firstName FROM Employee E”;
• Query query = session.createQuery(hql);
• List results = query.list();

WHERE Clause:
• String hql = “FROM Employee E WHERE E.id = 10”;
• Query query = session.createQuery(hql);
• List results = query.list();

ORDER BY Clause:

• String hql = “FROM Employee E WHERE E.id > 10 ORDER BY E.salary DESC”;
• Query query = session.createQuery(hql);
• List results = query.list();

GROUP BY Clause:
• String hql = “SELECT SUM(E.salary), E.firtName FROM Employee E ” +
• “GROUP BY E.firstName”;
• Query query = session.createQuery(hql);
• List results = query.list();

Aggregate functions are:
• avg(…), sum(…), min(…), max(…)
• count(*)
• count(…), count(distinct …), count(all…)

HQL Select Query Example:-
Retrieve a stock data where stock code is “7211”.
Query query = session.createQuery(“from Stock where stockCode = :value “);
query.setParameter(“value”, “7211”);
List list = query.list();
Query query = session.createQuery(“from Stock where stockCode = ‘7211’ “);
List list = query.list();
HQL Update Query Example:-

Query query = session.createQuery(“update Stock set stockName = :stockName” +” where stockCode = :stockCode”);
query.setParameter(“stockName”, “DIALOG11”);
query.setParameter(“stockCode”, “7211”);
int result = query.executeUpdate();
Query query = session.createQuery(“update Stock set stockName = ‘DIALOG2′” +” where stockCode = ‘7211’”);
int result = query.executeUpdate();

HQL Delete Query Example:-

Query query = session.createQuery(“delete Stock where stockCode = :stockCode”);
query.setParameter(“stockCode”, “7211”);
int result = query.executeUpdate();
Query query = session.createQuery(“delete Stock where stockCode = ‘7211’”);
int result = query.executeUpdate();

HQL Insert Query Example:-
In HQL, only the INSERT INTO … SELECT … is supported; there is no INSERT INTO … VALUES. HQL only support insert from another table. For example:

1) “insert into Object (id, name) select oo.id, oo.name from OtherObject oo”;
Insert a stock record from another backup_stock table. This can also called bulk-insert statement:
Query query = session.createQuery(“insert into Stock(stock_code, stock_name)” +
“select stock_code, stock_name from backup_stock”);
int result = query.executeUpdate();

You may also like to read:
Hibernate Mapping file
Hibernate Configuration file

Jar file creation

How to manage Sessions in Servlets

As known, HTTP Protocol is stateless, that means it does not store any session related information during the interaction between Web Browser and Web Server. HTTP Protocol just sends a request to Web Server, and receives response HTML page. But HTTP does not itself maintain any session information such as which user is currently browsing, etc…

Generally, a new session need to be created when user successfully logs in, and this user specific session data is being maintained, through out user interaction with various web pages. Finally when user logs out, the session need to be destroyed.
So it is responsibility of Server side program(like Java Servlets) to maintain session related information.

In case of Java, Servlets or JSP facilitates, to create, destroy, set and get values of Session. For this purpose javax.servlet.http.HttpSession class has been provided.

Why and when session is required

A session stores user specific data, when user is interacting with the web site. Not all the Servlets need sessions. Generally all Web sites with User login facility need to maintain session.

http-session
http-session

How to create a session: Session can be created by invoking
getSession() method in HttpServletRequest class. Below are two overloaded methods of getSession()
1.getSession(): This method has no parameters, and is always used to create new session.
2.getSession(boolean ):This method need to be invoked with true, to create a new session, and false to retrieve existing session which is in progress, and session which has been already created in previous servlets.

Below is description of few methods declared in javax.servlet.http.HttpSession
Once the session is created, below operations can be performed
1.void setAttribute(String attr_name, Object obj); is invoked to set an attribute name and value, so that this value can be retrieved[by invoking getAttribute(String attr_name) method] in other servlets

2.
Object getAttribute(String attr_name); is invoked to retrieve a value which has already been set to the session, by invoking setAttribute(String attr_name, Object obj);

Any User’s data can be stored in session, You can set and get any object in the session.
But be aware that, saving huge data in the session, may adversely affect your Web Application’s performance.
By default, session data is stored temporarily during web application’s execution and session data does not get stored persistently.
Though session data is stored on server side, it is good practice not to store confidential data in session.

3.session.removeAttribute(“attribute_name”); removes or deletes an attribute’s object from the session. You can use this method, when a specific attribute is more required. Other attributes remains intact in the session.

How to set session idle timeout

3.When no methods of session are invoked for certain period, automatically session gets destroyed.
setMaxInactiveInterval(int interval); interval in seconds

How to Destroy a session

4.When user tries to log out, invalidate() method of HttpSession is invoked to destroy the session which is in progress. After the session is destroyed, no session data is available.

Below are simple snippets, showing on how to create/destroy sessions, and how to get and put values into HttpSession.

Below is an HTML page, which invokes HttpSessionDemo servlet, when submitted.

<html>
    <head>
        <title>Session Demo</title>
    </head>
    <body>
        <form action="HttpSessionDemo">  
Name:<input type="text" name="userName"/><br/>  
<input type="submit" value="go"/>  
</form> 
    </body>
</html>

Below Servlet receives userName submitted by above html form, then creates a new session, then sets the username to uname attribute. Also provides an hyper link Visit, when clicked HttpSessionDemo1 Servlet is displayed

import java.io.*;  
import javax.servlet.*;  
import javax.servlet.http.*;  
  
  
public class HttpSessionDemo extends HttpServlet {  
  
public void doGet(HttpServletRequest request, HttpServletResponse response){  
        try{  
  
        response.setContentType("text/html");  
        PrintWriter out = response.getWriter();  
          
        String n=request.getParameter("userName");  
        out.print("Welcome "+n);  
          
        //create new session
        HttpSession session=request.getSession();
        
        //set the attribute uname to the session
        //which can be further retrieved, in other servlets
        //as long as session is valid
        //Attribute value can be of any type, since Object is expected parameter
        session.setAttribute("uname",n);  
        
        //setMaxInactiveInterval(int interval), 
        //container invalidates session, if no requests from client, for a certain time(in seconds)
  
        out.print("visit");  
                  
        out.close();  
  
                }catch(Exception e){System.out.println(e);}  
    }  
  
}  

Below Servlet is processed, when Visit hyper is clicked, this servlet gets the existing session, also gets uname attribute from session, then displays uname value. Finally destroys session and it’s data by invoking sesison.inValidate()

import java.io.*;  
import javax.servlet.*;  
import javax.servlet.http.*;  
  
public class HttpSessionDemo1 extends HttpServlet {  
  
    @Override
public void doGet(HttpServletRequest request, HttpServletResponse response)  
{
        try{  
  
        response.setContentType("text/html");  
        PrintWriter out = response.getWriter();  
          
        //retrieve existing session, hence false parameter is sent
        HttpSession session=request.getSession(false); 
        
        //retrieve the attribute uname, from the session
        String n=(String)session.getAttribute("uname");  
        out.print("Hello "+n);  
  
        //invoke removeAttribute() if you want to remove any attribute
        //stored in the session
        //session.removeAttribute("attribute_name");
        
        //use invalidate method to completely destroy current session
        //so that it doesn't exist any more
        session.invalidate();      
        
        out.close();  
  
                }catch(Exception e){System.out.println(e);}  
    }  
      
  
}  

However, for database backed sessions, may be more useful when a web application is deployed across multiple servers, and client requests are managed by Load Balancer.

You may also like to read:

How to use multiple Servlet Filters
How many implicit java objects are there in JSP
Servlet Life Cycle

JavaScript How to access DOM of an HTML Page

As known JavaScript is one of the powerful Scripting language, which gets interpreted on Web Browser. Basic usage of JavaScript is
#1.Client side validations.
#2.To perform dynamic operations on an Webpage.

Disadvantage part of JavaScript is, it can be manually disabled by user, on his/her Browser.

Below are few examples

Change color of a button periodically

Below is sample JavaScript code to dynamically change background color of button for every one second. However this approach can be used for any HTML elements, and time interval also can be changed as required.

<html>
<head>
<title>Button with dynamic Random color</title>
<script type="text/JavaScript">
window.onload = function() {            
    function rndBtnClr() {
var rndColor = '#' + (Math.random() * 0xFFFFFF << 0).toString(16);

document.getElementById("btn").style.background=rndColor;
//get the reference of the Button, and set its background color

    }
    setInterval(rndBtnClr, 1000);
}
</script>
</head>
<body>
Can you observe dynamic random color, for below button.<br>
<input type="button" value="Click Me" id="btn" />
</body>
</html>

rndBtnClr() method is invoked every one second(i..e 1000 ms). Six digit hexadecimal random color is being generated by below line.

var rndColor = ‘#’ + (Math.random() * 0xFFFFFF << 0).toString(16);

The same in considered as DHTML(Dynamic HTML)

Dynamically enabled or disable a HTML element

Below javascript enables or disables a button, by clicking Click Me button.

callme() function is clicked whenever “Click Me” button is clicked.if condition checks if the button is currently disabled, if button is currently disabled, then button is enabled, else button is disabled.

<html>
<head>
<title>Enable/Disable an HTML element, dynamically</title>
<script type="text/javascript">
function callme(){
if(document.getElementById("btn").disabled)
{
document.getElementById("btn").disabled=false;
}
else
{
document.getElementById("btn").disabled=true;
}
}
</script>
</head>
<body>
Can you observe dynamic random color, for below button.<br>
<input type="button" value="Click Me" onclick="callme()"/>
<input type="button" value="Enabled/Disabled button" id="btn" />
</body>
</html>

You may also like to read:
List of input controls in HTML
HTML marquee tag example
favicon for a website

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)
		{
			System.out.println(item);
		}
	}
	
	
	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?

Solution:

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){
        this.radius=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);
obj.getDiameter();
obj.getcircumference();
obj.getarea();
    }
}

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

Difference between ServletContext and ServletConfig

A Web application can have any number of Servlets. ServletConfig is specific to a single Servlet, where as ServletContext is common to all servlets in a Web application.

Similarities of ServletContext and ServletConfig

1.Both ServletContext and ServletConfig belong to javax.servlet package.
2.Both are required to provide Initialization Parameters to a Web application or Servlet. Initialization parameters need to be provided thru Deployment Descriptor file i..e web.xml
3.Both provide getInitParameter(“parameter-name”) method, to get Initialization parameter.

Difference between ServletContext and ServletConfig

1.Both differ in scope. ServletContext is common to entire Web Application, where as ServletConfig is specific to a servlet.
2.As shown in Servlet Life Cycle ServletConfig is received as parameter to init() method of Servlet Life Cycle. Also, getServletConfig() method can be invoked to get an object of ServletConfig.
3.getServletContext() method can be invoked, to get an object of ServletContext.
4.As shown in below examples, <context-param> element specifies ServletContext initialization parameters. But <init-param> with in <servlet> , specifies ServletConfig initialization parameters.

Why to use Servlet initialization parameters

Instead of hard-coding that parameter in java source code, declaring it in web.xml has the advantage of being able to change it from time to time.

In general the same is true for all settings, for example timeouts, database username, password, database host,etc…

Another advantage of init parameters in web.xml is, all such values are available in a single file, web.xml making maintenance easier.

ServletContext example

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <context-param>
    <param-name>blogname</param-name>
    <param-value>java652.com</param-value>
</context-param>

    <servlet>
        <servlet-name>NewServlet</servlet-name>
        <servlet-class>NewServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>NewServlet</servlet-name>
        <url-pattern>/NewServlet</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletContext;

public class NewServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            ServletContext sc = getServletContext();
            
            String nam = sc.getInitParameter("blogname");
            PrintWriter pw = response.getWriter();
            
            pw.println("Parameter Value is: "+nam);
    }
}

ServletConfig example

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <servlet>
        <servlet-name>NewServlet1</servlet-name>
        <servlet-class>NewServlet1</servlet-class>
        
        <init-param>
        <param-name>myParam</param-name>
        <param-value>xyz</param-value>
        
        </init-param>
        
        <init-param>
        <param-name>myParam1</param-name>
        <param-value>abc</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>NewServlet1</servlet-name>
        <url-pattern>/NewServlet1</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

public class NewServlet1 extends HttpServlet {

	public void init(ServletConfig config)
	{
            System.out.println("Am from Init method...!");
            String param_val = config.getInitParameter("myParam");
            System.out.println("Param Val:"+param_val);

            String param_val1 = config.getInitParameter("myParam1");
            System.out.println("Param Val1:"+param_val1);

            //to get enumeration of parameters
            Enumeration enm = config.getInitParameterNames();
	}
    

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        //another way of getting ServletConfig
        ServletConfig sc = getServletConfig();
    }

}

In Servlet 3.0 version Annotations can also be used in java source code to set init parameters, as shown below

@WebServlet(name = "HelloServlet" , urlPatterns = { "/HelloServlet" }
    , initParams = { @WebInitParam(name = "city" , value = "New Delhi") })

In case the value is fixed forever, and it need not be changed, declaring it in java source code, also can be an option.

You may also like to read:
Java Servlet Life Cycle
How many Filters can be used for a Servlet
How many implicit objects in JSP

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
ab
abc
abcd
abcde
abcdef

(iii)a
b
c
d
e
f

(iV) a
b
c
d
e
f

(V)a f

b e

cd

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 java.io.SequenceInputStream. 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