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 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

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

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

Differences between Stack and Heap Memory in Java

Stack is a type of temporary memory used by JVM ( Java Virtual Machine ) to store local method primitives variables, and method calls information.

Whereas in Heap is a type of memory used by JVM ( Java Virtual Machine ) to store references of objects (regardless where they are created) and String Pool.

Stack and Heap both are stored in the computer’s RAM (Random Access Memory).


Differences between Stack and Heap memory in Java

 Here are few differences between stack and heap memory in Java:

1) The main difference between heap and stack is that stack memory is used to store local variable and function call, while heap memory is used to store objects in Java. No matter, where object is created in code e.g. as member variable, local variable or class variable, they are always created inside heap space in Java.

2) If there is no memory left in stack for storing function call or local variable, JVM will throw java.lang.StackOverFlowError, while if there is no more heap space for creating object, JVM will throw java.lang.OutOfMemoryError .

3)  Each Thread in java has their own stack memory which can be specified using -Xss JVM parameter, similarly you can also specify heap size of Java program using JVM option -Xms and -Xmx where -Xms is starting size of heap and -Xmx is maximum size of java heap.

4)  The size of stack memory is very small as compared to that of heap memory in Java. The heap memory size is quite bigger than that of stack memory.

5)  The stack memory is kind of private memory of Java Threads, while heap memory is shared among all threads. In other words stack memory is not shared between multiple threads. Each thread will have its own stack memory while heap memory is shared between multiple threads, so each thread can get reference of any object.

6)   The garbage collection is not performed in case of stack as once a function call runs to completion; any data on the stack created specifically for that function call will automatically be deleted. In case of heap garbage collection is performed by the JVM (Java Virtual Machine) once all references for any object are null.

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.

14.in 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