MKP (PCIT4303) JAVA 5 IT 68 Java Assignments
MKP (PCIT4303) JAVA 5 IT 68 Java Assignments
1. Write down Java statements to declare a double variable salary with the initial value 17000.0,
an boolean variable bold with no initial value, and an int constant NUM_WHEELS with the
value 4.
2. The body mass index (BMI) of a person is defined as the ratio of body mass in kilograms to the
square of body height in meter. For example, a person of 1.8m tall with weight 55kg has BMI
55/(1.8)2 = 16.975308641975307. A person with BMI between 20 and 25 is considered to have
a healthy amount of body fat. A person with BMI of less than 20 is regarded as underweight,
and one with a BMI of more than 25 is regarded as overweight.
Write a program to calculate the body mass index (BMI) of the user. Ask the user for their
height and their mass. Allow the user to enter both in inches and meters, and both in pounds
and kilograms. Also output the meaning of the BMI.
Note that 1kg = 2.2lb, and 1in = 0.0254in.
Example input/output:
What is your weight? 55
In lb or kg? (1=lb, 2=kg) 2
What is your height? 1.8
In in or m? (1=in, 2=m) 2
Your BMI is 16.975308641975307.
You are underweight.
3. Write a method that takes a number between 0 and 9 as an argument and prints the number
as a word on the screen.
4. Write a method that takes a number between 0 and 9 as a parameter and returns the number
as a string from the method.
5. Write a method that takes a number between 0 and 9 as an argument and prints on the screen
“Number green bottles standing on the wall” (where Number is replaced by the word version of
the number). If the numeric parameter is 1 then your method should print bottle rather than
bottles.
Control Statements
1. A secret code encrypts a message by putting it in an array and reading down the columns
(blanks are replaced by asterisks and full stops are added to fill up the array). Write a program
that encrypts an input string. (For extra marks write a program that decrypts a given string
using the rules outlined above.)
LETS*G
O*TO*T
HE*SAN
DWICH*
SHOP*T
ODAY..
Example:
Input: “Lets go to the sandwich shop today”
Output: “Lohdsoe*ewhdtt*ioasoscpy**ah*.gtn*t.”
2. To sort a list of integers using selection sort.
3. Given 2 arrays A & B of integers, which are unsorted, write a program to merge them into a
single sorted array C that contains every item from arrays A & B.
Class
1. Write a class called Account with following attributes name, accountNumber, balance,
address. Use appropriate data types for these attributes. Use access control to prevent direct
access of these attributes from outside the class. Write methods that allow you to read these
variables and also change them (if change is permitted). Write another class called
AccountDemo and instantiate an object of Account class. Test your methods and print values
eg: String getName( ) & void setName(String name) create all the methods following the above
naming convention
2. Create a class called Calculator and write another class called CalculatorDemo (contains
main method). Provide support for following methods in the Calculator class Prototypes:
int add(int , int) ; int substract(int, int); int multiply(int, int); int divide(int, int);
Create an instance of Calculator and then invoke the above methods from CalculatorDemo.
3. Declare a variable Student which consists of a person's name, mark for Programming, for
Logic and a grade for Lab. A mark is a number (between 0 and100) and a grade is a letter
(between A and F). Write a predicate (a boolean method) isStronger, which takes two students
and returns true if and only if the first student has done better than the second in the ordering
below.
a. the Programming mark is most important,
b. numerical order of Maths marks is the determining factor when two students have the
same Programming mark,
c. alphabetical order of Lab grades is the determining factor when two students have the
same Programming and Maths marks.
4. Suppose we want to represent a planet in the solar system as an object of class Planet. In the
object, it contains two fields: one called name is a String containing its name, and one called
satellites is an array of String containing the names of all its satellites. Define the class, with a
constructor taking a String and an array of String as argument for initializing the object.
5. For the last question, write a method print() in the class to print out the name of the planet and
all the satellites. For example, if we have
String[] earth_sat = { "Moon" };
Planet earth = new Planet("Earth", earth_sat);
Then we want earth.print(); to print out the following:
Earth has 1 satellite(s):
Moon.
6. When creating an array, we need to know the exact size of the array when the array is created.
There is no way to expand or contract an array afterwards. There are many applications that
want a “resizable” array, because the exact number of elements is not known when the array is
created. This can be achieved in Java by reallocating an array whenever the original array is
not sufficient to hold the array. When this happens, we copy all the elements from the old array
to the new one.
Write a Java class for representing a resizable array of integers. The class, called IntArray,
should have the following constructors and methods. Here ia denotes a reference to IntArray.
• Constructor: IntArray(initial_size), where initial_size is an integer specifying the
initial size of the array. All elements are initially 0.
• Read: intAt(index): return the integer stored in the array at the integer index
index. A run-time error should be generated if index is out of range.
• Write: storeAt(index, value): store an integer value into the array at the integer
index index. Return nothing. A run-time error should be generated if index is out
of range.
• Size: getSize(): return the current size of the array.
• Resize: resize(size): change the capacity of the array to an integer size. If size is
different from the current size of the array, a new array should be allocated, and
the old content of the array should be copied to the new array. If size is smaller
than the original size, the extra elements in the original array are lost. If size is
larger than the original size, the extra elements in the new array takes the value
0. Return nothing.
• Write and resize: storeAndResize(index, value): store an integer value at an
integer index index. If index is larger than or equal to the current size of the array,
it also expand the array. If this happens, the array is expanded to either a size of
index+1, or double the original size, whichever the larger. A run-time error should
be generated if index is negative. Return nothing.
With this class, write a program that reads integers until it reads -1, and prints out the
median of the integers
read (not counting -1). For example:
Type the numbers, terminated by -1:
298376
-1
The median is 6.5.
7. Create an abstract class called Animal and create at least three classes ( Dog, Snake, Fish
etc.,) which extend from that class and override the abstract methods defined in animal class.
(Print different values for different animals when you override methods in Animal class)
public abstract class Animal{
public abstract void move();
public abstract void eat();
public void sleep(){
Sys.println(“i am sleeping”);
}
}
Then create another class called AnimalDemo and write a method called with the following
signature:
live(Animal);
In this method invoke some methods of Animal. Your main method should be written in
AnimalDemo class.
8. Go through the following classes and follow the instructions given below:
class Hello{
String name;
private Hello( String name){
this.name=name;
}
public void sayHello( ){
System.out.println("hello "+name);
}
}
Save the above class to a file. Try to create an object of this class in another class say
HelloDemo (contains main method) and invoke sayHello( ) methods on that object.
note: you are not permitted to add constructors or modify the existing constructors
hint: use static
9. Write a class called Gen which contains an instance variable called id (say of type int). Now
whenever an object is created, id has to be assigned a unique value. This has to be assigned
in incremental fashion. Do not set this id manually after creation of the object. Do not use
parameterized constructors.
10. Design a class called Single keeping in mind the following constraints.
Only a single instance of the class should be allowed to create and same instance should be
made to share by all the clients. (Clients here refer to the classes which use the class Single).
You should ensure that no additional instances are created accidentally. (Hint: use static)
Inheritance
1. Design the class hierarchy. Add your own methods.
Staff
Code
Name
Regular Casual
Salary Daily wages
Package & Interface
1. Define a class UString which contains method for the following statement.
a. To reverse the given string
b. To give the number of alphabets in a string.
Create a package and include this class in the created package. Import this package in to
java source file and perform string operations.
c. To extract a portion of character string and print the extracted string.
Assume that m characters are extracted starting with the nth character.
d. To read a text and count all occurrence of a particular word.
e. To read a string and rewrite it in the alphabetical order
( Ex ;- STRING --->GINRST)
2. Create a package by name logicgate which consist of classes for AND, OR, NOT gate, import
this package in to java source file and simulate the behavior of half adder circuit.
3. Create a package called shapes. Now write a class called Point (belongs to package shape)
which represents a point in 2D-space. It has two fields x and y. Write a parametrized
constructor to initialize these values(do not provide default constructor).
---> Now write another class called Circle (belongs to package shapes) which has a field of
type Point (to represent the center of circle) and another field radius. Write a parametrized
constructor to initalize all fields of circle. Now write a method in this class called isInside()
which takes a point as parameter and returns true if that point is inside the circle or false
otherwise.
---> Now write main method (in CircleDemo class), create a circle and invoke isInside()
method by passing a parameter to it and print the return value.
we will have Three classes Point, Circle and CircleDemo (contains main method)
Point(int x, int y){ } //parametrized constructor
Circle(Point centre, int radius){ } //parametrized constructor
boolean isInside(Point p)
CircleDemo doesn’t belong to shapes package.
4. Assuming you have the following interface:
public interface Sort{
public void sort(int elements[], int start, int end);
public void sort(int elements[]); //equivalent to calling sort(elements, 0, elements.length-
1)
}
Now extend the ParallelMergeSort from the AbstractMergeSortClass class, and make it invoke
as many SorterTaskThread s as required:
Now finally implement class MergeSortTester; Randomly populate an array of 200 elements
using Math.random()*123456.
Sort the array using MergeSort, then using ParallelMergeSort.
Now run both implementations and test the time using this command:
test java MergeSortTester
Sample the times taken for 10 times, average it. Now find the ratio of time for MergeSort/time
for ParallelMergeSort.
If it's <1, why is it so?
Now repeat the same with 200000 elements. Does the ratio change?
Exception Handling
1. Save the above class to a file and compile it and check the output.
class A{
public static void main(String[] args){
int a,b;
try{
a=0;b=1;
System.out.println(b/a);
//return;
}catch(Exception){
System.out.println(“Exception caught”);
//return;
}finally{
System.out.println(“in Finally”)
}
//System.out.println(“at the end”);
}
}
Now uncomment the comments one by one and observe the outputs and understand all the
cases.
2. Write a class called BankAccount with the following properties and methods.
Properties: name, PIN, balance
methods: deposit(int amt), withdraw(int amt)
write another class called ATM with following methods and properties:
methods:deposit(Account acc, int amt), withdraw(Account acc, int amt) ,
transfer(Account acc1, Account acc2, int amt)
Assume that an account needs to have a minimum balance of 200. If an attempt is made to
withdraw, which results in balance going below 200, throw an exception called
MinimumBalanceException.
For this you need to create your own exception class.
Note: To create an Exception class called MyFirstException
class MyFirstException extends Exception{
/*I never thought it’s so simple*/
}
Use throw and throws wherever necessary.
3. Write a java program to compare names of two persons (first name and last name) and return
result as
2. Four missiles are test fired at a research centre such that every missile fires four firing
components FC1 , FC2 , FC3, FC4. The missiles have a serial arrangement and they are fired
one after another with a delay of 1500ms.The components are automatically shot within the
allotted timeslot with uniform delay. A timer program (written in java) from the trigger interface
displays the time of firing of different components of different missiles (may be named missile1,
missile2 , missile3 & missile4)
Using threads implement the timer program in java to display the times at which each
missile and its component are fired.
Sample output :
Timer reading : 0ms – missile1 ready
Timer reading : 300ms – FC1 fired
Timer reading : 600ms – FC2 fired
Timer reading : 900ms – FC3 fired
Timer reading : 1200ms – FC4 fired
3. A relay circuit has two types of components Major component and Minor components to ring
relayed alarm bells. The design is such that for every Major bell ring 3 Minor alarms ring.Using
threads implement the above scenario for a timed output as below :