Download as pdf or txt
Download as pdf or txt
You are on page 1of 161

LAB COURSE-II | CAMS-20P1

DEPARTMENT OF COMPUTER
SCIENCE

MASTER OF COMPUTER APPLICATION

CAMS-20P1: LABORATORY COURSE-II

SUBMITTED BY: SUBMITTED TO:


BILAL AHMAD DR. ARMAN RASOOL FARIDI
21CAMSA 111 MS. SAJIDA KHATOON
GI1527 MR. MD. SAJID ANWER
MR. TIPU SULTAN
BILAL AHMAD 21CAMSA 111 1
LAB COURSE-II | CAMS-20P1

WEEK NO.

PAGE NO.
SIGNATURE
OF THE
PROBLEMS WITH DESCRIPTION TEACHER
WITH DATE

1# Write a java program to print ‘Hello World’.


Write a java program to print the corresponding address of a
2#
student.

3# Write a Java program to calculate the sum of two numbers.

Write a Java program to convert the given temperature from


4# Fahrenheit to Celsius using the following conversion formula C = F
– 32 / 1.8 and display the value in a tabular form.

Write a java program for finding the sum, difference, product,


5#
quotient, minimum, and maximum of any two integers.
Write a java program 'MyNumber.java" that performs the
following operations on a variable 'num' of type double:
WEEK 1

i) Finds the round value of 'num' and stores the result in a variable
numRound of type double.
ii) Finds the ceil value of 'num' and stores the result in a variable
numCeil of type double.
6# iii) Finds the floor value of 'num' and stores the result in a variable
numFloor of type double.
Cast 'num' to type int and store the result in a variable numInteger
of type int.Display output of numRound, numCeil, numFloor, and
numInteger on screen.
Note: Test your program with the following value of num
num=56.764num=36.432
Write a java program to calculate simple interest and compound
7# interest on a certain sum for a certain time at a certain rate of
interest.

8# Write a java program to print ASCII Value of Alphabets.

9# Write a java program to print Alphabets from ASCII Value.

BILAL AHMAD 21CAMSA 111 2


LAB COURSE-II | CAMS-20P1

Write a java program to interchange the value of two variables.


10# (Note: both ways using temporary variable and not using any
other value).

BILAL AHMAD 21CAMSA 111 3


LAB COURSE-II | CAMS-20P1

WEEK NO. SIGNATURE

PAGE NO.
OF THE
PROBLEMS WITH DESCRIPTION TEACHER
WITH DATE

Write a java program to print the count of odd and even


1#
numbers entered.

Write a java program to print the squares and cubes for the
2#
numbers 1 to 5.

Write a java program that computes the sum of the


3#
reciprocals: 1/1+1/2+1/3+1/4+ --- --- --- --- --- --- ---+1/10.

Write Java program to compute the sum of the 2+4+6+---------


4#
N Terms.

Shown below is Floyd’s triangle:

1
23
456
7 8 9 10
11 12 13 14
15 16 17 18 19
WEEK 2

i) Write a program to print the above triangle.


5#
ii) Modify the program to produce the following form of
Floyd’s triangle:

1
01
101
0101
10101
010101
Write a program in the sequence 0, 1, 1, 2, 3, 5, 8, 13, 21…..is
6# called Fibonacci numbers. Write a program using a do while
loop to calculate and print the first m Fibonacci numbers.

Write a java program to print the multiplication table of a


7#
number.

8# Write a java program to find Perfect Number from 1 to 100.

9# Java program to convert decimal to binary, octal, and hexa.

10 Write a java program to find the Roots of Quadratic Equation.

BILAL AHMAD 21CAMSA 111 4


LAB COURSE-II | CAMS-20P1

WEEK NO.
SIGNATURE

PAGE NO.
OF THE
PROBLEMS WITH DESCRIPTION TEACHER
WITH DATE

1# Write Java program to show uses of all Math class methods.

Write a program to accept three digits (i.e. 0 - 9) and print


all its possible combinations. (For example, if the three
2#
digits are 1, 2, 3 then all possible combinations are: 123,
132,213, 231, 312, 321)
Write a program to calculate the area of triangle, square,
3#
circle, and rectangle by using method overloading.

Write a Java Program which prompts the user to enter 4


4# numbers. The program will then compute and display their
sum and their product.

Write a Java program that reads a 4-digit number and prints


5# the digits on separate lines. (Each digit is printed on one
line).
WEEK 3

The intersection method computes the intersection of two


rectangles- that is, the rectangle that is formed by two
overlapping rectangles. You call this method as follows:
6# Rectangle r3 =r1.intersection (r2);
Write a program that constructs two rectangle objects,
prints them, and then prints their intersection. What
happens when the rectangles do not overlap?

Write an interactive java program that reads in integers


until a 0 is entered. If it encounters 0 as input, then it should
display:
7#
- the total no. of even and odd integers.
- average value of even integers.
- average value of odd integers.

Write a java program to print a list of prime numbers


8#
between a given range that you entered from the keyboard.

Write an interactive program to generate the divisors of a


9#
given integers.

Write a java program to print the Sum of Series 1-(x/1!


10#
+x2/2!+......+xn/n!).

BILAL AHMAD 21CAMSA 111 5


LAB COURSE-II | CAMS-20P1

WEEK NO.
SIGNATURE

PAGE NO.
OF THE
PROBLEMS WITH DESCRIPTION TEACHER
WITH DATE

Write a Java program involving two classes: OddAndEven &


TestOddAndEven.OddAndEven has the following:
• Instance variables countOfOdd and countOfEven both of type
int.
• A method addNumber that takes a number as a parameter and
increments countOfOdd, if the number is odd, else increment
countOfEven.
#1
• A method toString that returns a string in the form: “Number of
Odd: x, Number of Even: y”, where x and y are the values of the
instance variables.
The TestOddAndEven class first creates an OddAndEven
object, then in a loop, read a number and use it to call the
addNumber method until the user enters Q. Finally, it prints the
count of odd and even numbers entered.
WEEK 4

Design a class Circle and implement the following methods:


• Define a circle method to compute its area
• Define a circle method to compute its perimeter
• Define a method that takes a given point represented by a pair
2# of numbers and checks whether or not the point is inside the
circle.
The circle class needs to have instance variables to store the
radius of the circle, and the x and y coordinates of the center.
Add main program to test the class Circle repeatedly, until user
enters negative value for the radius of the circle.

Write a program in Java that reads in text and prints as output


the following:
• The number of words in the text

3# • The number of sentences in the text


• The number of times the letter “e” occurs in the text
• The number of times the letter “z” occurs in the text
(Note: Use StringTokenizer class)

BILAL AHMAD 21CAMSA 111 6


LAB COURSE-II | CAMS-20P1

A salesperson is paid commission based on the sales he makes


as shown by the following table:

Write a class Commission which has an instance variable sale,


4# an appropriate constructor, and a method commission () that
returns the commission.
Now write a demo class to test the Commission class by reading
a sale from the user, using it to create a Commission object
after validating that the value is not negative. Finally, call the
commission () method to get and print the commission. If the
sales are negative, your demo should print the message “Invalid
Input”.

Certain instructor assigns letter grades for his course based on


the following table:
SCORE GRADE
>=90 A+
>=85 A
>=80 B+
>=75 B
>=65 C+
>=60 C
>=55 D+
5# >=50 D
<50 F
Write a class, Grader, which has an instance variable,
score, an appropriate constructor and appropriate method
letterGrade() that returns the letter grade as a String.
Now write a demo class to test the Grader class by reading
a score from the user, using it to create a Grader object
after validating that the value is not negative and is not
greater than 100. Finally, call the letterGrade() method to
get and print the grade.
Create a class named 'Student' with String variable 'name' and
integer variable 'roll_no'. Assign the value of roll_no as '2' and
6#
that of name as "John" by creating an object of the class
Student.

Write a Java class Clock for dealing with the day time
represented by hours, minutes, and seconds. Your class must
7# have the following features:
Three instance variables for the hours (range 0 - 23), minutes
(range 0 - 59), and seconds (range 0 - 59).

BILAL AHMAD 21CAMSA 111 7


LAB COURSE-II | CAMS-20P1

Three constructors:
• default (with no parameters passed; is should initialize the
represented time to 12:0:0)
• a constructor with three parameters: hours, minutes, and
seconds.
• a constructor with one parameter: the value of time in seconds
since midnight (it should be converted into the time value in
hours, minutes, and seconds)
Instance methods:
• a set-method method setClock() with one parameter seconds
since midnight (to be converted into the time value in hours,
minutes, and seconds as above).
• get-methods getHours(), getMinutes(), getSeconds() with no
parameters that return the corresponding values.
• set-methods setHours(), setMinutes(), setSeconds() with one
parameter each that set up the corresponding instance
variables.
• method tick() with no parameters that increments the time
stored in a Clock object by one second.
WEEK 4

• method addClock() accepting an object of type Clock as a


7# parameter. The method should add the time represented by the
parameter class to the time represented in the current class.
• Add an instance method toString() with no parameters to your
class. toString() must return a String representation of the
Clock object in the form "(hh:mm:ss)", for example "(03:02:34)".
• Add an instance method tickDown() which decrements the
time stored in a Clock object by one second.
• Add an instance method subtractClock() that takes one Clock
parameter and returns the difference between the time
represented in the current Clock object and the one
represented by the Clock parameter. The difference of time
should be returned as a clock object.
Write a separate class ClockDemo with a main() method. The
program should:
• instantiate a Clock object firstClock using one integer seconds
since midnight obtained from the keyboard.
• tick the clock ten times by applying its tick() method and print
out the time after each tick.
• Extend your code by appending to it instructions instantiating a
Clock object secondClock by using three integers (hours,
minutes, seconds) read from the keyboard.
• Then tick the clock ten times, printing the time after each tick.

BILAL AHMAD 21CAMSA 111 8


LAB COURSE-II | CAMS-20P1

• Add the secondClock time in firstClock by calling method


addClock.
• Print both clock objects calling toString method
Create a reference thirdClock that should reference to object of
difference of firstClock and secondClock by calling the method
subtractClock().

BILAL AHMAD 21CAMSA 111 9


LAB COURSE-II | CAMS-20P1

SIGNATURE

PAGE NO.
WEEK NO.

OF THE
PROBLEMS WITH DESCRIPTION
TEACHER

WITH DATE

Implement a Student class with the following fields,


constructors and methods:
Fields:
• name;
• totalScore;
• numberOfQuizzes;
Constructors:
• public Student(String name, double score)
• public Student(double score, String name)
• public Student(String name)
WEEK 5

Methods:

1# • public String getName()


• public double getAverage() //this should return zero if no quiz
has been taken.
• public double getTotalScore()
• public void addQuiz(double score)
• public void printStudent() //this should print the student’s
name and
average score.
• public String toString()
Write an application TestStudent that reads a student name
and use the Student class to create a Student object. Then
read the scores of the student in three quizzes and add each
to the totalScore of the student using addQuiz() method and
print the student object.
( Note: Make use of this key word wherever it can be used ).

BILAL AHMAD 21CAMSA 111 10


LAB COURSE-II | CAMS-20P1

Write a program to design a class to represent a bank


account. Include the
following members.
Date members:
• Name of depositor
• Account Number
• Type of account
• Balance account in the account
Methods:
• To assign initial values
• To deposit an account
• To withdraw an account after checking balance.
• To display the name and balance

BILAL AHMAD 21CAMSA 111 11


LAB COURSE-II | CAMS-20P1

SIGNATURE
WEEK NO.

PAGE NO.
OF THE
PROBLEMS WITH DESCRIPTION
TEACHER
WITH DATE

Write a program that reads in a sentence from the user


and prints it out with each word reversed, but with the
words and punctuation in the original order:
1#

Write a program where interface can be used to support


2# multiple inheritances. Develop a standalone Java
program for this
Write a program that reads in three strings and sorts
them lexicographically.
3# Hint: Enter strings: Charlie Able Banker

Output: Able Banker Charlie

Implement the classes for the shapes using an interface


4# for the common methods, rather than inheritance from
WEEK 6

the super class, while still Shape as a base class.

Implement a super class Person. Make two classes,


Student and Instructor, inherit from Person. A person
has a name and a year of birth. A student has a major,
5# and an instructor has a salary. Write the class
definitions, the constructors, and the methods toString
for all classes. Supply a test program that tests these
classes and methods.
Write a Java class Complex for dealing with complex
number. Your class must have the following features:

• Instance variables :
o realPart for the real part of type double
o imaginaryPart for imaginary part of type double.

6# • Constructor:
o public Complex (): A default constructor, it should
initialize the number to 0, 0)
o public Complex (double realPart, double
imaginaryPart): A constructor with parameters, it
creates the complex object by setting the two fields to
the passed values.
• Instance methods:
o public Complex add (Complex otherNumber):

BILAL AHMAD 21CAMSA 111 12


LAB COURSE-II | CAMS-20P1

This method will find the sum of the current complex


number and the passed complex number. The methods
returns a new Complex number which is the sum of the
two.

o public Complex subtract (Complex otherNumber): This


method will find the difference of the current complex
number and the passed complex number. The methods
returns a new Complex number which is the difference
of the two.

o public Complex multiply (Complex otherNumber): This


method will find the product of the current complex
number and the passed complex number. The methods
returns a new Complex number which is the product of
the two.

o public Complex divide (Complex otherNumber): This


method will find the ... of the current complex number
and the passed complex number. The methods returns a
new Complex number which is the ... of the two.

o public void setRealPart (double realPart): Used to set


the real part of this complex number.

o public void setImaginaryPart (double realPart): Used


to set the imaginary part of this complex number.

o public double getRealPart(): This method returns the


real part of the complex number.

o public double getImaginaryPart(): This method returns


the imaginary part of the complex number.

o public String toString(): This method allows the


complex number to be easily printed out to the screen
Write a separate class ComplexDemo with a main()
method and test the Complex class methods.

BILAL AHMAD 21CAMSA 111 13


LAB COURSE-II | CAMS-20P1

SIGNATURE
WEEK NO.

PAGE NO.
OF THE
PROBLEMS WITH DESCRIPTION TEACHER
WITH DATE

Define a class Employee having private members – id,


name, department, salary. Define default and
parameterized constructors. Create a subclass called
“Manager” with a private member bonus. Define
1#
methods accept and display in both the classes. Create
n objects of the Manager class and display the details of
the manager having the maximum total salary
(salary+bonus).

Write a Java program to create a super class Vehicle


having members Company and price. Derive 2 different
classes LightMotorVehicle (members – mileage) and
2# HeavyMotorVehicle (members – capacity-in-tons).
Accept the information for n vehicles and display the
information in appropriate form. While taking data, ask
the user about the type of vehicle first.
WEEK 7

A bank maintains two kinds of accounts - Savings


Account and Current Account. The savings account
provides compound interest, deposit, and withdrawal
facilities. The current account only provides deposit and
withdrawal facilities. Current account holders should
also maintain a minimum balance. If the balance falls
below this level, a service charge is imposed. Create a
class Account that stores the customer name, account
number, and type of account. From this derive the
3# classes Curr-acct and Sav-acct. Include the necessary
methods in order to achieve the following tasks:
• Accept deposit from a customer and update the
balance.
• Display the balance.
• Compute interest and add to balance.
• Permit withdrawal and update the balance (Check for
the minimum balance, impose a penalty if necessary).

BILAL AHMAD 21CAMSA 111 14


LAB COURSE-II | CAMS-20P1

Define a class called fruit with the following attributes:


• Name of the fruit
• Single fruit or bunch fruit
4# Define a suitable constructor and displayFruit() method
that displays values of all the attributes. Write a program
that creates 2 objects of fruit class and display their
attributes.

Write a program where interface can be used to support


5# multiple inheritances. Develop a standalone Java
program for this.

BILAL AHMAD 21CAMSA 111 15


LAB COURSE-II | CAMS-20P1

WEEK NO.

PAGE NO.
SIGNATURE
OF THE
PROBLEMS WITH DESCRIPTION
TEACHER
WITH DATE

Implement the classes for the shapes using an


interface for the common methods, rather than
1#
inheritance from the super class, while still Shape as a
base class.
Create a package called "Arithmetic" that contains
2# methods to deal all arithmetic operations. Also, write a
program to use the package.
Write a program to make use of a parameterized
method inside a class. Take the following case: Create
3# a class Box and define a method in this class which
will return the volume of the box. Initialize two objects
for your class and print out the volumes respectively.
Write a program that calls a method that throws an
exception of type ArithmeticException at a random
4# iteration in a for loop. Catch the exception in the
WEEK 8

method and pass the iteration count when the


exception occurred to the calling method by using an
object of an exception class you define.
5# Write a program that will count the number of
characters in a file.
Write a Java class Author with following features:

• Instance variables :
o firstName for the author’s first name of type String.
o lastName for the author’s last name of type String.

• Constructor:
o public Author (String firstName, String lastName): A
6# constructor with parameters, it creates the Author
object by setting the two fields to the passed values.

• Instance methods:
o public void setFirstName (String firstName): Used to
set the first name of author.
o public void setLastName (String lastName): Used to
set the last name of author.

BILAL AHMAD 21CAMSA 111 16


LAB COURSE-II | CAMS-20P1

o public double getFirstName(): This method returns


the first name of the author.
o public double getLastName(): This method returns
the last name of the author.
o public String toString(): This method printed out
author’s name to the screen.

Write a Java class Book with the following features:

• Instance variables :
o title for the title of book of type String.
o author for the author’s name of type String.
o price for the book price of type double.

• Constructor:
o public Book (String title, Author name, double price):
WEEK 8

A constructor with parameters, it creates the Author


object by setting the the fields to the passed values.
6#
• Instance methods:
o public void setTitle(String title): Used to set the title
of book.
o public void setAuthor(String author): Used to set the
name of
author of book.
o public void setPrice(double price): Used to set the
price of book.
o public double getTitle(): This method returns the title
of book.
o public double getAuthor(): This method returns the
author’s name of book.
o public String toString(): This method printed out
book’s details to the screen.

Write a separate class BookDemo with a main()


method creates a Book titled “Developing Java
Software” with authors Russel Winderand price 79.75.
Prints the Book’s string representation to standard
output (using System.out.println).

BILAL AHMAD 21CAMSA 111 17


LAB COURSE-II | CAMS-20P1

SIGNATURE

PAGE NO.
WEEK NO.

OF THE
PROBLEMS WITH DESCRIPTION
TEACHER
WITH DATE
Write a Java program which reads student grades from a
text file called grades.txt and prints only the
corresponding letter grades into a file called letter.txt.
The letter grades are assigned according to the following
table. Assume that the grades.txt file can have any
number of students’ grades. Hint:The last number in the
grades.txt file is -1

1#
WEEK 9

2# Write a program to read a, b, c from data file and store


roots of the quadratic equation in the output file. You must
open your output file in append mode.
Develop an applet that receives three numeric values as
3# input from the user and then displays the largest of the
three on the screen. Write a HTML pages and test the
applet.
4# Write a java program to read a file and find the total no. of
characters in that file.

5# Write a java program to read a file and find total no. of


lines in that file.

BILAL AHMAD 21CAMSA 111 18


LAB COURSE-II | CAMS-20P1

SIGNATURE

PAGE NO.
WEEK NO.

OF THE
PROBLEMS WITH DESCRIPTION
TEACHER
WITH DATE
Write applets to draw the following shapes:
1#
a)Cone b)Cylinder c)Square inside a circle

Write an applet that will display the following on a green


background. Use the following dimension:
Rectangle : (10, 10, 300, 150), Fill colour: blue
Left Circle : (10, 10, 50, 150), Fill Colour: Yellow
Right Circle: (159, 10, 150, 150), Fill colour: Yellow

2# Text : (110, 90), colour: Red


WEEK 10

Write a JAVA Applet program to plot the following face:

3#

BILAL AHMAD 21CAMSA 111 19


LAB COURSE-II | CAMS-20P1

WEEK NO. SIGNATURE

PAGE NO.
OF THE
PROBLEMS WITH DESCRIPTION
TEACHER
WITH DATE
Write a graphics program that draws a clock face with a
time that the user enters in a text field. (The user must
enter the time in the format hh:mm, for example09:45).

Hint: You need to find out the angles of the hour hand and
the minute hand. The angle of the hour hand is harder; it
travels 360 degrees in 12 x 60 minutes. Your output must
1# be in the following format:

Write a program that draws the picture of a house.


WEEK 11

Sample Output:

2#

Write an applet to display the following figure:


Sample Output:
3#

Write an applet to display the following figure:


Sample Output:

4#

BILAL AHMAD 21CAMSA 111 20


LAB COURSE-II | CAMS-20P1

PAGE NO.
SIGNATURE
WEEK NO.

OF THE
PROBLEMS WITH DESCRIPTION
TEACHER
WITH DATE

Draw a “bull’s eye” a set of concentric rings in alternation


black and white colors: Fill a black circle, and then fill a
smaller white circle on top, and so on.
1#
WEEK 12

Write an AWT GUI application (called AWTCounter) as


shown in the Figure. Each time the "Count" button is
clicked, the counter value shall increase by 1.
2#

BILAL AHMAD 21CAMSA 111 21


LAB COURSE-II | CAMS-20P1

SIGNATURE
WEEK NO.

PAGE NO.
OF THE
PROBLEMS WITH DESCRIPTION
TEACHER
WITH DATE
Write a java program to perform calculations like addition,
subtraction, multiplication, and division using AWT and
applets. Create three Text Fields for entering a first
number, the second number, and displaying the result.
Add four buttons for performing addition, subtraction,
multiplication, and division.

1#
WEEK 13

Write a program in Java such that it accepts a number and


displays the square of the number 12 using applet. Create
an input text field to accept a number from user. Create a
button to confirm the number and calculate its square.
When the button is clicked, display its square in a text
field.
2#

BILAL AHMAD 21CAMSA 111 22


LAB COURSE-II | CAMS-20P1

WEEK NO.

SIGNATURE

PAGE NO.
OF THE
PROBLEMS WITH DESCRIPTION
TEACHER
WITH DATE
WEEK 14

Write a Java program to display the employee id,


1# age, first name and last name
using JDBC connectivity.

BILAL AHMAD 21CAMSA 111 23


LAB COURSE-II | CAMS-20P1

BILAL AHMAD 21CAMSA 111 24


LAB COURSE-II | CAMS-20P1

WEEK 1
#1 Write a java program to print ‘Hello World ’.
This is the required code:

package javaapplication1;
public class JavaApplication1 {
public static void main(String[] args){
System.out.println("hello");
}
}
And this is its output:

#2 Write a java program to print the corresponding address of a student.


This is the required code:

package javaapplication1;
public class JavaApplication1 {
public static void main(String[] args){
System. out.println(“College View Apartment, Dhorra Mafi, Aligarh");
}
}

OUTPUT:

BILAL AHMAD 21CAMSA 111 25


LAB COURSE-II | CAMS-20P1

#3 Write a Java program to calculate the sum of two numbers.


This is the required code:

package javaapplication1;
import java.util.Scanner;
public class week1Q3 {
public static void main(String[] args)
{ Scanner a=new Scanner(System.in);
System.out.println("Enter first number: ");
int x=a.nextInt();
System.out.println("Enter second number: ");
int y=a.nextInt();
int sum;
sum=x+y;
System.out.println("Sum of the two numbers is: "+sum);
}
}
And this is its output:

#4 Write a Java program to convert the given temperature in Fahrenheit to


Celsius using the following conversion formula C = F – 32 / 1.8 and display the
value in a tabular form.
This is the required code:

BILAL AHMAD 21CAMSA 111 26


LAB COURSE-II | CAMS-20P1

package javaapplication1;
import java.util.Scanner;
public class week1Q4 {
public static void main(String[] args) {

Scanner a=new Scanner(System.in);


double F,C;
System.out.println("Enter the value of temperature in fahrenheit: ");
F=a.nextDouble();
C=(F-32)*(5.0/9.0);
System.out.println("Temp in Fahrenheit "+" Temp in Celcius ");
System.out.println(" "+F+" "+C);
}
}
Its output is:

#5 Write a java program for finding the sum, difference, product, quotient,
minimum and maximum of any two integers.
This is the required code:

package javaapplication1;
import java.util.Scanner;
import java.lang.Math;
public class Week1Q5 {

BILAL AHMAD 21CAMSA 111 27


LAB COURSE-II | CAMS-20P1

public static void main(String[] args){


Scanner a=new Scanner(System.in);
float x,y,sum,diff,product,max,min;
float quotient;
System.out.println("Enter the value of both integers: ");
x=a.nextInt();
y=a.nextInt();
sum=x+y;
diff=x-y;
product=x*y;
quotient=x/y;
max=Math.max(x,y);
min=Math.min(x, y);
System.out.println("Sum of the two numbers is: "+sum );
System.out.println("Difference of the two numbers is: "+diff);
System.out.println("Product of the two numbers is: "+product);
System.out.println("Quotient after division of both numbers is: "+quotient);
System.out.println("Maximum value from thesw two is: "+max);
System.out.println("Minimum value among these two is: "+min);
}
}
And this is its output:

BILAL AHMAD 21CAMSA 111 28


LAB COURSE-II | CAMS-20P1

#6 Write a java program 'MyNumber.java" that performs following operations


on a variable 'num' of type double:
i) Finds the round value of 'num' and stores the result in a variable numRound
of type double.
ii) Finds the ceil value of 'num' and stores the result in a variable numCeil of
type double.
iii) Finds the floor value of 'num' and stores the result in a variable numFloor
of type double.
Cast 'num' to type int and stores the result in a variable numInteger of type
int. Display output of numRound, numCeil, numFloor and numInteger on
screen.
Note: Test your program with following value of num
num=56.764num=36.432
This is the required code:

package javaapplication1;
import java.util.Scanner;
import java.lang.Math;
public class Week1Q6 {
public static void main(String[] args){
double num;
Scanner s=new Scanner(System.in);
System.out.println("Enter the value: ");
num=s.nextDouble();
double numRound=Math.round(num);
System.out.println("The round value of entered number is: "+numRound);
double numCeil=Math.ceil(num);
System.out.println("The ceil value of entered number is: "+numCeil);
double numFloor=Math.floor(num);

BILAL AHMAD 21CAMSA 111 29


LAB COURSE-II | CAMS-20P1

System.out.println("The floor value for entered number is: "+numFloor);


int numInteger=(int)num;
System.out.println("Value after typecasting to integer is: "+numInteger);
}
}
And this is its output:

#7 Write a java program to calculate simple interest and compound interest


on a certain sum for a certain time at a certain rate of interest.
This is the required code:

package javaapplication1;
import java.util.Scanner;
import java.lang.Math;
public class Week1Q7 {
public static void main(String[] args){
double P,R,T,SI,CI;
Scanner s=new Scanner(System.in);
System.out.println("Enter the principal amount: ");
P=s.nextDouble();
System.out.println("Enter the rate of interest: ");
R=s.nextDouble();
System.out.println("Enter the time duration: ");
T=s.nextDouble();
BILAL AHMAD 21CAMSA 111 30
LAB COURSE-II | CAMS-20P1

SI=(P*R*T)/100;
System.out.println("The value of simple interest is: "+SI);
CI=P*Math.pow(1+(R/100),T)-P;
System.out.println("The value of compound interest is: "+CI);
}
}

And this is its output:

#8 Write a java program to print ASCII Value of Alphabets.


This is the required code:
package javaapplication1;
public class Week1Q8 {
public static void main(String[] args){
for(char ch='A';ch<='Z';ch++)
{ System.out.println("The ASCII value of "+ch+" is "+(int)ch);
}
for(char ch='a';ch<='z';ch++){
System.out.println("The ASCII value of "+ch+" is "+(int)ch);}
} }

BILAL AHMAD 21CAMSA 111 31


LAB COURSE-II | CAMS-20P1

And this is its output:

BILAL AHMAD 21CAMSA 111 32


LAB COURSE-II | CAMS-20P1

#9 Write a java program to print Alphabets from ASCII Value.


This is the required code:
package javaapplication;
public class Week1Q9 {
public static void main(String[] args){
char c,ch;
for(int i=65;i<=90;i++){
c=(char)i;
System.out.println("Alphabet value for ASCII value "+i+" is "+c);
}
for(int j=97;j<=122;j++){
ch=(char)j;
System.out.println("Alphabet for ASCII value "+j+" is "+ch);
}} }
This is its output:

BILAL AHMAD 21CAMSA 111 33


LAB COURSE-II | CAMS-20P1

#10 Write a java program to interchange the value of two variables. (Note:
both ways using temporary variable and not using any other value).

This is the required code using a third variable:

package javaapplication1;
import java.util.Scanner;
public class week1q10 {
public static void main(String[] args){
int x,y,z;
Scanner s=new Scanner(System.in);
System.out.println("Enter value of first variable x: ");
x=s.nextInt();
System.out.println("Enter value of second variable y: ");
y=s.nextInt();
z=x;
x=y;
y=z;
System.out.println("Value after swapping becomes: ");
System.out.println("x= "+x+" y= "+y);
}
}
And this is its output:

BILAL AHMAD 21CAMSA 111 34


LAB COURSE-II | CAMS-20P1

Without using a third variable, the required code is given below:

package javaapplication1;
import java.util.Scanner;
public class WEEK1Q10withoutthirdvariable {
public static void main(String[] args){
int x,y;
Scanner s=new Scanner(System.in);
System.out.println("Enter value of first variable x: ");
x=s.nextInt();
System.out.println("Enter value of second variable y: ");
y=s.nextInt();
x=x+y;
y=x-y;
x=x-y;
System.out.println("Value after swapping becomes: ");
System.out.println("x= "+x+" y= "+y);
}
}
And this is its output:

BILAL AHMAD 21CAMSA 111 35


LAB COURSE-II | CAMS-20P1

WEEK 2

BILAL AHMAD 21CAMSA 111 36


LAB COURSE-II | CAMS-20P1

WEEK 2
#1 Write a java program to prints the count of odd and even no’s entered.

This is the required code:

package javaapplication1;
import java.util.Scanner;
public class week2Q1 {
public static void main(String[] args) {
int n,e=0,o=0;
Scanner a=new Scanner(System.in);
System.out.println("Enter the amount of numbers you wish to enter");
n=a.nextInt();
for(int i=0;i<=n;i++){
System.out.println("Enter the value of "+i+" number");
int b=a.nextInt();
if(b%2==0) {
e++; }
else {
o++; }
}
System.out.println("Number of even numbers entered is: "+e);
System.out.println("Number of odd numbers entered is: "+o);
}
}

And given below is its output:


BILAL AHMAD 21CAMSA 111 37
LAB COURSE-II | CAMS-20P1

#2 Write a java program to print the squares and cubes for the numbers 1 to
5.
This is the required code:

package javaapplication1;
import java.util.Scanner;
import java.lang.Math;
public class week2Q2 {
public static void main(String[] args) {
int sq,cube;
for(int i=0;i<=5;i++)
{ sq=(int) Math.pow(i, 2);
System.out.println("Square of number "+i+" is: "+sq);
cube= (int) Math.pow(i,3);
System.out.println("Cube of number "+i+" is: "+cube); }
}
}

BILAL AHMAD 21CAMSA 111 38


LAB COURSE-II | CAMS-20P1

And this is its output:

#3 Write a java program that computes the sum of the reciprocals:


1/1+1/2+1/3+1/4+ --- --- --- --- --- --- ---+1/10.

This is the required code:

package javaapplication1;
import java.util.Scanner;
public class Week2Q3 {
public static void main(String[] args){
double sum=0;
for(double i=1;i<=10;i++) {
sum=sum+1/i; }
System.out.println("Sum of the reciprocals 1/1+1/2+1/3+1/4+ --- --- --- --- --- --- ---+1/10 is: ");
System.out.println(sum);
} }

And this is its output:

BILAL AHMAD 21CAMSA 111 39


LAB COURSE-II | CAMS-20P1

#4 Write a Java program to compute the sum of the 2+4+6+---------N Terms.

This is the required code:

package javaapplication1;
import java.util.Scanner;
public class week2Q4 {
public static void main(String[] args){
Scanner a=new Scanner(System.in);
System.out.println("Enter the number of even numbers for which sum is to be computed: ");
int N=a.nextInt();
int sum=0;
int b=0;
for(int i=1;i<=N;i++){
b=b+2;
sum+=b;
}
System.out.println("Sum of "+N+" even integers is: "+sum);
}
}

And this is its output:

#5 Shown below is a Floyd’s triangle:

BILAL AHMAD 21CAMSA 111 40


LAB COURSE-II | CAMS-20P1

1
23
456
7 8 9 10
11 12 13 14
15 16 17 18 19
i) Write a program to print the above triangle.
ii) Modify the program to produce the following form of Floyd’s triangle.
1
01
101
0101
10101
010101

(i)This is the required code for the given Floyd’s triangle:

package javaapplication1;
public class WeekQ5 {
public static void main(String[] args){
System.out.println("Floyd's triangle will be : ");
int k=1;
for(int j=1;j<=6;j++){
for(int i=1;i<=j;i++){
if(i==5) {
continue; }
System.out.print(k + " ");
k++; }
System.out.println(); }

BILAL AHMAD 21CAMSA 111 41


LAB COURSE-II | CAMS-20P1

} }
And this is its output:

(ii) Given below is the required code for the given triangle:

package javaapplication1;
public class Week2q5ii {
public static void main(String[] args) {
int p,q;
for(int i=1;i<=6;++i) {
if (i%2==0) {
p=1;
q=0; }
else{
p=0;
q=1; }
for(int j=1;j<=i;++j) {
if(j%2==0) {
System.out.print(p+""); }
else{
System.out.print(q+""); }
}
System.out.println();

BILAL AHMAD 21CAMSA 111 42


LAB COURSE-II | CAMS-20P1

} } }
And this is its output:

#6 Write a program in the sequence 0, 1, 1, 2, 3, 5, 8, 13, 21 ……………… is


called Fibonacci numbers. Write a program using a do…while loop to
calculate and print the first m Fibonacci numbers.

This is the required code for the Fibonacci series:

package javaapplication1;
import java.util.Scanner;
public class week2Q6 {
public static void main(String[] args){
Scanner a=new Scanner(System.in);
int m;
System.out.println(“Enter the number of terms of fibonacci sequence that u wish to compute: “);
m=a.nextInt();
int i=1;
int n1=0;
int n2=1;
int n3=0;
System.out.print(“fibonacci series till “+m+”terms is: “);
do{
System.out.println(n1+” ,”);
BILAL AHMAD 21CAMSA 111 43
LAB COURSE-II | CAMS-20P1

n3=n1+n2;
n1=n2;
n2=n3;
i++;
}
while(i<=m);
}
}
And this is its output:

#7 Write a java program to print the multiplication table of a number.

This is the required code:

package javaapplication1;
import java.util.Scanner;
public class week2q7 {
public static void main(String[] args){
Scanner s=new Scanner(System.in);
System.out.println("Enter the number for which multiplication table must be printed: ");
int n;
n=s.nextInt();
int product = 0;
System.out.println("Table of"+n+"is: ");
BILAL AHMAD 21CAMSA 111 44
LAB COURSE-II | CAMS-20P1

for(int i=1;i<=10;i++){
product=n*i;
System.out.println(n+" * "+i+" = "+product); }
} }
And this is its output:

#8 Write a java program to find Perfect Number from 1 to 100.

This is the required code for perfect number:

package javaapplication1;
public class week2q8 {
public static void main(String[] args) {
int i = 0,j,c;
for(j=1;i<=100;i++) {
c=0;
for(j=1;j<i;j++) {
if(i%j==0)
c+=j; }
if(c==i)
System.out.println(i); }

BILAL AHMAD 21CAMSA 111 45


LAB COURSE-II | CAMS-20P1

}
}
This is its output:

#9 Write a java program to convert Decimal Number to Binary, Octal and


Hexadecimal.

This is the required code:

package javaapplication1;
import java.util.Scanner;
public class Week2Q9 {
public static void main(String[] args){
Scanner s=new Scanner(System.in);
System.out.println("Enter any number: ");
int i=s.nextInt();
System.out.println("The value of number in Binary is: "+Integer.toBinaryString(i));
System.out.println("The value of number in Octal is: "+Integer.toOctalString(i));
System.out.println("The value of number in hexadecimal is: "+Integer.toHexString(i));
}
}
And this is its output:

BILAL AHMAD 21CAMSA 111 46


LAB COURSE-II | CAMS-20P1

#10 Write a java program to find Roots of Quadratic Equation.


This is the required code:

package javaapplication1;
import java.lang.Math;
import java.util.Scanner;
public class Week2Q10 {
public static void main(String[] args){
Scanner s=new Scanner(System.in);
System.out.println("Enter the value for coefficient a: ");
double a=s.nextDouble();
System.out.println("Enter the value for coefficient b: ");
double b=s.nextDouble();
System.out.println("Enter the value of constant term c: ");
double c=s.nextDouble();
double d=(Math.pow(b,2)-4*a*c);
double dscr=Math.sqrt(d);
if(d<0){
System.out.println("The given equation has no real roots"); }
else {
double x1=(-b+dscr)/(2*a);
double x2=(-b-dscr)/(2*a);
System.out.println("Roots of the following equation are: "+x1+" and "+x2); }
} }
This is its output:

BILAL AHMAD 21CAMSA 111 47


LAB COURSE-II | CAMS-20P1

WEEK 3

BILAL AHMAD 21CAMSA 111 48


LAB COURSE-II | CAMS-20P1

WEEK 3

#1 Write a Java program to show uses of all Math class methods.


This is the required code:

package javaapplication2week3;
import java.util.Scanner;
public class Week3Q1 {
public static void main(String[] args){
double x,y;
Scanner s=new Scanner(System.in);
System.out.println("Enter first value: ");
x=s.nextDouble();
System.out.println("Enter the second value: ");
y=s.nextDouble();
System.out.println("The ceil value of x is: "+Math.ceil(x));
System.out.println("The ceil value of y is: "+Math.ceil(y));

System.out.println("The floor value of x is: "+Math.floor(x));


System.out.println("The floor value of y is: "+Math.floor(y));

System.out.println("log of x is: "+Math.log(x));


System.out.println("log of y is: "+Math.log(y));

System.out.println("exp of x is: "+Math.exp(x));


System.out.println("exp of y is: "+Math.exp(y));

BILAL AHMAD 21CAMSA 111 49


LAB COURSE-II | CAMS-20P1

System.out.println("log10 of x is: "+Math.log10(x));


System.out.println("log10 of y is: "+Math.log10(y));

System.out.println("Greater value among x and y is: "+Math.max(x,y));


System.out.println("Lesser value among x and y is: "+Math.min(x,y));

System.out.println("Round value of x is: "+Math.round(x));


System.out.println("Round value of y is: "+Math.round(y));

System.out.println("4th power of x is: "+Math.pow(x,4));


System.out.println("4th power of y is: "+Math.pow(y,4));

System.out.println("Square root of x is: "+Math.sqrt(x));


System.out.println("Square root of y is: "+Math.sqrt(y));

System.out.println("Signum of x is: "+Math.signum(x));


System.out.println("Signum of y is: "+Math.signum(y));

System.out.println("Value in radian of x is: "+Math.toRadians(x));


System.out.println("Value in radian of y is: "+Math.toRadians(y));
System.out.println("Sine of x is: "+Math.sin(x));
System.out.println("Sine of y is: "+Math.sin(y));
System.out.println("Cosine of x is: "+Math.cos(x));
System.out.println("Cosine of y is: "+Math.cos(y));
System.out.println("Tan of x is: "+Math.tan(x));
System.out.println("Tan of y is: "+Math.tan(y));
} }
And its output is given on the next page:

BILAL AHMAD 21CAMSA 111 50


LAB COURSE-II | CAMS-20P1

#2 Write a program to accept three digits (i.e. 0 - 9) and print all its possible
combinations. (For example, if the three digits are 1, 2, and 3 then all
possible combinations are: 123, 132,213, 231, 312, 321).

The program required is given below:

package javaapplication2week3;
import java.util.Scanner;
import java.lang.Math;
public class Week3Q2 {

BILAL AHMAD 21CAMSA 111 51


LAB COURSE-II | CAMS-20P1

public static void main(String[] args){


Scanner s=new Scanner(System.in);
System.out.println("Enter first digit(any number from 0-9)");
int x=s.nextInt();
System.out.println("Enter second digit(any number from 0-9)");
int y=s.nextInt();
System.out.println("Enter third number(any number from 0-9)");
int z=s.nextInt();
int a[]={x,y,z};
if(x<=9&&y<=9&&z<=9){
for(x=0;x<3;x++){
for(y=0;y<3;y++){
for(z=0;z<3;z++){
if(x!=y&&y!=z&&z!=x){
System.out.println(a[x]+""+a[y]+""+a[z]);
}
}
}
}
}
} }
And this is its output:

BILAL AHMAD 21CAMSA 111 52


LAB COURSE-II | CAMS-20P1

#3 Write a program to calculate the area of triangle, square, circle, rectangle


by using method overloading.

This is the required program:

package javaapplication2week3;
public class Week3Q3 {
void area(int b,int h){
System.out.println("The area of triangle is "+((float)0.5*b*h)+" sq units");
}
void area(double x){
System.out.println("The area of square is "+Math.pow(x,2)+" sq units");
}
void area(int r){
double z=3.14*r*r;
System.out.println("The area of the circle is "+z+" sq units");
}
void area(double x,double y){
System.out.println("The area of rectangle is "+x*y+" sq units");
}
}
class overload{
public static void main(String[] args){
Week3Q3 ob=new Week3Q3();
ob.area(14, 7);
ob.area(5);
ob.area(7);
ob.area(16, 14);
} }
BILAL AHMAD 21CAMSA 111 53
LAB COURSE-II | CAMS-20P1

And this is its output:

#4 Write a Java Program which prompts the user to enter 4 numbers. The
program will then compute and display their sum and their product.

This is the required code:

package javaapplication2week3;
import java.util.Scanner;
public class Week3Q4 {
public static void main(String[] args){
double x,y,z,w,sum,product;
Scanner s=new Scanner(System.in);
System.out.println("Enter first number: ");
x=s.nextDouble();
System.out.println("Enter the second number: ");
y=s.nextDouble();
System.out.println("Enter the third number: ");
z=s.nextDouble();
System.out.println("Enter the fourth number: ");
w=s.nextDouble();
sum=x+y+z+w;
product=x*y*z*w;
System.out.println("Sum of the four numbers entered is: "+sum);
System.out.println("Product of the four numbers entered is: "+product); } }
BILAL AHMAD 21CAMSA 111 54
LAB COURSE-II | CAMS-20P1

And this is its output:

#5 Write a Java program which reads a 4-digit number and prints the digits
on separate lines. (Each digit is printed on one line).

Its code is given below:

package javaapplication2week3;
import java.util.Scanner;
public class Week3Q5 {
public static void main(String[] args){
Scanner s=new Scanner(System.in);
int n,TH,H,T,O;
System.out.println("Enter a four digit number: ");
n=s.nextInt();
System.out.println();
TH=n/1000;
System.out.println(TH);
H=(n%1000)/100;
System.out.println(H);
T=((n%1000)%100)/10;

BILAL AHMAD 21CAMSA 111 55


LAB COURSE-II | CAMS-20P1

System.out.println(T);
O=(((n%1000)%100)%10);
System.out.println(O);
}
}

Its output is given below:

#6 The intersection method computes the intersection of two rectangles- that


is, the rectangle that is formed by two overlapping rectangles: You call this
method as follows:
Rectangle r3 =r1.intersection (r2);
Write a program that constructs two rectangle objects, prints them, and then
prints their intersection. What happens when the rectangles do not overlap?

This is the required code:

package javaapplication2week3;
import java.awt.Rectangle;
import java.util.Scanner;
public class Week3Q6 {
public static void main(String[] args){
Scanner s=new Scanner(System.in);
System.out.println("Enter height of first rectangle: ");
BILAL AHMAD 21CAMSA 111 56
LAB COURSE-II | CAMS-20P1

int h1=s.nextInt();
System.out.println("Enter width of first rectangle: ");
int w1=s.nextInt();
System.out.println("Enter x-coordinate of the first rectangle:");
int x1=s.nextInt();
System.out.println("Enter y-coordinate of the first rectangle: ");
int y1=s.nextInt();
System.out.println("Enter height of ssecond rectangle ");
int h2=s.nextInt();
System.out.println("Enter width of second rectangle: ");
int w2=s.nextInt();
System.out.println("Enter x-coordinate of second rectangle: ");
int x2=s.nextInt();
System.out.println("Enter y-coordinate of second rectangle: ");
int y2=s.nextInt();
Rectangle r1=new Rectangle(h1,w1,x1,y1);
System.out.println("First rectangle is: "+r1);
Rectangle r2=new Rectangle(h2,w2,x2,y2);
System.out.println("Second rectangle is: "+r2);
Rectangle r3 = r1.intersection(r2);
System.out.println("Intersecting rectangle is: "+r3);
}
}

Its output is given on the next page:

BILAL AHMAD 21CAMSA 111 57


LAB COURSE-II | CAMS-20P1

#7 Write an interactive java program that reads in integers until a 0 is


entered. If it encounters 0 as input, then it should display:
- the total no. of even and odd integers.
- average value of even integers.
- average value of odd integers.

This is the required code:

package javaapplication2week3;
import java.util.Scanner;
public class Week3Q7 {
public static void main(String[] args){
int even=0,odd=0,evensum=0,oddsum=0;
Scanner s=new Scanner(System.in);
System.out.println("Enter as many numbers as u want : ");
for(int i=1;i>0;i++) {

BILAL AHMAD 21CAMSA 111 58


LAB COURSE-II | CAMS-20P1

int n=s.nextInt();
if( n==0){
System.out.println("You have entered a 0. Loop ended.");
break; }
if(n%2==0){
even++;
evensum+=n;
}else{
odd++;
oddsum+=n;
}
}
System.out.println("The number of even integers entered is: "+even+" And the number of odd
integers entered is: "+odd);
System.out.println("Average value of even integers entered is: "+evensum/even);
System.out.println("Average value of odd integers entered is: "+oddsum/odd);
}
}

Its output is given below:

BILAL AHMAD 21CAMSA 111 59


LAB COURSE-II | CAMS-20P1

#8 Write a java program to print a list of prime numbers between a given


range that you entered from the keyboard.

Required code is given below:

package javaapplication2week3;
import java.util.Scanner;
public class Week3Q8 {
public static void main(String[] args){
int n1,n2;
Scanner s=new Scanner(System.in);
System.out.println("Enter the upper range: ");
n2=s.nextInt();
System.out.println("Enter the lower range :");
n1=s.nextInt();
System.out.println("Prime numbers between "+n1+" and "+n2+" are given below: ");
int i,j;
for(i=n1;i<n2;i++){
for(j=2;j<i;j++)
{ if(i%j==0)
break;
}
if(j==i)
System.out.print(i+" , ");
}
}} Its output is:

BILAL AHMAD 21CAMSA 111 60


LAB COURSE-II | CAMS-20P1

#9 Write an interactive program to generate the divisors of a given integers.

Required code is given below:

package javaapplication2week3;
import java.util.Scanner;
public class Week3Q9 {
public static void main(String[] args)
{
int n;
System.out.println("Enter the integer whose divisors are to be printed: ");
Scanner s=new Scanner(System.in);
n=s.nextInt();
System.out.println("Divisors of "+n+" are : ");
for(int i=1;i<=n;i++){
if(n%i==0){
System.out.print(i+" , ");
}
}
}
}

Its Output is given below:

BILAL AHMAD 21CAMSA 111 61


LAB COURSE-II | CAMS-20P1

#10 Write a java program to print Sum of Series 1-(x/1! +x2/2!+......+xn/n!).

This is the required code:

package javaapplication2week3;
import java.util.Scanner;
import java.lang.Math;
public class Week3Q10 {
public static void main(String[] args){
int x,n,fact=1;
double sum=0,series;
Scanner s=new Scanner(System.in);
System.out.println("Enter the value for which series is to be printed: ");
x=s.nextInt();
System.out.println("Enter the number of terms for which the series is to be printed: ");
n=s.nextInt();
for(int i=1;i<=n;i++){
fact=fact*i;
sum=sum+(Math.pow(x, i)/fact);
}
series=1-sum;
System.out.println("Sum of the series until "+n+" terms is: "+series);
}}
Its output is:

BILAL AHMAD 21CAMSA 111 62


LAB COURSE-II | CAMS-20P1

WEEK 4

BILAL AHMAD 21CAMSA 111 63


LAB COURSE-II | CAMS-20P1

WEEK 4
#1 Write Java program involving two classes: OddAndEven &
TestOddAndEven. OddAndEven has the following:
• Instance varaibales countOfOdd and countOfEven both of type int.
• A method addNumber that takes a number as parameter and increment
countOfOdd, if the number is odd, else increment countOfEven.
• A method toString that returns a string in the form: “Number of Odd: x,
Number of Even: y”, where x and y are the values of the instance variables.
The TestOddAndEven class first creates OddAndEven object, then in a
loop,read a number and use it to call the addNumber method until the user
enters Q. Finally, it prints the count of odd and even numbers entered.

Given below is its code:

package javaapplication3week4;
import java.util.Scanner;
class OddandEven{
int countofEven,countofOdd;
void addNumber(int n){
if(n%2==0){
countofEven++;
}else{
countofOdd++;
}
}
public String toString(){
return"Number of even: "+countofEven+" Number of odd: "+countofOdd;
}
}

BILAL AHMAD 21CAMSA 111 64


LAB COURSE-II | CAMS-20P1

public class Q1 {
public static void main(String[] args){
OddandEven o=new OddandEven();
Scanner s=new Scanner(System.in);
for(int i=1;i>0;i++){
System.out.println("Enter any number or q to stop: ");
String b=s.nextLine();
if(b.equals("q")&&!b.equals("Q")){
} else {
break;
}
int a=Integer.parseInt(b);
o.addNumber(a);
}
System.out.println(o);
}
}
And this is its output:

BILAL AHMAD 21CAMSA 111 65


LAB COURSE-II | CAMS-20P1

#2 Design a class Circle and implement the following methods:


• Define a circle method to compute its area
• Define a circle method to compute its perimeter
• Define a method that takes a given point represented by a pair of numbers
and checks whether or not the point is inside the circle.The circle class
needs to have instance variables to store the radius of the circle, and the x
and y coordinates of the centre. Add main program to test the class Circle
repeatedly, until user enters negative value for the radius of the circle.

This is its code:

package javaapplication3week4;
import java.lang.Math;
import java.util.Scanner;
public class Week4Q2 {
static class Circle {
int radius;
double x, y;
Circle(int radius, double x, double y) {
this.radius = radius;
this.x = x;
this.y = y;
}
double area() {
double areaCircle = 3.14 * radius * radius;
return areaCircle;
}
double perimeter() {
double perimeterCircle = 2 * 3.14 * radius;
return perimeterCircle;
BILAL AHMAD 21CAMSA 111 66
LAB COURSE-II | CAMS-20P1

}
void checkpoint(double x1, double y1) {
double D = Math.sqrt(Math.pow((x – x1), 2) + Math.pow((y – y1), 2));
if (D < radius) {
System.out.println(“(“ + x1 + “,” + y1 + “) is inside Circle.”);
} else {
System.out.println(“Points are not inside Circle.”);
}
}
public static void main(String[] args){
Scanner obj1 = new Scanner(System.in);
while (true) {
System.out.println(“Enter radius of Circle”);
int rad = obj1.nextInt();
if (rad < 0) {
System.out.println(“Negative radius doesnot exist!!”);
break;
}
System.out.println(“Enter x coordinate of Centre”);
double xCoordinate = obj1.nextDouble();
System.out.println(“Enter y coordinate of Centre”);
double yCoordinate = obj1.nextDouble();
System.out.println(“Enter point to check inside circle or not.”);
System.out.println(“X coordinate”);
double x1 = obj1.nextDouble();
System.out.println(“Y coordinate”);
double y1 = obj1.nextDouble();
Circle obj = new Circle(rad, xCoordinate, yCoordinate);
System.out.println(“Area of Circle = “ + obj.area());
BILAL AHMAD 21CAMSA 111 67
LAB COURSE-II | CAMS-20P1

System.out.println(“Perimeter of Circle = “ + obj.perimeter());


obj.checkPoint(x1, y1);
}
}
}
}

And this is its output:

#3 Write a program in Java that reads in text and prints as output the
following:
• The number of words in the text
• The number of sentences in the text
• The number of times the letter “e” occurs in the text
• The number of times the letter “z” occurs in the text
(Note: Use StringTokenizer class)

This is the required code:

BILAL AHMAD 21CAMSA 111 68


LAB COURSE-II | CAMS-20P1

package javaapplication3week4;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Week4Q3 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in) ;
System.out.print(" Please enter your Text: " );
String text = sc.nextLine( ) ;
StringTokenizer st = new StringTokenizer(text," ");
/* Prints the number of tokens present in the String */
System.out.println("Number of words in the text is : " + st.countTokens() );
int eCount = 0 ; int zCount = 0 ;
int sentenCount = 0 ;
while (st.hasMoreTokens() ) {
String TokenCheck= st.nextToken() ;
for (int i = 0 ;i< TokenCheck.length() ; i++) {
if (TokenCheck.charAt(i) == 'e')
{ eCount++;}
else if (TokenCheck.charAt(i) == 'z')
{ zCount++; }
else if (TokenCheck.charAt(i) == '.')
{ sentenCount++;
}
else continue;
} }
System.out.println("Number of sentences in the text : " +sentenCount );
System.out.println("Number of times the letter 'e' occurs in the text : " +eCount );
System.out.println("Number of times the letter 'z' occurs in the text : " +zCount ); } }

BILAL AHMAD 21CAMSA 111 69


LAB COURSE-II | CAMS-20P1

And this is its result:

#4 A salesperson is paid commission based on the sales he makes as shown


by the following table:

Write a class Commission which has an instance variable sale, an


appropriate constructor, and a method commission () that returns the
commission. Now write a demo class to test the Commission class by
reading a sale from the user, using it to create a Commission object after
validating that the value is not negative. Finally, call the commission ()
method to get and print the commission. If the sales are negative, your demo
should print the message “Invalid Input”.

Given below is its code:

package javaapplication3week4;
import java.util.Scanner;
class Commission {
public double sale ;
Commission ( double sale ) // constructor
{ this . sale = sale ;
}
public double commission ( double sale ) // method

BILAL AHMAD 21CAMSA 111 70


LAB COURSE-II | CAMS-20P1

{ double comm ;
if ( sale < 500 ) {
comm = 2.0*sale/100 ;
}
else if( sale >= 500 && sale < 5000 )
{ comm = 5.0*sale/100 ;
}
else{ // ( sale >= 5000 )
comm = 8.0*sale/100 ;
}
return comm;
}
}
public class Week4q4 {
public static void main (String [ ] args) {
int p ;
Scanner sc = new Scanner( System.in) ;
System.out.print("Please enter your sale : ");
double sale = sc.nextDouble(); Commission obj = new Commission ( sale ) ;
if (sale > 0)
System.out.println("Commision is: " + obj.commission(obj.sale) ) ; // method call
else
System.out.println("Invalid Input”.");
} }
And this is its result:

BILAL AHMAD 21CAMSA 111 71


LAB COURSE-II | CAMS-20P1

#5 The certain instructor assigns letter grade for his course based on the
following table:

Write a class, Grader, which has an instance variable, score, an appropriate


constructor and appropriate method letterGrade() that returns the letter
grade as a String.Now write a demo class to test the Grader class by reading
a score from the user, using it to create a Grader object after validating that
the value is not negative and is not greater than 100. Finally, call the
letterGrade() method to get and print the grade.

Required code is given below:

package javaapplication3week4;
import java.util.Scanner;
class Grader
{
public int score ;
Grader ( int marks)
{ score = marks ;
}
public String letterGrade(int marks )
{ String grade ;
if (marks >= 90 )
grade = "A+";
else if (marks >= 85 )

BILAL AHMAD 21CAMSA 111 72


LAB COURSE-II | CAMS-20P1

grade = "A";
else if (marks >= 80 )
grade = "B+";
else if (marks >= 75 )
grade = "B";
else if (marks >= 65 )
grade = "C+";
else if (marks >= 60 )
grade = "C";
else if (marks >= 55 )
grade = "D+";
else if (marks >= 50 )
grade = "D";
else //if (marks < 50 )
grade = "F" ; return grade;
}}
public class Week4Q5 {
public static void main (String [ ] args ) {
Scanner sc = new Scanner (System.in);
System.out.print("Please enter your Score: ");
int marks = sc.nextInt() ;
Grader obj = new Grader(marks);
if (marks > 0 && marks < 100 )
{ System.out.println("Your grade is: " + obj.letterGrade(marks));
}
else
System.out.println("INVALID Input");
}
}
BILAL AHMAD 21CAMSA 111 73
LAB COURSE-II | CAMS-20P1

And this is its output:

#6 Create a class named 'Student' with String variable 'name' and integer
variable 'roll_no'. Assign the value of roll_no as '2' and that of name as "John"
bycreating an object of the class Student.

This is the required input:

package javaapplication3week4;
import java.util.Scanner ;
class Student {
public String name ;
public int roll_no ;
Student ( int Roll , String name ) {
roll_no = Roll ;
this.name = name ; }
public void Display ( ) {
System.out.println("Name of Student: " + name );
System.out.println("ROll number of Student: " + roll_no );
}}
public class Week4Q6 {
public static void main (String[ ] args ) {
Student obj = new Student(2 , "John");
obj.Display ( ) ;
} }

BILAL AHMAD 21CAMSA 111 74


LAB COURSE-II | CAMS-20P1

And this is its output:

#7 Write a Java class Clock for dealing with the day time represented by
hours, minutes, and seconds. Your class must have the following features:
Three instance variables for the hours (range 0 - 23), minutes (range 0 -
59),and seconds (range 0 - 59).
Three constructors:
• default (with no parameters passed; is should initialize the represented time
to 12:0:0)
• a constructor with three parameters: hours, minutes, and seconds.
• a constructor with one parameter: the value of time in seconds since
midnight (it should be converted into the time value in hours, minutes,and
seconds)
Instance methods:
• a set-method method setClock() with one parameter seconds since
midnight(to be converted into the time value in hours, minutes, and seconds
as above).
• get-methods getHours(), getMinutes(), getSeconds() with no parameters
that return the corresponding values.
• set-methods setHours(), setMinutes(), setSeconds() with one parameter
each that set up the corresponding instance variables.
• method tick() with no parameters that increments the time stored in a Clock
object by one second.
• method addClock() accepting an object of type Clock as a parameter. The
method should add the time represented by the parameter class to the time
represented in the current class.
• Add an instance method toString() with no parameters to your class.
toString() must return a String representation of the Clock object in the form
"(hh:mm:ss)", for example "(03:02:34)".

BILAL AHMAD 21CAMSA 111 75


LAB COURSE-II | CAMS-20P1

• Add an instance method tickDown() which decrements the time stored in a


Clock object by one second.
• Add an instance method subtractClock() that takes one Clock parameter
and returns the difference between the time represented in the current
Clock object and the one represented by the Clock parameter. Difference of
time should be returned as an clock object.
Write a separate class ClockDemo with a main() method. The program
should:
• instantiate a Clock object firstClock using one integer seconds since
midnight obtained from the keyboard.
• tick the clock ten times by applying its tick() method and print out the
timeafter each tick.
• Extend your code by appending to it instructions instantiating a Clock
object secondClock by using three integers (hours, minutes, seconds) read
from the keyboard.
• Then tick the clock ten times, printing the time after each tick.
• Add the secondClock time in firstClock by calling method addClock.
• Print both clock objects calling toString method

Create a reference thirdClock that should reference to object of difference of


firstClock and secondClock by calling the method subtractClock().

Given below is the required code:

package javaapplication3week4;
public class WeekQ7 {
static class Clock{
int hours;
int minutes;
int seconds; //---------- Constructors------------
Clock() {

BILAL AHMAD 21CAMSA 111 76


LAB COURSE-II | CAMS-20P1

this.hours = 12;
this.minutes = 0;
this.seconds = 0;
}
Clock(int hours, int minutes, int seconds)
{ this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
}
Clock(int sec)
{
this.hours = sec / 3600;
sec %= 3600;
this.minutes = sec / 60;
sec %= 60; this.seconds = sec;
}//--------------- Setters ---------------
public void setClock(int sec)
{ this.hours = sec / 3600;
sec %= 3600;
this.minutes = sec / 60;
sec %= 60;
this.seconds = sec;
}
public void setHours(int hours)
{
if(hours > 23)
{ System.out.println("Out of range");
return;}
this.hours = hours;
BILAL AHMAD 21CAMSA 111 77
LAB COURSE-II | CAMS-20P1

}
public void setMinutes(int minutes)
{
if(minutes > 59)
{ System.out.println("Out of range");
return;
}
this.minutes = minutes;
}
public void setSeconds(int seconds)
{
if(seconds > 59){
System.out.println("Out of range");
return;
}
this.seconds = seconds;
}
//-------------Getters------------
public int getHours()
{ return this.hours;
}
public int getMinutes()
{ return this.minutes;
}
public int getSeconds()
{ return this.seconds;

}
//-------------Updaters---------------
BILAL AHMAD 21CAMSA 111 78
LAB COURSE-II | CAMS-20P1

public void tick()


{ this.seconds++;
if(this.seconds > 59)
{ this.seconds = 0;
this.minutes++;
}
if(this.minutes > 59)
{ this.minutes = 0;
this.hours++;
}
if(this.hours > 23)
{ this.hours = 0;
}
}
public void tickDown()
{ this.seconds--;
if(this.seconds < 0){
this.seconds = 59;
this.minutes--;
}
if(this.minutes < 0)
{ this.minutes = 59;
this.hours--;
}
if(this.hours < 0)
{ this.hours = 23;
}
}
public void addClock(Clock Obj){
BILAL AHMAD 21CAMSA 111 79
LAB COURSE-II | CAMS-20P1

this.seconds += Obj.seconds;
this.minutes += Obj.minutes;
this.hours += Obj.hours;
if(this.seconds >= 60){
this.seconds -= 60;
this.minutes++; }
if(this.minutes >= 60)
{
this.minutes -= 60;
this.hours++;
}
if(this.hours >= 24)
{ this.hours -= 24;
}
}
public void subtractClock(Clock Obj)
{
this.seconds -= Obj.seconds;
this.minutes -= Obj.minutes;
this.hours -= Obj.hours;
if(this.seconds < 0)
{
this.seconds += 60;
this.minutes--;
}
if(this.minutes < 0)
{
this.minutes += 60;
this.hours--;
BILAL AHMAD 21CAMSA 111 80
LAB COURSE-II | CAMS-20P1

}
if(this.hours < 0)
{
this.hours += 24;
}
}
public String toString(){
String hrs = "", min = "", sec="";
if(this.hours < 10)
hrs = "0" + this.hours;
else
hrs += this.hours;
if(this.minutes < 10)
min = "0" + this.minutes;
else
min += this.minutes;
if(this.seconds < 10)
sec = "0" + this.seconds;
else
sec += this.seconds;
return (hrs + ":" + min + ":" + sec);
}
}
//---------End of Clock class -----------
public static void main(String[] args){
Clock firstClock = new Clock(4589);
for (int i = 1; i <= 10; i++) {
firstClock.tick();
System.out.print(firstClock .toString() + " ");
BILAL AHMAD 21CAMSA 111 81
LAB COURSE-II | CAMS-20P1

}
System.out.println();
Clock secondClock = new Clock(23,59,40);
for (int i = 1; i <= 10; i++)
{
secondClock.tick();
System.out.print(secondClock.toString() + " ");
}
System.out.println();
firstClock.addClock(secondClock);
System.out.print("After addition : ");
System.out.println(firstClock.toString());
firstClock.subtractClock(secondClock);
System.out.print("After subtraction : ");
System.out.println(firstClock.toString());
}
}

And this is its result:

BILAL AHMAD 21CAMSA 111 82


LAB COURSE-II | CAMS-20P1

WEEK 5

BILAL AHMAD 21CAMSA 111 83


LAB COURSE-II | CAMS-20P1

WEEK 5
#1 Implement a Student class with the following fields, constructors and
methods:
Fields:
• name;
• totalScore;
• numberOfQuizzes;
Constructors:
• public Student(String name, double score)
• public Student(double score, String name)
• public Student(String name)
Methods:
• public String getName()
• public double getAverage() //this should return zero if no quiz has been
taken.
• public double getTotalScore()
• public void addQuiz(double score)
• public void printStudent() //this should print the student’s name and
average score.
• public String toString()
Write an application TestStudent that reads a student name and use the
Student class to create a Student object. Then read the scores of the student
in three quizzes and add each to the totalScore of the student using
addQuiz() method and print the student object.
( Note: Make use of this key word wherever it can be used ).

The required code is given on the next page:

BILAL AHMAD 21CAMSA 111 84


LAB COURSE-II | CAMS-20P1

package javaapplication4week5;
import java.util.Scanner;
class Student{
String name;
double totalScore;
int numberOfQuizzes;
public Student(String name, double score) {
this.name = name;
totalScore = score;
this.numberOfQuizzes = 1;
}
public Student(double score, String name) {
totalScore = score;
this.name = name;
this.numberOfQuizzes = 1;
}
public Student(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void addQuiz(double score) {
totalScore += score;
++this.numberOfQuizzes;
}
public double getAverage() {
if (numberOfQuizzes == 0) {
return 0;
BILAL AHMAD 21CAMSA 111 85
LAB COURSE-II | CAMS-20P1

} else {
return totalScore / numberOfQuizzes;
}
}
public double getTotalScore() {
return totalScore;
}
public void printStudent() {
System.out.println("Name : " + name + "\tAverage is : " +
this.getAverage());
}
@Override
public String toString(){
return name+" "+totalScore+" "+numberOfQuizzes;
}
}
public class Week5Q1 {
public static void main(String[] args) {
Scanner obj = new Scanner(System.in);
System.out.print("Enter name of Student : ");
String name = obj.nextLine();
Student obj1 = new Student(name);
for (int i = 1; i < 4; i++) {
System.out.println("Enter Quiz " + (i) + " for " + name + " : ");
double score = obj.nextDouble();
obj1.addQuiz(score);
}
obj1.printStudent();
} }
BILAL AHMAD 21CAMSA 111 86
LAB COURSE-II | CAMS-20P1

And this is its result:

#2 Write a program to design a class to represent a bank account. Include


the following members.
Date members:
• Name of depositor
• Account Number
• Type of account
• Balance account in the account
Methods:
• To assign initial values
• To deposit an account
• To withdraw an account after checking balance.
• To display the name and balance

Given below is the required code:

package javaapplication4week5;
import java.util.Scanner;
public class Week5Q2 {
String nameOfDepositor;
int accountNumber;
String typeOfAccount;
BILAL AHMAD 21CAMSA 111 87
LAB COURSE-II | CAMS-20P1

double balance;
void setValues(String name,int accNum,String accType,double balance){
nameOfDepositor = name;
accountNumber = accNum;
typeOfAccount = accType;
this.balance = balance;
}
void deposit(double addMoney){
balance = balance + addMoney;
}
void withdraw(){
Scanner obj = new Scanner(System.in);
System.out.println("Press 1 to Check Balance");
System.out.println("Press 2 to Withdraw Money");
int n = obj.nextInt();
switch(n){
case 1:
System.out.println("Balance : "+balance);
case 2:
System.out.print("Enter amount to withdraw : ");
double withdrawMoney = obj.nextDouble();
if(balance<withdrawMoney){
System.out.println("Insufficient Balance");
}
else{
balance = balance - withdrawMoney;
System.out.println("Withdrawn successfully");
}
}
BILAL AHMAD 21CAMSA 111 88
LAB COURSE-II | CAMS-20P1

}
void display(){
System.out.println("Name : "+nameOfDepositor+"\tBalance : "+balance);
}
public static void main(String[] args){
BankAccount obj = new BankAccount();
obj.setValues("Bilal", 123456, "Savings", 0);
obj.deposit(10000);
obj.withdraw();
obj.display();
}
}

And this is its result:

BILAL AHMAD 21CAMSA 111 89


LAB COURSE-II | CAMS-20P1

WEEK 6

BILAL AHMAD 21CAMSA 111 90


LAB COURSE-II | CAMS-20P1

WEEK 6
#1 Write a program that reads in a sentence from the user and prints it out
with each word reversed, but with the words and punctuation in the original
order.

This is the required code:

package javaapplication5week6;
import java.util.Scanner;
import java.util.StringTokenizer;
public class JavaApplication5Week6 {
public static void main(String[] args) {
String temp = "";
System.out.println("Enter a sentence: ");
Scanner obj = new Scanner(System.in);
String str1 = obj.nextLine();
StringTokenizer st = new StringTokenizer(str1," :,!",true);
System.out.print("Output: ");
while(st.hasMoreTokens()){
String str2 = st.nextToken();
String rev1="";
for(int i =str2.length()-1;i>=0;i--) {
rev1 += str2.charAt(i); }
temp+=(rev1); }
System.out.println(temp);
} }

BILAL AHMAD 21CAMSA 111 91


LAB COURSE-II | CAMS-20P1

And this is its output:

#2 Write a program where interface can be used to support multiple


inheritances. Develop a standalone Java program for this.

This is the required input code:

package javaapplication5week6;
interface University{
public void getEnrol();
}
interface Department{
public void facultyNo();
}
class Students implements University,Department{
String enrolNo;
String facNo;
String name;
@Override
public void getEnrol(){
System.out.println(this.name+"'s enrol no = "+this.enrolNo);
}
@Override
public void facultyNo(){
System.out.println(this.name+"'s faculty no= "+this.facNo);
BILAL AHMAD 21CAMSA 111 92
LAB COURSE-II | CAMS-20P1

}
}
public class Week6Q2 {
public static void main(String[] args){
Students s =new Students();
s.name="BILAL";
s.enrolNo="GI1527";
s.facNo="21 CAMSA 111";
s.facultyNo();
s.getEnrol();
}
}

And this is its output:

#3 Write a program that reads in three strings and sorts them


lexicographically.
Hint: Enter strings: Charlie Able Banker
Output: Able Banker Charlie
This is the required code:

package javaapplication5week6;
import java.util.Scanner;
public class Week6Q3 {
static String[] sortLexo(String[] s1){
BILAL AHMAD 21CAMSA 111 93
LAB COURSE-II | CAMS-20P1

for(int i = 0;i< s1.length-1;i++){


for(int j=0;j<s1.length-1-i;j++){
if(s1[j].charAt(0)>s1[j+1].charAt(0)){
String temp ="";
temp = s1[j];
s1[j] = s1[j+1];
s1[j+1] = temp;
}
}
}
return s1;
}
public static void main(String[] args) {
Scanner obj = new Scanner(System.in);
String[] s1 = new String[3];
for(int i=0;i<s1.length;i++){
System.out.print("Enter word "+(i+1)+" : ");
s1[i] = obj.next();
}
sortLexo(s1);
for(int i=0;i<s1.length;i++){
System.out.print(s1[i]+" ");
} } }

And this is its output:

BILAL AHMAD 21CAMSA 111 94


LAB COURSE-II | CAMS-20P1

#4 Implement the classes for the shapes using an interface for the common
methods, rather than inheritance from the super class, while still Shape as a
base class.

This is the required code:

package javaapplication5week6;
interface Shapes{
int area(int a,int b);
int perimeter(int c, int d);
}
class Rectangle implements Shapes{
public int area(int length,int breadth){
return length*breadth;
}
public int perimeter(int length,int breadth){
return 2*(length+breadth);
}
}
class Square implements Shapes{
public int area(int length,int breadth){
return length*breadth;
}
public int perimeter(int length,int breadth){
return 2*(length+breadth);
}
}
public class Week6Q4 {
public static void main(String[] args){

BILAL AHMAD 21CAMSA 111 95


LAB COURSE-II | CAMS-20P1

Rectangle rec = new Rectangle();


Square sqr = new Square();
System.out.println("Area of rectangle = "+rec.area(12, 4));
System.out.println("Perimeter of rectangle = "+rec.area(12, 4));
System.out.println("Area of Square = "+sqr.area(12, 12));
System.out.println("Perimeter of Square = "+sqr.area(12, 12));
}
}

And this is its result:

#5 Implement a super class Person. Make two classes, Student and


Instructor,inherit from Person. A person has a name and a year of birth. A
student has a major, and an instructor has a salary. Write the class definitions,
the constructors, and the methods toString for all classes. Supply a test
program that tests these classes and methods.

This is the required code:

package javaapplication5week6;
class Person{
String name;
int year;
public Person(){};
public Person(String name,int year){

BILAL AHMAD 21CAMSA 111 96


LAB COURSE-II | CAMS-20P1

this.name=name;
this.year=year;
}
@Override
public String toString(){
return name+" "+year;
}
}
class Student extends Person{
String major;
public Student(String major,String name,int year){
super(name,year);
this.major=major;
}
@Override
public String toString(){
return name+" "+year+" "+major;
}
}
class Instructor extends Person{
double salary;
public Instructor(double salary,String name,int year){
super(name,year);
this.salary=salary;
}
@Override
public String toString(){
return name+" "+year+" "+salary;
}
BILAL AHMAD 21CAMSA 111 97
LAB COURSE-II | CAMS-20P1

}
public class Week6Q5 {
public static void main(String[] args){
Student stu = new Student("Computer Science","Bilal",1998);
Instructor ins = new Instructor(20000,"Bilal",1998);
System.out.println(stu);
System.out.println(ins);
}
}

And this is its result:

#6 Write a Java class Complex for dealing with complex number. Your class
must have the following features:
• Instance variables :
o realPart for the real part of type double
o imaginaryPart for imaginary part of type double.
• Constructor:
o public Complex (): A default constructor, it should initialize the number to 0,
0)
o public Complex (double realPart, double imaginaryPart): A constructor with
parameters, it creates the complex object by setting the two fields to the
passed values.
• Instance methods:
o public Complex add (Complex otherNumber): This method will find the sum
of the current complex number and the passed complex number. The methods
returns a new Complex number which is the sum of the two.
BILAL AHMAD 21CAMSA 111 98
LAB COURSE-II | CAMS-20P1

o public Complex subtract (Complex otherNumber): This method will find the
difference of the current complex number and the passed complex number.
The methods returns a new Complex number which is the difference of the
two.
o public Complex multiply (Complex otherNumber): This method will find the
product of the current complex number and the passed complex number.
The methods returns a new Complex number which is the product of the two.
o public Complex divide (Complex otherNumber): This method will find the ...
of the current complex number and the passed complex number. The
methods returns a new Complex number which is the ... of the two.
o public void setRealPart (double realPart): Used to set the real part of this
complex number.
o public void setImaginaryPart (double realPart): Used to set the imaginary
part of this complex number.
o public double getRealPart(): This method returns the real part of the
complex number
o public double getImaginaryPart(): This method returns the imaginary part
of the complex number
o public String toString(): This method allows the complex number to be
easily printed out to the screen
Write a separate class ComplexDemo with a main() method and test the
Complex class methods.

This is the required code:

package javaapplication5week6;
class Complex{
double realPart;
double imaginaryPart;
public Complex (){
realPart = 0;
imaginaryPart = 0;

BILAL AHMAD 21CAMSA 111 99


LAB COURSE-II | CAMS-20P1

}
public Complex (double realPart, double imaginaryPart){
this.realPart = realPart;
this.imaginaryPart = imaginaryPart;
}
public Complex add (Complex otherNumber){
Complex num = new Complex();
num.realPart =this.realPart + otherNumber.realPart;
num.imaginaryPart =this.imaginaryPart + otherNumber.imaginaryPart;
return num;
}
public Complex subtract (Complex otherNumber){
Complex num = new Complex();
num.realPart =this.realPart - otherNumber.realPart;
num.imaginaryPart =this.imaginaryPart - otherNumber.imaginaryPart;
return num;
}
public Complex multiply (Complex otherNumber){
Complex num = new Complex();
num.realPart = this.realPart*otherNumber.realPart-
(this.imaginaryPart*otherNumber.imaginaryPart);
num.imaginaryPart =
this.realPart*otherNumber.imaginaryPart+(this.imaginaryPart*otherNumber.realPart);
return num;
}
public Complex divide (Complex otherNumber){
Complex temp = new Complex();
Complex c = new Complex();
double d;

BILAL AHMAD 21CAMSA 111 100


LAB COURSE-II | CAMS-20P1

temp.realPart=otherNumber.realPart;
temp.imaginaryPart = -(otherNumber.imaginaryPart);
c=this.multiply(temp);
d=(otherNumber.realPart*otherNumber.realPart) +
(otherNumber.imaginaryPart*otherNumber.imaginaryPart);
System.out.println("d="+d);
if(d==0){
System.out.println("Invalid !!");
}else{
this.realPart = c.realPart/d;
this.imaginaryPart = c.imaginaryPart/d;
}
return this;
}
public void setRealPart (double realPart){
this.realPart = realPart;
}
public void setImaginaryPart (double imaginaryPart){
this.imaginaryPart = imaginaryPart;
}
public double getRealPart(){
return this.realPart;
}
public double getImaginaryPart(){
return this.imaginaryPart;
}
@Override
public String toString(){
return realPart+"+("+imaginaryPart+")i";
BILAL AHMAD 21CAMSA 111 101
LAB COURSE-II | CAMS-20P1

}
}
public class Week6Q6 {
public static void main(String[] args){
Complex com1 = new Complex(3,-2);
System.out.println("Complex number 1 = "+com1);
Complex com2 = new Complex(4,5);
System.out.println("Complex number 2 = "+com2);
Complex com3 = com1.add(com2);
System.out.println("Addition of complex numbers = "+com3);
com3 = com1.subtract(com2);
System.out.println("Subtraction of complex numbers = "+com3);
com3 = com1.multiply(com2);
System.out.println("Multiplication of complex numbers = "+com3);
com3 = com1.divide(com2);
System.out.println("Division of complex numbers = "+com3);
}
}

And this is its result:

BILAL AHMAD 21CAMSA 111 102


LAB COURSE-II | CAMS-20P1

WEEK 7

BILAL AHMAD 21CAMSA 111 103


LAB COURSE-II | CAMS-20P1

WEEK 7
#1 Define a class Employee having private members – id, name, department,
salary. Define default and parameterized constructors. Create a subclass
called “Manager” with private member bonus. Define methods accept and
display in both the classes. Create n objects of the Manager class and
display the details of the manager having the maximum total salary
(salary+bonus).
This is the required code:

package javaapplication6week7;
import java.util.Scanner;
class Employee{
private int id;
private String name;
private String department;
private double salary;
public Employee(){};
public Employee(int id,String name,String department,double salary){
this.id = id;
this.name = name;
this.department = department;
this.salary = salary;
}
public double getSalary(){
return salary;
}
public void accepts(int id,String name,String department,double salary){
this.id = id;

BILAL AHMAD 21CAMSA 111 104


LAB COURSE-II | CAMS-20P1

this.name = name;
this.department = department;
this.salary = salary;
}
public void display(){
System.out.println("Name : "+name);
System.out.println("ID : "+id);
System.out.println("Department : "+department);
System.out.println("Salary : "+salary);
}
}
class Manager extends Employee{
private double bonus;
public void accepts(int id,String name,String department,double
salary,double bonus){
super.accepts(id, name, department, salary);
this.bonus = bonus;
}
@Override
public void display(){
super.display();
System.out.println("Bonus : "+bonus);
System.out.println("Total Salary : "+(this.getSalary()+bonus));
}
}
public class Week7Q1 {
public static void main(String[] args) {
Manager obj = new Manager();
obj.accepts(213, "Bilal", "IT", 50000, 5000);
BILAL AHMAD 21CAMSA 111 105
LAB COURSE-II | CAMS-20P1

obj.display();
}
}

And this is its output:

#2 Write a Java program to create a super class Vehicle having members


Company and price. Derive 2 different classes LightMotorVehicle (members
– mileage) and HeavyMotorVehicle (members – capacity-in-tons). Accept the
information for n vehicles and display the information in appropriate form.
While taking data, ask the user about the type of vehicle first.

The required code is given below:

package javaapplication6week7;
import java.util.Scanner;
class Vehicle{
String Company;
double price;
public Vehicle(){};
public Vehicle(String Company, double price){
this.Company = Company;
this.price = price;
}

BILAL AHMAD 21CAMSA 111 106


LAB COURSE-II | CAMS-20P1

}
class LightMotorVehicle extends Vehicle{
String mileage;
public LightMotorVehicle(String Company, double price,String mileage){
super(Company,price);
this.mileage = mileage;
}
}
class HeavyMotorVehicle extends Vehicle{
String capacity;
public HeavyMotorVehicle(String Company, double price,String capacity){
super(Company,price);
this.capacity = capacity;
}
}
public class Week7Q2 {
public static void main(String[] args){
Scanner obj = new Scanner(System.in);
String Company , mileage,capacity;
double price;
for(int i = 0;i<2;i++){
System.out.println("Press 1 for Light Motor Vehicle");
System.out.println("Press 2 for Heavy Motor Vehicle");
int n = obj.nextInt();
switch (n){
case 1:
obj.nextLine();
System.out.print("Enter Vehicle Company : ");
Company = obj.nextLine();
BILAL AHMAD 21CAMSA 111 107
LAB COURSE-II | CAMS-20P1

System.out.print("Enter it's mileage : ");


mileage = obj.nextLine();
System.out.print("Enter it's price : ");
price = obj.nextDouble();
LightMotorVehicle vehL = new
LightMotorVehicle(Company,price,mileage);
System.out.println("Type of vehicle : Light Motor Vehicle");
System.out.println("Company : "+vehL.Company);
System.out.println("Price : "+vehL.price);
System.out.println("Mileage : "+vehL.mileage);
break;
case 2:
obj.nextLine();
System.out.print("Enter Vehicle Company : ");
Company = obj.nextLine();
System.out.print("Enter it's Capcity : ");
capacity = obj.nextLine();
System.out.print("Enter it's price : ");
price = obj.nextDouble();
HeavyMotorVehicle vehH = new
HeavyMotorVehicle(Company,price,capacity);
System.out.println("Type of vehicle : Light Motor Vehicle");
System.out.println("Company : "+vehH.Company);
System.out.println("Price : "+vehH.price);
System.out.println("Capacity : "+vehH.capacity);
break;
}
}
} }
BILAL AHMAD 21CAMSA 111 108
LAB COURSE-II | CAMS-20P1

And this is its result:

#3 A bank maintains two kinds of accounts - Savings Account and Current


Account. The savings account provides compound interest, deposit and
withdrawal facilities. The current account only provides deposit and
withdrawal facilities. Current account holders should also maintain a
minimum balance. If balance falls below this level, a service charge is
imposed. Create a class Account that stores customer name, account
number,and type of account. From this derive the classes Curr-acct and Sav
acct. Include the necessary methods in order to achieve the following tasks:
• Accept deposit from a customer and update the balance.
• Display the balance.
• Compute interest and add to balance.
• Permit withdrawal and update the balance (Check for the minimum balance,
impose penalty if necessary).
The required code is provided on the next page:

BILAL AHMAD 21CAMSA 111 109


LAB COURSE-II | CAMS-20P1

package javaapplication6week7;

import java.util.Scanner;

class Account {
String cusName;
String typeOfAcc;
long AccNumber;
public Account() {
}
;
public Account(String cusName, String typeOfAcc, long AccNumber) {
this.cusName = cusName;
this.typeOfAcc = typeOfAcc;
this.AccNumber = AccNumber;
}
public void display() {
System.out.println("Name : " + cusName);
System.out.println("Type of account : " + typeOfAcc);
System.out.println("Account Number : " + AccNumber);
}
}
class SavingAccount extends Account {
double balance;
double minBalance = 2000;
public SavingAccount(String cusName, String typeOfAcc, long AccNumber,
double balance) {
super(cusName, typeOfAcc, AccNumber);

BILAL AHMAD 21CAMSA 111 110


LAB COURSE-II | CAMS-20P1

this.balance = balance;
}
public void compoundIntrest(int yr, double rate, int n) {
double interest = balance * (Math.pow(1 + rate / (100 * n), n * yr));
balance += interest;
}
public void deposit(double amount) {
balance += amount;
}
public void withdrawl(double amount) {
if (balance >= amount) {
balance -= amount;
if (balance < minBalance) {
System.out.println("Penality of rs 50");
balance -= 50;
}
} else {
System.out.println("Insufficient Balance !!");
}
}
@Override
public void display() {
super.display();
System.out.println("Minimum balance to maintain : rs " + minBalance);
System.out.println("Current balance : " + balance);
}
}
class CurrentAccount extends Account {

BILAL AHMAD 21CAMSA 111 111


LAB COURSE-II | CAMS-20P1

double balance;
double minBalance = 2000;
public CurrentAccount(String cusName, String typeOfAcc, long AccNumber,
double balance) {
super(cusName, typeOfAcc, AccNumber);
this.balance = balance;
}
public void deposit(double amount) {
balance += amount;
}
public void withdrawl(double amount) {
if (balance >= amount) {
balance -= amount;
if (balance < minBalance) {
System.out.println("Penality of rs 50");
balance -= 50;
}
} else {
System.out.println("Insufficient Balance !!");
}
}
@Override
public void display() {
super.display();
System.out.println("Minimum balance to maintain : rs " + minBalance);
System.out.println("Current balance : " + balance);
}
}

BILAL AHMAD 21CAMSA 111 112


LAB COURSE-II | CAMS-20P1

public class Week7Q3 {


public static void main(String[] args) {
Scanner obj = new Scanner(System.in);
System.out.print("Enter name of customer : ");
String name = obj.nextLine();
System.out.print("Enter type of Account (Saving/Current) : ");
String typeAcc = obj.nextLine();
System.out.println("Enter Balance : ");
double balance = obj.nextDouble();
long accNumber,accNumber2;
if (typeAcc.equals("Saving")) {
while (true) {
System.out.println("Enter Account Number(9 digits) : ");
accNumber = obj.nextLong();
if (accNumber <= 999999999L) {
break;
} else {
System.out.println("Invalid Account Number!!");
System.out.println("Try again!!");
}
}
SavingAccount sacc = new SavingAccount(name, typeAcc, accNumber,
balance);
sacc.display();
System.out.print("Enter amount to deposit : ");
double amountDeposit = obj.nextDouble();
sacc.deposit(amountDeposit);
sacc.display();

BILAL AHMAD 21CAMSA 111 113


LAB COURSE-II | CAMS-20P1

System.out.print("Enter amount to withdraw :");


double amountWithdraw = obj.nextDouble();
sacc.withdrawl(amountWithdraw);
sacc.display();
int yr, n;
double rate;
System.out.println("To print total balance after compound interest.");
System.out.print("Enter time(years) : ");
yr = obj.nextInt();
System.out.print("Enter rate :");
rate = obj.nextInt();
System.out.print("Enter number of times interest compunded anually :");
n = obj.nextInt();
sacc.compoundIntrest(yr, rate, n);
sacc.display();
} else if (typeAcc.equals("Current")) {
while (true) {
System.out.println("Enter Account Number(9 digits) : ");
accNumber2 = obj.nextLong();
if (accNumber2 <= 999999999L) {
break;
} else {
System.out.println("Invalid Account Number!!");
System.out.println("Try again!!");
}
}
CurrentAccount sacc = new CurrentAccount(name, typeAcc,
accNumber2, balance);

BILAL AHMAD 21CAMSA 111 114


LAB COURSE-II | CAMS-20P1

sacc.display();
System.out.print("Enter amount to deposit : ");
double amountDeposit = obj.nextDouble();
sacc.deposit(amountDeposit);
sacc.display();
System.out.print("Enter amount to withdraw :");
double amountWithdraw = obj.nextDouble();
sacc.withdrawl(amountWithdraw);
sacc.display();
} else {
System.out.println("Invalid input!!");
System.out.println("Valid input -> 'Saving' or 'Current'");
}
}
}

Its output has been provided on the next page:

BILAL AHMAD 21CAMSA 111 115


LAB COURSE-II | CAMS-20P1

#4 Define a class called fruit with the following attributes:


• Name of the fruit
• Single fruit or bunch fruit
Define a suitable constructor and displayFruit() method that displays values
of all the attributes. Write a program that creates 2 objects of fruit class and
display their attributes.

The required code is provided on the next page:

BILAL AHMAD 21CAMSA 111 116


LAB COURSE-II | CAMS-20P1

package javaapplication6week7;
import java.util.Scanner;
class Fruit {
String nameOfFruit;
int isSingle;
public Fruit(String f, int a) {
this.nameOfFruit = f;
this.isSingle = a;
}
void displayFruit() {
System.out.println("Name of fruit : " + nameOfFruit);
if (isSingle == 1) {
System.out.println("Type of fruit : Single fruit");
} else {
System.out.println("Type of fruit : Bunch fruit");
}
}
}
public class Week7Q4 {
public static void main(String[] args) {
Scanner obj = new Scanner(System.in);
int n;
String fruit;
for (int i = 0; i < 2; i++) {
System.out.print("Enter name of fruit " + (i + 1) + " : ");
fruit = obj.nextLine();
while (true) {
System.out.println("Press 1 for Single fruit :");
System.out.println("Press 2 for Bunch fruit :");
BILAL AHMAD 21CAMSA 111 117
LAB COURSE-II | CAMS-20P1

n = obj.nextInt();
if (n == 1) {
obj.nextLine();
Fruit single = new Fruit(fruit, n);
single.displayFruit();
break;
} else if (n == 2) {
obj.nextLine();
Fruit bunch = new Fruit(fruit, n);
bunch.displayFruit();
break;
} else {
System.out.println("Invalid input try again!");
}
}
}
}
}

And its result is:

BILAL AHMAD 21CAMSA 111 118


LAB COURSE-II | CAMS-20P1

#5 Write a program where interface can be used to support multiple


inheritances. Develop a standalone Java program for this.

Required code:

package javaapplication6week7;
interface Gps{
void track();
}
interface Camera{
void clickPic();
}
class Phone{
public void call(){
System.out.println("Calling....");
}
}
class SmartPhone extends Phone implements Gps,Camera{
String model;
public SmartPhone(String model){
this.model = model;
}
public String getModel(){
return model;
}
public void track(){
System.out.println("Tracking....");
}
public void clickPic(){
BILAL AHMAD 21CAMSA 111 119
LAB COURSE-II | CAMS-20P1

System.out.println("Clicking picture....");
}
}
public class Week7Q5 {
public static void main(String[] args){
SmartPhone oppo = new SmartPhone("Oppo A83");
System.out.println(oppo.getModel());
oppo.call();
oppo.clickPic();
oppo.track();
}
}

And this is its output:

BILAL AHMAD 21CAMSA 111 120


LAB COURSE-II | CAMS-20P1

WEEK 8

BILAL AHMAD 21CAMSA 111 121


LAB COURSE-II | CAMS-20P1

WEEK 8
#1 Implement the classes for the shapes using an interface for the common
methods, rather than inheritance from the super class, while still Shape as a
base class.
This is the required code:

package javaapplication7week8;
import java.util.Scanner;
interface Shape{
double area();
void print();
}
class Rectangle implements Shape{
double length,width;
public void set(double length,double width){
this.length=length;
this.width=width;
}
public double area(){
return length*width;
}
public void print(){
System.out.println("Area of rectangle is: "+area());
} }
abstract class Circle implements Shape{
double radius;
void set(double radius){

BILAL AHMAD 21CAMSA 111 122


LAB COURSE-II | CAMS-20P1

this.radius=radius;
}
public double area(){
return 3.14*radius*radius;
}
public void print(){
System.out.println("The area of Circle is: "+area());
}}
public class JavaApplication7Week8 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the length and breadth of rectangle: ");
double w=sc.nextDouble();
double l=sc.nextDouble();
Rectangle r=new Rectangle();
r.set(w,l);
r.print();
System.out.println("Enter the radius of the circle: ");
double radius=sc.nextDouble();
Circle c=new Circle() {};
c.set(radius);
c.print();
}}
And this is its result:

BILAL AHMAD 21CAMSA 111 123


LAB COURSE-II | CAMS-20P1

#2 Create a package called "Arithmetic" that contains methods to deal all


arithmetic operations. Also, write a program to use the package.

This is the required package:

package arithmetic;
public class ArithmeticWeek8Q2 {
public int add(int x,int y)
{return x+y;
}
public int sub(int x,int y)
{
return x-y;
}
public int mul(int x,int y)
{
return x*y;
}
public double div(int x,int y)
{
return (double)x/y;
}
public int mod(int x,int y)
{
return x%y;
} }

And program to use the package is given on the next page:

BILAL AHMAD 21CAMSA 111 124


LAB COURSE-II | CAMS-20P1

package arithmetic;
import arithmetic.ArithmeticWeek8Q2;
public class Week8Q2 {
public static void main(String as[])
{
ArithmeticWeek8Q2 m=new ArithmeticWeek8Q2();
System.out.println(m.add(8,5));
System.out.println(m.sub(8,5));
System.out.println(m.mul(8,5));
System.out.println(m.div(8,5));
System.out.println(m.mod(8,5));
}
}
And this is its result:

#3 Write a program to make use of a parameterized method inside a class.


Take the following case: Create a class Box and define a method in this class
which will return the volume of the box. Initialize two objects for your class
and print out the volumes respectively.

The required code is given below:

package javaapplication7week8;
class Box {
double height,width,depth;
BILAL AHMAD 21CAMSA 111 125
LAB COURSE-II | CAMS-20P1

public Box(double width,double height,double depth)


{
this.height=height;
this.width=width;
this.depth=depth;
}
public double volume()
{
double v;
v=height*width*depth;
return v;
}
}
public class Week8Q3 {
public static void main(String[] args) {
Box bc = new Box(8.5,80.3,9.6);
System.out.println("The volume of Box is : "+bc.volume());
}}

And its result is given below:

#4 Write a program that calls a method that throws an exception of type


ArithmeticException at a random iteration in a for loop. Catch the exception
in the method and pass the iteration count when the exception occurred to
the calling method by using an object of an exception class you define.
Code is given on the next page:

BILAL AHMAD 21CAMSA 111 126


LAB COURSE-II | CAMS-20P1

package javaapplication7week8;

class MyException extends Exception {


int iteration;
MyException(int i) {
this.iteration = i;
}
}
public class Week8Q4 {

public static void main(String[] args){


try {
loop();
} catch (MyException e) {
System.out.println("iteration occured at" +e.iteration);
}
}
public static void loop() throws MyException {
int n = 10;
for (int i = 0; i < n; i++) {
try {
int result = n / i;
} catch (ArithmeticException e) {
System.out.println("cannot divide by zero");
System.out.println(i);
}
}
}}

BILAL AHMAD 21CAMSA 111 127


LAB COURSE-II | CAMS-20P1

And this is its output:

#5 Write a program that will count the number of characters in a file.


Required code:

package week_8;
import java.io.FileReader;
import java.io.IOException;
public class Ques_5 {
public static void main(String[] args) {
try{
FileReader file = new FileReader("D:\\hello.txt");
try{
int i, cntWithoutNewLine = 0, cntWithNewLine = 0;
while((i = file.read()) != -1){
char ch = (char) i;
if(ch != '\n' && i != 13) cntWithoutNewLine++;
if(i != 13) cntWithNewLine++;
}
System.out.println("Count with newline character included : " + cntWithNewLine);
System.out.println("Count with newline character excluded : " + cntWithoutNewLine);

}
finally {
System.out.println("Successful Termination");
BILAL AHMAD 21CAMSA 111 128
LAB COURSE-II | CAMS-20P1

file.close();
}
}
catch(IOException e){
System.out.println(e);
}
}
}
And this is its output:

#6 Write a Java class Author with following features:


• Instance variables :
o firstName for the author’s first name of type String.
o lastName for the author’s last name of type String.
• Constructor:
o public Author (String firstName, String lastName): A constructor with
parameters, it creates the Author object by setting the two fields to the
passed values.
• Instance methods:
o public void setFirstName (String firstName): Used to set the first name of
author.
o public void setLastName (String lastName): Used to set the last name of
author.

BILAL AHMAD 21CAMSA 111 129


LAB COURSE-II | CAMS-20P1

o public double getFirstName(): This method returns the first name of the
author.
o public double getLastName(): This method returns the last name of the
author.
o public String toString(): This method printed out author’s name to the
screen
Write a Java class Book with following features:
• Instance variables :
o title for the title of book of type String.
o author for the author’s name of type String.
o price for the book price of type double.
• Constructor:
o public Book (String title, Author name, double price): A constructor with
parameters, it creates the Author object by setting the the fields to the
passed values.
• Instance methods:
o public void setTitle(String title): Used to set the title of book.
o public void setAuthor(String author): Used to set the name of author of
book.
o public void setPrice(double price): Used to set the price of book.
o public double getTitle(): This method returns the title of book.
o public double getAuthor(): This method returns the author’s name of book.
o public String toString(): This method printed out book’s details to the
screen
Write a separate class BookDemo with a main() method creates a Book titled
“Developing Java Software” with authors Russel Winderand price 79.75.
Prints the Book’s string representation to standard output (using
System.out.println).

Required code is given on the next page:

BILAL AHMAD 21CAMSA 111 130


LAB COURSE-II | CAMS-20P1

package javaapplication7week8;
class Author {
String firstName;
String secondName;
Author() {
}
Author(String firstName, String secondName) {
this.firstName = firstName;
this.secondName = secondName;
}
public void setFirstName(String firstName) {
this.firstName = firstName; }
public void setSecondName(String secondName) {
this.secondName = secondName;
}
public String getFirstName() {
return this.firstName;
}
public String getSecondName() {
return this.secondName;
}
public String tostring() {
return this.firstName + this.secondName;
}
}
class Book extends Author {
String title;
String author_name; // autgor name
double price;
BILAL AHMAD 21CAMSA 111 131
LAB COURSE-II | CAMS-20P1

Book(String title, Author name, double price) {


this.title = title;
this.author_name = name.firstName + name.secondName;
this.price = price;
}
public void setTitle(String Title) {
this.title = title;
}
public void SetAuthor(String author) {
this.author_name = author;
}
public void setPrice(double price) {
this.price = price;
}
String getTitle() {
return this.title;
}
String getAuthor() {
return this.author_name;
}
public String tostring() {
return this.title + this.author_name + this.price;
}
}
public class Week8Q6 {
public static void main(String[] args) {Author a1 = new Author(" Russel ", " Winderland ");
Book b1 = new Book("Developing Java Software", a1, 79.75);
System.out.println( b1.tostring());
}}
BILAL AHMAD 21CAMSA 111 132
LAB COURSE-II | CAMS-20P1

And this is its result:

BILAL AHMAD 21CAMSA 111 133


LAB COURSE-II | CAMS-20P1

WEEK 9

BILAL AHMAD 21CAMSA 111 134


LAB COURSE-II | CAMS-20P1

WEEK 9
#1 Write a Java program which reads student grades from a text file called
grades.txt and prints only the corresponding letter grades into a file called
letter.txt. The letter grades are assigned according to the following table.
Assume that the grades.txt file can have any number of students’ grades.
Hint: The last number in the grades.txt file is -1.

package javaapplication9week9;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class JavaApplication9Week9 {
public static void main(String[] args) {
File myFile1 = new File("grades.txt");
File myFile2 = new File("letter.txt");
int num;
String grade;
try{
Scanner sc = new Scanner(myFile1);
while(sc.hasNextInt()){
num = sc.nextInt();
if(num>=90){
grade = "A+";
}else if(num>=85){
grade = "A";
}else if(num>=80){
BILAL AHMAD 21CAMSA 111 135
LAB COURSE-II | CAMS-20P1

grade = "B+";
}else if(num>=75){
grade = "B";
}else if(num>=70){
grade = "C+";
}else if(num>=65){
grade = "C";
}else if(num>=60){
grade = "D+";
}else if(num>=55){
grade = "D";
}else{
grade = "F";
}
}
System.out.println(grade);
try{
FileWriter fileWriter = new FileWriter("letter.txt",true);
fileWriter.write(grade + "\n");
fileWriter.close();
}catch(IOException e){
System.out.println(e);
}
}
}
catch(FileNotFoundException e){
System.out.println(e);
}
} }
BILAL AHMAD 21CAMSA 111 136
LAB COURSE-II | CAMS-20P1

Output is given below:

BILAL AHMAD 21CAMSA 111 137


LAB COURSE-II | CAMS-20P1

#2 Write a program to read a, b, c from data file and store roots of the
quadratic equation in output file. You must open your output file in append
mode.

This is the required code:

package javaapplication9week9;
import java.io.IOException;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
public class Week9Q2 {
public static void main(String[] args) {
File myFile = new File("Datafile.txt");
try {
Scanner sc = new Scanner(myFile);
int a = 0, b = 0, c = 0;
double d, r1=0, r2=0;
while (sc.hasNextInt()) {
a = sc.nextInt();
b = sc.nextInt();
c = sc.nextInt();
}
d = b * b - 4 * a * c;
if (d >= 0) {
r1 = (-b + d) / (2 * a);
r2 = (-b - d) / (2 * a);
} else {System.out.println("Imaginary roots!!");

BILAL AHMAD 21CAMSA 111 138


LAB COURSE-II | CAMS-20P1

}
File myFile1 = new File("Roots.txt");
try{
myFile1.createNewFile();
}catch(IOException e){
System.out.println(e);
}
try{
FileWriter fileWriter = new FileWriter("Roots.txt");
fileWriter.write("First Root = "+r1+"\nSecond Root = "+r2);
fileWriter.close();
}catch(IOException e){
System.out.println(e);
}
try{
Scanner obj = new Scanner (myFile1);
while(obj.hasNextLine()){
String line = obj.nextLine();
System.out.println(line);
}
obj.close();
}catch(FileNotFoundException e){
System.out.println(e);
}
} catch (FileNotFoundException e) {System.out.println(e);
}
}
}

BILAL AHMAD 21CAMSA 111 139


LAB COURSE-II | CAMS-20P1

And this is its result:

#5 Write a java program to read a file and find total no. of lines in that file.

package javaapplication9week9;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Week9Q5 {


static int count=0;
public static void main(String[] args){
File myFile = new File("Exceptional2.txt");
try{
Scanner sc = new Scanner(myFile);
while(sc.hasNextLine()){
String line = sc.nextLine();
count++;
System.out.println(line);
}
sc.close();
System.out.println("Total number of lines " +count);
}
catch(FileNotFoundException e){

BILAL AHMAD 21CAMSA 111 140


LAB COURSE-II | CAMS-20P1

// e.printStackTrace();
System.out.println(e);
}
}
}
Output:

BILAL AHMAD 21CAMSA 111 141


LAB COURSE-II | CAMS-20P1

WEEK 10

BILAL AHMAD 21CAMSA 111 142


LAB COURSE-II | CAMS-20P1

WEEK 10
1 - Write applets to draw the following shapes:
a) Cone

SOURCE CODE:
package week_10;
import java.applet.Applet;
import java.awt.*;
public class Ques_1_b extends Applet {
public void paint(Graphics g){
setBackground(Color.yellow);
g.setColor(Color.black);

g.drawOval(500,60,200,50);
g.drawLine(500,80,500,300);
g.drawLine(700,80,700,300);
g.drawOval(500,280,200,50);
}
}
OUTPUT:

BILAL AHMAD 21CAMSA 111 143


LAB COURSE-II | CAMS-20P1

a) Cylinder

SOURCE CODE:
package week_10;
import java.applet.Applet;
import java.awt.*;
public class Ques_1_b extends Applet {
public void paint(Graphics g){
setBackground(Color.yellow);
g.setColor(Color.black);
g.drawOval(500,60,200,50);
g.drawLine(500,80,500,300);
g.drawLine(700,80,700,300);
g.drawOval(500,280,200,50);
}
}
OUTPUT:

b) Square inside a circle

BILAL AHMAD 21CAMSA 111 144


LAB COURSE-II | CAMS-20P1

SOURCE CODE:

package week_10;
import java.applet.Applet;
import java.awt.*;
public class Ques_1_c extends Applet {
public void paint(Graphics g) {
g.setColor(Color.green);
g.drawOval(20, 20, 240, 240);
g.setColor(Color.red);
g.drawRect(65, 60, 150, 150);
}
}
OUTPUT:

#2 Write an applet that will display the following on a green background. Use
the following dimension:
Rectangle : (10, 10, 300, 150), Fill colour: blue
Left Circle : (10, 10, 50, 150), Fill Colour: Yellow
Right Circle: (159, 10, 150, 150), Fill colour: Yellow
Text : (110, 90), colour: Red

BILAL AHMAD 21CAMSA 111 145


LAB COURSE-II | CAMS-20P1

SOURCE CODE:

package week_10;
import java.applet.Applet;
import java.awt.*;
public class Ques_2 extends Applet {
public void paint(Graphics g){
g.setColor(Color.blue);
g.fillRect(10, 10, 300, 150);
g.setColor(Color.yellow);
g.fillOval(10, 10, 150, 150);
g.setColor(Color.yellow);
g.fillOval(150, 10, 150, 150);
g.setColor(Color.red);
g.drawString("RAMADAN MUBARK", 110, 90);
}
}
OUTPUT:

BILAL AHMAD 21CAMSA 111 146


LAB COURSE-II | CAMS-20P1

#3 Write a JAVA Applet program to plot the following face:

SOURCE CODE:
package week_10;
import java.applet.Applet;
import java.awt.*;
public class Ques_3 extends Applet {
public void paint(Graphics g){
g.drawOval(10, 10, 240, 180);
g.drawOval(60, 52, 25, 25);
g.drawOval(178, 50, 25, 25);
g.drawLine(63, 130, 198, 130);
}
}
OUTPUT:

BILAL AHMAD 21CAMSA 111 147


LAB COURSE-II | CAMS-20P1

WEEK 11

BILAL AHMAD 21CAMSA 111 148


LAB COURSE-II | CAMS-20P1

WEEK 11
#1 Write a graphics program that draws a clock face with a time that the user
enters in a text field. (The user must enter the time in the format hh:mm, for
example 09:45).

SOURCE CODE:
package week_11;

import java.applet.Applet;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Ques_1 extends Applet implements ActionListener{

Label l;
TextField t;
Button ok,cancel;
double hrs_x = 190, hrs_y = 250, min_x = 120, min_y = 160;
boolean event = false;

public void init() {


l = new Label("Enter time as hh:mm");
t = new TextField(20);
ok = new Button("OK");
setLayout(null);
add(l);
l.setBounds(20, 10, 200, 30);

BILAL AHMAD 21CAMSA 111 149


LAB COURSE-II | CAMS-20P1

add(t);
t.setBounds(20, 50, 200, 30);
add(ok);
ok.setBounds(20, 90, 200, 30);
ok.addActionListener(this);
}
public void paint(Graphics g){
if(event == true){
g.drawOval(20, 150, 200, 200);
g.drawLine(120, 250, (int)min_x, (int)min_y);
g.drawLine(120, 250, (int)hrs_x, (int)hrs_y);
}
}

public void actionPerformed(ActionEvent e){


if(e.getSource() == ok){
String h = t.getText().substring(0, 2);
String m = t.getText().substring(3);
int hrs = Integer.parseInt(h);
int mins = Integer.parseInt(m);

double angle_min = Math.toRadians(-mins*6 - 180);


min_x = 90*Math.sin(angle_min) + 120;
min_y = 90*Math.cos(angle_min) + 250;
double angle_hrs = Math.toRadians(-((hrs * 30) + 0.5 * mins) - 180);

hrs_x = 70*Math.sin(angle_hrs) + 120;


hrs_y = 70 * Math.cos(angle_hrs) + 250;

BILAL AHMAD 21CAMSA 111 150


LAB COURSE-II | CAMS-20P1

event = true;
repaint();
}
}
}

SOURCE CODE:

#2 Write a program that draws the picture of a house.

BILAL AHMAD 21CAMSA 111 151


LAB COURSE-II | CAMS-20P1

SOURCE CODE:

package week_11;

import java.applet.Applet;
import java.awt.*;

public class Ques_2 extends Applet {


int[] x = {0, 100, 200};
int[] y = {50, 10, 50};
public void paint(Graphics g) {
g.drawPolygon(x, y, 3);
g.drawRect(0, 50, 200, 150);
//Gate
g.drawRect(30, 100, 40, 100);
//Window
g.drawRect(90, 100, 80, 35);
}
}
OUTPUT:

BILAL AHMAD 21CAMSA 111 152


LAB COURSE-II | CAMS-20P1

#3 Write an applet to display the following figure:

SOURCE CODE:
package week_11;

import java.applet.Applet;
import java.awt.*;
public class Ques_3 extends Applet {
public void paint(Graphics g) {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == j) {
g.fillOval(i * 30, j * 30, 20, 20);
} else {
g.drawOval(i * 30, j * 30, 20, 20);
}
}
BILAL AHMAD 21CAMSA 111 153
LAB COURSE-II | CAMS-20P1

}
}
}

SOURCE CODE:

#4 Write an applet to display the following figure:

SOURCE CODE:

package week_11;

import java.applet.Applet;

BILAL AHMAD 21CAMSA 111 154


LAB COURSE-II | CAMS-20P1

import java.awt.*;

public class Ques_4 extends Applet {


public void paint(Graphics g) {

for (int i = 0; i < 8; i++) {


int row = i * 30;
for (int j = 0; j < 8; j++) {
int col = j * 30;
if ((i%2) == (j%2)) {
g.setColor(Color.black);
g.fillRect(col, row, 30, 30);
} else {
g.setColor(Color.white);
g.fillRect(col, row, 30, 30);
}
}
}
}}
OUTPUT:

BILAL AHMAD 21CAMSA 111 155


LAB COURSE-II | CAMS-20P1

WEEK 12

BILAL AHMAD 21CAMSA 111 156


LAB COURSE-II | CAMS-20P1

WEEK 12
#1 Draw a “bull’s eye” a set of concentric rings in alternation black and white
colours: Fill a black circle, and then fill a smaller white circle on top, and so
on.

SOURCE CODE:
package week_12;
import java.applet.Applet;
import java.awt.*;
public class Ques_1 extends Applet {

public void paint(Graphics g) {

for (int i = 5; i >= 1; i--) {


int coord = (5 - i) * 20 + 20;
int hw = i * 40;

if (i % 2 != 0) {
g.setColor(Color.black);
g.fillOval(coord, coord, hw, hw);
} else {
g.setColor(Color.white);
g.fillOval(coord, coord, hw, hw);
}
}
BILAL AHMAD 21CAMSA 111 157
LAB COURSE-II | CAMS-20P1

}
}

OUTPUT:

#2 Write an AWT GUI application (called AWTCounter) as shown in the


Figure. Each time the "Count" button is clicked, the counter value shall
increase by 1.

SOURCE CODE:
package week_12;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class Ques_2 {

public Ques_2(){
BILAL AHMAD 21CAMSA 111 158
LAB COURSE-II | CAMS-20P1

//Making frame object


final Frame f = new Frame();

f.setSize(400, 300);
f.setLayout(new FlowLayout());
f.setVisible(true);

Label l = new Label("Counter");


final TextField t = new TextField(10);
t.setText("0");
Button btn = new Button("Count");
f.add(l);
f.add(t);
f.add(btn);
//Event Listener on button
btn.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
int cnt = Integer.parseInt(t.getText());
cnt++;
String res = Integer.toString(cnt);
t.setText(res);
}

});

//Window Listener for closing opearation


f.addWindowListener(new WindowAdapter(){

BILAL AHMAD 21CAMSA 111 159


LAB COURSE-II | CAMS-20P1

@Override
public void windowClosing(WindowEvent e){
f.dispose();
}
});
}

//Main function
public static void main(String[] args) {
Ques_2 obj = new Ques_2();
}
}

OUTPUT:

BILAL AHMAD 21CAMSA 111 160


LAB COURSE-II | CAMS-20P1

BILAL AHMAD 21CAMSA 111 161

You might also like