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

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

Array example in Java

Hope you had already gone thru Arrays in Java to get basic understanding of arrays.

Now, let us solve a simple problem using Arrays.
Arrays Problem: Write a class which has Constructor, taking marks of students as parameters. Expose methods to return max marks, min marks, avg marks, number of students scored more than 60, number of students scored less than 60.

class Student{
	private int marks[];
	
	public Student(int marks[])
	{
		this.marks=marks;
	}
	
	public int getMaxMarks()
	{
		int max = 0;
		
		for(int i=0;i < marks.length;i++)
		{
			if(marks[i] > max)
			{
				max = marks[i];
			}
		}
		
		return max;
	}
	
	public int getMinMarks()
	{
		int min = 999;
		
		for(int i=0;i < marks.length;i++)
		{
			if(marks[i] < min)
			{
				min = marks[i];
			}
		}
		
		return min;		
	}
	
	public int getAverageMarks()
	{
		int avg = 0;
		
		for(int i=0;i < marks.length;i++)
		{
			avg+=marks[i];
		}
		
		avg /= marks.length;
		
		return avg;
	}
}

public class Cond{
public static void main(String args[])
{
	int st_marks[] = {36,94,83,42,35,86,65,91};
	
	Student obj = new Student(st_marks);
	
	System.out.println("Max Marks:"+obj.getMaxMarks());
	
	System.out.println("Min Marks:"+obj.getMinMarks());
	
	System.out.println("Avg Marks:"+obj.getAverageMarks());
}
}

Note: Finding number of students scored less than 60 and more than 60 is left out, for you to work on.

Hint: To get number of students less than 60, use for loop, and in each iteration increment counter, if the mark of a student is less than 60, and return the counter value. Similarly find number of students scored greater than 60.

You may also like to read:
How to write a class in Java
Loops examples
What is purpose of Constructor