0% found this document useful (0 votes)
40 views70 pages

Manav 22CSU111 Final Lab Manual FOCP-II 2nd Sem

Uploaded by

manav 22csu111
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views70 pages

Manav 22CSU111 Final Lab Manual FOCP-II 2nd Sem

Uploaded by

manav 22csu111
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 70

FOCP II

Lab Manual
Department of Computer Science and
Engineering
The NorthCap University, Gurugram
FOCP II Lab Manual(CSL108)
2021-22

FOCP II
Lab Manual
CSL 108

Dr. Neeti Kashyap

Department of Computer Science and Engineering

NorthCap University, Gurugram- 122001, India

Session 2021-22

2
FOCP II Lab Manual(CSL108)
2021-22

Published by:

School of Engineering and Technology

Department of Computer Science & Engineering

The NorthCap University Gurugram

• Laboratory Manual is for Internal Circulation only

© Copyright Reserved

No part of this Practical Record Book may be

reproduced, used, stored without prior permission of The NorthCap University

Copying or facilitating copying of lab work comes under cheating and is


considered as use of unfair means. Students indulging in copying or
facilitating copying shall be awarded zero marks for that particular
experiment. Frequent cases of copying may lead to disciplinary action.
Attendance in lab classes is mandatory.

Labs are open up to 7 PM upon request. Students are encouraged to


make full use of labs beyond normal lab hours.

3
FOCP II Lab Manual(CSL108)
2021-22

PREFACE

The aim of this lab manual is to help students understand real life
problem using programming skills.

This manual is required for second semester computer science and


engineering students, so that they are able understand Java, one of
the most in-demand programming languages. The lab manual outline
is designed in such a manner that the beginners with little or no
knowledge about Object Oriented programming concepts can
understand the core OOP concepts including Encapsulation,
Polymorphism, Inheritance etc. and their implementation in Java. The
students will have extensive hands-on experience writing, compiling,
testing and executing Java programs applying the above principles for
developing modular reusable programs. to understand fundamental
concepts of Java programming language that can be further used to
design applications.

By the end of this practical, the students will gain the foundational skills
a software engineer needs, to solve real-world problems, from
designing algorithms to testing and debugging; and will be able to
apply these concepts to build their own interactive Java applications.

Author expresses deep gratitude to Members, Governing Body-NCU


for encouragement and motivation.

Dr. Neeti Kashyap


The NorthCap University
Gurugram, India

4
FOCP II Lab Manual(CSL108)
2021-22

CONTENTS

Page
S.N. Details No.

1 Introduction 6

2 Lab Requirement 6

3 General Instructions 6

4 List of Experiments 8

5 Rubrics 9

6 Annexure 1 (Format of Lab Report) 10

5
FOCP II Lab Manual(CSL108)
2021-22

1. INTRODUCTION

That ‘learning is a continuous process’ cannot be over emphasized. The theoretical


knowledge
gained during lecture sessions need to be strengthened through practical
experimentation.
Thus, practical makes an integral part of a learning process.

The purpose of conducting experiments can be stated as follows:


● To familiarize the students with the basic concepts, programming skill
development and the take home laboratory assignments mainly
implementation-oriented which have to be coded in high level language. The
lab sessions will be based on exploring the concepts discussed in class.
● Observing basic structure and characteristics of Computer Systems

● Reporting and analyzing the programming concepts.

● Hands on experience on the coding and software tools

2. LAB REQUIREMENTS
● Mac or PC

● Java Development kit (JDK)

● Free Text editor (Sublime Recommended)

● Web Browser (Chrome and Firefox Recommended)

● GIT user Account

3. GENERAL INSTRUCTIONS

3.1 General discipline in the lab

6
FOCP II Lab Manual(CSL108)
2021-22

● Students must turn up in time and contact concerned faculty for the
experiment they are supposed to perform.
● Students will not be allowed to enter late in the lab.

● Students will not leave the class till the period is over.

● Students should come prepared for their experiment.

● Experimental results should be entered in the lab report format and


certified/signed by concerned faculty/ lab Instructor.
● Students must get the connection of the hardware setup verified before
switching on the power supply.
● Students should maintain silence while performing the experiments. If any
necessity arises for discussion amongst them, they should discuss with a
very low pitch without disturbing the adjacent groups.
● Violating the above code of conduct may attract disciplinary action.

● Damaging lab equipment or removing any component from the lab may
invite penalties and strict disciplinary action.

3.2 Attendance

● Attendance in the lab class is compulsory.

● Students should not attend a different lab group/section other than the one
assigned at the beginning of the session.
● On account of illness or some family problems, if a student misses his/her
lab classes, he/she may be assigned a different group to make up the
losses in consultation with the concerned faculty / lab instructor. Or he/she
may work in the lab during spare/extra hours to complete the experiment.
No attendance will be granted for such case.

7
FOCP II Lab Manual(CSL108)
2021-22

3.3 Preparation and Performance

● Students should come to the lab thoroughly prepared on the practicals they are
assigned to perform on that day. Brief introduction to each experiment with
information about self-study reference is provided on LMS.
● Students must bring the lab report during each practical class with written records
of the last experiments performed complete in all respect.
● Each student is required to write a complete report of the practical he has
performed and bring to lab class for evaluation in the next working lab. Sufficient
space in work book is provided for independent writing of theory, observation,
calculation and conclusion.
● Students should follow the Zero tolerance policy for copying / plagiarism. Zero
marks will be awarded if found copied. If caught further, it will lead to disciplinary
action.
● Refer Annexure 1 for Lab Report Format

3.4 Norms to be followed for doing lab practical


● All the students will work in a team of 2 members each.

● Each and every practical will contain a number of programming


problems to be solved by students.

4. LIST OF EXPERIMENTS

Exp. No. List of Experiments

1 Programs on Data types

2 Programs on Control Statements

8
FOCP II Lab Manual(CSL108)
2021-22

3 Programs on Arrays

4 Programs on classes and objects

5 Programs on Inheritance

6 Programs on Interface

7 Programs on Packages

8 Programs on Exception Handling

9 Programs on File Handling

5. RUBRICS

Marks Distribution

Continuous Evaluation (50 End Semester Project (20


Marks) Marks)

Each experiment shall be Unguided project carries 20


evaluated for 10 marks and at marks.
the end of the semester
proportional marks shall be
awarded out of 50.

9
FOCP II Lab Manual(CSL108)
2021-22

6. Annexure 1
FOCP II
CSL108

Project Report

10
FOCP II Lab Manual(CSL108)
2021-22

Faculty name: Student name:

Roll No.:

Semester:

Group:

Department of Computer Science and Engineering

The NorthCap University, Gurugram- 122001, India

Session 2021-22

Table of Contents
S.No Page
No.
1. Project Title:

2. Description of Project:

Problem Statement
3. Problem Analysis

11
FOCP II Lab Manual(CSL108)
2021-22

3.1 Hardware Requirements

3.2 Software Requirements

4. Design

4.1 Data/Input Output Description:

4.2 Algorithmic Approach / Algorithm / DFD / ER


diagram/Program Steps

5. Implementation and Testing (stage/module


wise)

6. Output (Screenshots)

7. Conclusion and Future Scope

S. S No Experiment Date of Date of Marks CO Signature


Experiment Submission Covered

1 Programs on Data
Types

2 Programs on
Control Statements

12
FOCP II Lab Manual(CSL108)
2021-22

3 Programs on Arrays

4 Programs on
Classes & Objects

5 Programs on
Inheritance

6 Programs on
Packages
7 Programs on
Interfaces
8 Programs on
Exception Handling

9 Programs on File
handling

Index

PRACTICAL NO. 1

Student Name and Roll Number: Manav Goel 22CSU111

Semester /Section: 2nd Semester section -B

Date:

Faculty Signature:

13
FOCP II Lab Manual(CSL108)
2021-22

Objective(s):

 Perform variable assignment.


 Use comments in code
 Use operator precedence and operator associativity.
 Effectively use arithmetic expressions in Java

Outcome:

Student will be familiarizing with the data types in Java.

Problem Statement:
Q1. Write a program that takes two integers (values to be given within the program) and
displays the output of the following operators: addition, subtraction, multiplication, division and
modulus.
Definition of Done:
DoD 1: Assign two numbers to two variables.
DoD2: Use separate variables to store the results.

Q2. Write a Java program to convert minutes into the number of years, months and days.
Definition Of Done :
DoD 1: Ask the user to input the minutes
DoD 2: Display years and months and days in the sequence yy-mm-dd.

Background Study: Data Types in Java


Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and
double.
Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.

Question Bank:

1. Why Java is considered dynamic?

Ans. Java is considered to be dynamic since it is designed to adapt to an evolving environment. Java
programs can carry an extensive amount of run-time information that can be used to verify and resolve

14
FOCP II Lab Manual(CSL108)
2021-22

accesses to objects at run-time.

2. What is Java Virtual Machine and how it is considered in context of


Java’s platform independent feature?

Ans. JVM is the main component of Java architecture, and it is the part of the JRE. JVM is
responsible for allocating the necessary memory needed by the Java program. Java is called
platform independent because of Java Virtual Machine. As different computers with the
different operating system have their JVM, when we submit a .class file to any operating system,
JVM interprets the bytecode into machine level language.

3. List two Java IDE’s? List some Java keywords(unlike C, C++


keywords)?

Ans.

Two common IDE’s that are widely used are:

1. VS Code

2. IntelliJ IDEA

Some Java keywords are:

Specifies that a class or method will be implemented later, in a


abstract subclass

Assert describes a predicate placed in a java program to indicate that


assert the developer thinks that the predicate is always true at that place.

boolean A data type that can hold True and False values only

default Specifies the default block of code in a switch statement

extends Indicates that a class is derived from another class or interface

15
FOCP II Lab Manual(CSL108)
2021-22

4. Consider the following class:

public class IdentifyMyParts {


public static int x = 7;
public int y = 3;
}
a) What are the class variables?

Class variables also known as static variables are declared with the static keyword in a class,
but outside a method, constructor or a block. There would only be one copy of each class
variable per class, regardless of how many objects are created from it.

For this program class variable is “x”.

b) What are the instance variables?

Instance variables are declared in a class, but outside a method. When space is allocated for an object in
the heap, a slot for each instance variable value is created. Instance variables hold values that must be
referenced by more than one method, constructor or block, or essential parts of an object's state that must
be present throughout the class.

For this program instance variable is “y”.

Flipped practicals

1. What is the output from the following code:

IdentifyMyParts a = new IdentifyMyParts();


IdentifyMyParts b = new IdentifyMyParts();
a.y = 5;
b.y = 6;
a.x = 1;
b.x = 2;
System.out.println("a.y = " + a.y);
System.out.println("b.y = " + b.y);

16
FOCP II Lab Manual(CSL108)
2021-22

System.out.println("a.x = " + a.x);


System.out.println("b.x = " + b.x);
System.out.println("IdentifyMyParts.x = " + IdentifyMyParts.x);

2. What's wrong with the following program?

public class SomethingIsWrong {


public static void main(String[] args) {
Rectangle myRect;
myRect.width = 40;
myRect.height = 50;
System.out.println("myRect's area is " + myRect.area());
}
}
Ans.
The object is not declared properly.
It should be declared as:
Rectangle myRect = new Rectangle();

Student Work Area


Algorithm/Flowchart/Code/Sample Outputs

import java.util.*;

public class Main


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);

17
FOCP II Lab Manual(CSL108)
2021-22

System.out.print("Enter days: ");


int days = in.nextInt();
int years = days / 365;
days = days - (365 * years);
int months = days / 30;
int d = days - (months * 30);

System.out.println(years + " Years " + months + "


Months " + d + " Days");

in.close();
}

import java.util.*;

public class Start {


public static void main(String[] args) {
int n1,n2;
int sub,add,product;
float divide;
Scanner sc = new Scanner(System.in);
System.out.println("enter 1st number:");
n1 = sc.nextInt();
System.out.println("enter 2nd number:");
n2 = sc.nextInt();
add = n1+n2;
sub = n1-n2;
product = n1*n2;
divide = (float)n1/n2;

System.out.println("sum is: "+add);


System.out.println("subtraction is: "+sub);
System.out.println("product is: "+product);
System.out.println("division is: "+divide);

sc.close();

18
FOCP II Lab Manual(CSL108)
2021-22

19
FOCP II Lab Manual(CSL108)
2021-22

PRACTICAL NO. 2
Student Name and Roll Number: Manav Goel 22CSU111

Semester /Section: 2nd sec-B

Date:

Faculty Signature:

Objective
To familiarize the students with control statements in JAVA

Program Outcome
Through this practical, students will learn about the control statements

Problem Statement

1. Write a Java program to solve quadratic equations (use if, else if and else).
Definition of Done:
DoD 1: The program asks the values of coefficients of a quadratic equation.
DoD 2: The program should display the roots or an appropriate message.

2. Write a Java program that asks the user to provide a single character from the alphabet.
Print Vowel or Consonant, depending on the user input. If the user input is not a letter
(between a and z or A and Z), or is a string of length > 1, print an error message.
Definition of Done:
DoD 1: The program asks an input from the user.

20
FOCP II Lab Manual(CSL108)
2021-22

DoD 2: A single character input is taken from the user or an error message is
generated.
DoD 3: The program should print “Vowel” if the entered character is a vowel and
“Consonant” if the entered character is a consonant.

3. Write a Java program to print following structure:


*
**
***
****
*****
******

Background Study:
Java compiler executes the java code from top to bottom. The statements are executed according
to the order in which they appear. However, Java provides statements that can be used to control
the flow of java code. Such statements are called control flow statements.
Java provides three types of control flow statements.
 Decision Making statements
 Loop statements
 Jump statements

Question Bank
1. The most basic control flow statement supported by the Java programming language is the
__if-then__ statement.

2. The __Switch__ statement allows for any number of possible execution paths.

3. The __do-while__ statement is similar to the while statement, but evaluates its expression at
the __bottom__ of the loop.

4.How do you write an infinite loop using the for statement?

class Main {

public static void main(String args[]) {


for (int i = 0; i < 3; i--) {
System.out.println("Hello World");
}
}
}

21
FOCP II Lab Manual(CSL108)
2021-22

The code will be executed infinite times as each time the value of I is incremented by 1 and goes
upto infinity.

5. How do you write an infinite loop using the while statement?

class Main {

public static void main(String args[]) {


while (true) {
System.out.println("Hello World");
}
}
}

The code will print Hello World as the while loop keeps on executing for infinite time.

6. Which looping process checks the test condition at the end of the loop?
Ans. For loop.

7. Why do we use continue statement?


Ans. It is used to skip the current iteration and then continue to the next iteration.

8. What is the size of boolean variable?


Ans. 1 bit

9. Which looping process is best used when the number of iterations is known?
Ans. For loop.

Flipped Practicals
1. Consider the following code snippet.

if (aNumber >= 0)
if (aNumber == 0)
System.out.println("first string");
else System.out.println("second string");
System.out.println("third string");

a) What output do you think the code will produce if aNumber is 3?


b) Write a test program containing the previous code snippet; make aNumber 3. What is the
output of the program? Is it what you predicted? Explain why the output is what it is; in other

22
FOCP II Lab Manual(CSL108)
2021-22

words, what is the control flow for the code snippet?


c) Using only spaces and line breaks, reformat the code snippet to make the control flow easier to
understand.
d) Use braces, { and }, to further clarify the code.

2. What's wrong? for (int k = 2, k <= 12, k++)


3. If there is more than one statement in the block of a for loop, what must be placed at the
beginning and the ending of the loop block?
4. What value is stored in num at the end of this looping?
for (num = 1; num <= 5; num++)

Student Work Area


Algorithm/Flowchart/Code/Sample Outputs

Q1. WAP to solve quadratic equation.

import java.util.*;

public class Quadratic {


public static void main(String[] args) {

System.out.println("enter coefficients of quadratic


equation ");
Scanner sc = new Scanner(System.in);

System.out.println("Enter a");
int a = sc.nextInt();
System.out.println("Enter b");
int b = sc.nextInt();
System.out.println("Enter c");
int c = sc.nextInt();

System.out.println("the quadratic eqn is:


"+a+"x^2+"+b+"x+"+c);

float d = b*b-4*a*c;
if(d<0){
System.out.println("imaginary soln");

23
FOCP II Lab Manual(CSL108)
2021-22

}
else if(d==0){
System.out.println("roots are equal");
System.out.println("x1 & x2 = "+(float)-b/(2*a));
}
else if(d>0){
System.out.println("unique soln");
System.out.println("x1 = "+(float)(-b+(b*b-
4*a*c))/2*a);
System.out.println("x2 = "+(float)(-b-(b*b-
4*a*c))/2*a);
}

sc.close();

Q2. Write a Java program that asks the user to provide a single character
from the alphabet. Print Vowel or Consonant, depending on the user input. If
the user input is not a letter.

import java.util.*;

public class Vowel {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter a character ");
boolean b = sc.hasNextInt();

if(b==true){
System.out.println("error");
}else{

char ch = sc.next().charAt(0);
if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u'||
ch=='A'||ch=='E'||ch=='O'||ch=='U'||ch=='I'){
System.out.println(ch+" :its a vowel");
}else{
System.out.println(ch+" :its a consonant");
}
}

24
FOCP II Lab Manual(CSL108)
2021-22

sc.close();

Q3. Write a Java program to print following structure:

**

***

****

*****

******

public class Pattern {


public static void main(String[] args) {
int n=5;
for(int i=1;i<=n;i++){

25
FOCP II Lab Manual(CSL108)
2021-22

for(int j=1;j<=i;j++){
System.out.print("*");
}
System.out.println();
}

26
FOCP II Lab Manual(CSL108)
2021-22

PRACTICAL NO. 3
Student Name and Roll Number: Manav Goel 22CSU111

Semester /Section: 2nd semester Section -B

Date:

Faculty Signature:

Objective
To familiarize the students with array in JAVA.

Program Outcome
The students will learn the concept of arrays in Java.

Problem Statement

1. Write a Java program to find the maximum and minimum value of an array.

Definition of Done:

27
FOCP II Lab Manual(CSL108)
2021-22

DoD 1: The program should ask the user to enter the elements of the array.

DoD 2: The program should display the maximum and minimum elements of the array.

2. Write a Java program to find the index of an array element in an array of size 10. The
program should not use any function other than main ( ) functions.

Definition of Done:

DoD 1: The program should ask the user to enter the elements of the array.
DoD 2: The program should ask the user to enter a number to search.
DoD 3: The program should display the elements of the array entered.
DoD 4: The program should display the index of the number if the item is present or
display -1 of the elements is not present.

3. Write a Java Program to count even and odd numbers in an array.

Definition of Done

DoD 1: The program should ask the user to enter the elements of the array.

DoD 2: Even elements will be stored in EvenArray[] and odd elements will be stored in
oddArray[].

DoD 3: Display all three arrays along with their length.

4. Write a Java program to read numbers in an integer array of size 5 and display the
following (using functions for each functionality):

i) Sum of all the elements

ii) Sum of alternate elements in the array.

Definition of Done

28
FOCP II Lab Manual(CSL108)
2021-22

DoD 1: The program should ask the user to enter the elements of the array.

DoD 2: The program should display a menu with the above choices and ask the user to
choose one of the choices.

Background Study:

Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure
where we store similar elements. We can store only a fixed set of elements in a Java
array.

Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.

Question Bank:

1. Can you pass the negative number as an array size?

Ans. NO

2. Can you change the size of the array once you define it?

Ans. NO

3. What is an anonymous array?

Ans. An array without name.

4. What is the difference between int [] a and int a []?

Ans. No difference.

5. What are jagged arrays in java? Give example?

Ans. A jagged Array is an array of arrays where each element is an array. It is a

29
FOCP II Lab Manual(CSL108)
2021-22

special type of Multidimensional array where there are a variable number of


columns in each row.

Flipped Practicals
1.Which of these is an incorrect array declaration?
a) int arr[] = new int[5]
b) int [] arr = new int[5]
c) int arr[] = new int[5]
d) int arr[] = int [5] new

Ans-(d)

2. What will be the output of the following program?


public class MyFirst {
public static void main (String[] args) {
MyFirst obj = new MyFirst(n);
}
static int a = 10;
static int n;
int b = 5;
int c;
public MyFirst(int m) {
System.out.println(a + ", " + b + ", " + c + ", " + n + ", " + m);
}
// Instance Block
{
b = 30;
n = 20;
}
// Static Block
static
{
a = 60;
}
}

30
FOCP II Lab Manual(CSL108)
2021-22

Student Work Area


Algorithm/Flowchart/Code/Sample Outputs

Q1.Write a Java program to find the maximum and minimum value of an array.

package Arrays;
import java.util.*;
public class MAXMIN {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int i;
System.out.println("enter length of array");
int n = sc.nextInt();
System.out.println("enter elements of array");
int arr[] = new int[n];
for( i=0;i<n;i++){
arr[i] = sc.nextInt();
}
int max = arr[0];
int min = arr[0];

for( i=0;i<n;i++){
if(max<arr[i]){
max=arr[i];
}if(min>arr[i]){
min=arr[i];
}
}
System.out.println("max is "+max);

31
FOCP II Lab Manual(CSL108)
2021-22

System.out.println("min is "+min);
sc.close();
}
}

Q2. Write a Java program to find the index of an array element in an


array of size 10. The program should not use any function other than
main ( ) functions.
package Arrays;
import java.util.*;

public class FindIndex {


public static void main(String[] args) {
int i;
Scanner sc = new Scanner(System.in);
System.out.println("enter the length of array");
int n1 = sc.nextInt();
System.out.println("enter elements of array");
int arr[] = new int[n1];
for(i=0;i<n1;i++){
arr[i] = sc.nextInt();
}
System.out.println("your array:");

for(i=0;i<n1;i++){
System.out.println(arr[i]);
}

System.out.println("enter the number you want to


search");
int n = sc.nextInt();
for(i=0;i<n1;i++){
if(n==arr[i]){
System.out.println("number: "+n+"\nindex: "+i);
}

else if(i==n1-1) {
System.out.println("number is not present in
the entered array");
}

}
sc.close();

32
FOCP II Lab Manual(CSL108)
2021-22

Q3. Write a Java Program to count even and odd numbers in an array.

package Arrays;

import java.util.Scanner;
public class hh {
private static Scanner sc;
public static void main(String[] args)
{
int Size, i;
int even = 0, odd = 0;
sc = new Scanner(System.in);

System.out.print(" Please Enter Number of elements in


an array : ");
Size = sc.nextInt();

int [] a = new int[Size];

System.out.print(" Please Enter " + Size + " elements


of an Array : ");
for (i = 0; i < Size; i++)
{
a[i] = sc.nextInt();
}

for(i = 0; i < Size; i++)


{
if(a[i] % 2 == 0)
{
even++;
}
else
{
odd++;
}
}
System.out.println("\n Total Number of Even Numbers in
this Array = " + even);

33
FOCP II Lab Manual(CSL108)
2021-22

System.out.println("\n Total Number of Odd Numbers in


this Array = " + odd);
}
}

Q4. . Write a Java program to read numbers in an integer array of size


5 and display the following (using functions for each functionality):
import java.util.*;

public class Sumofele {


public static void main(String[] args) {
int i;
int sum = 0;
int alrsum = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the elemnets of array");
int arr[] = new int[5];
for (i = 0; i < 5; i++) {
arr[i] = sc.nextInt();
}
for (i = 0; i < 5; i++) {
sum = sum + arr[i];

}
for (i = 0; i < 5; i++) {
alrsum = alrsum + arr[i];
i++;
}
System.out.println("Sum of elements = " + sum);
System.out.println("Sum of alt elements = " + alrsum);
}

34
FOCP II Lab Manual(CSL108)
2021-22

35
FOCP II Lab Manual(CSL108)
2021-22

PRACTICAL NO: 4
Student Name and Roll Number: Manav Goel 22CSU111

Semester /Section: 2nd Semester

Date:

Faculty Signature:

Objective
To familiarize the students with classes and objects.

Program Outcome
The students will learn the concept of classes and objects.

Problem Statement

1.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" by creating an object of the
class Student.

2. Write a program to print the area and perimeter of a triangle having sides of 3, 4 and 5

36
FOCP II Lab Manual(CSL108)
2021-22

units by creating a class named 'Triangle' without any parameter in its constructor.

3. Write a program to print the area of a rectangle by creating a class named 'Area' taking
the values of its length and breadth as parameters of its constructor and having a method
named 'returnArea' which returns the area of the rectangle. Length and breadth of the
rectangle are entered through the keyboard.

4. Print the sum, difference and product of two complex numbers by creating a class
named 'Complex' with separate methods for each operation whose real and imaginary
parts are entered by the user.

5. Write a program to calculate the distance between two points (x1, y1) and (x2, y2). All
numbers and return values should be of type double.

Definition of Done:

DoD 1: Two java files to be defined. One for class definitions and another for the
application

DoD 2: A class point is defined with two float variables for x1 and x2 and the following
functionality:

i. Non-parametrized and parameterized constructors are defined.

ii. Get and set methods are defined for all the instance variables.

iii. Distance function is defined to calculate the distance between two points.

iv. Display function is defined with width of 7 and precision of 2.

Write this program with a static method definition for calculating the distance between two
points.

Background Study

37
FOCP II Lab Manual(CSL108)
2021-22

In object-oriented programming technique, we design a program using objects and


classes. An object in Java is the physical as well as a logical entity, whereas, a class in
Java is a logical entity only.

An object is an instance of a class. A class is a template or blueprint from which objects


are created. So, an object is the instance(result) of a class.

Question Bank

1. What is the difference between class and object?

CLASSES OBJECTS
Class is a blueprint or template from which Object is an instance of a class.
objects are created
Class is declared once. Object is created many times as per
requirement.

Class is a logical entity. Object is a physical entity.

2. What is constructor chaining?

Ans. Constructor chaining is the process of calling one constructor from another
constructor with respect to current object. One of the main use of constructor chaining is
to avoid duplicate codes while having multiple constructor (by means of constructor
overloading) and make code more readable

3. What is No-arg constructor?

Ans. A constructor that has no parameter is known as the No-argument or Zero argument
constructor. If we don’t define a constructor in a class, then the compiler creates a
constructor(with no arguments) for the class. And if we write a constructor with arguments
or no arguments then the compiler does not create a default constructor.

4. What happens if you keep return type for a constructor?

Ans. If we add a return type to a constructor, then it will become a method of the class.

38
FOCP II Lab Manual(CSL108)
2021-22

This is the way java runtime distinguish between a normal method and a constructor.

5. What is the use of private constructor?

Ans. The main purpose of using a private constructor is to restrict object creation. We
also use private constructors to implement the singleton design pattern.

6. Can we use this() in a method?

Ans. Yes, we can use while calling methods.

7. Can we define a method with same name of class?

Ans. Yes, we can write a method in Java with method name same as class name. But it is not
suggestable because of the following reasons −

 Using upper case letter at the starting of the name of the method violates the coding
conventions of Java for writing a methods name.
 There is a chance of assuming such methods with constructors of the class.

Flipped Practicals

1. What will be the output of the following Java program?


class A
{
int i;
int j;
A()
{
i = 1;
j = 2;
}
}
class Output
{

39
FOCP II Lab Manual(CSL108)
2021-22

public static void main(String args[])


{
A obj1 = new A();
A obj2 = new A();
System.out.print(obj1.equals(obj2));
}
}
a) false
b) true
c) 1
d) Compilation Error

Ans. A) false

Student Work Area


Algorithm/Flowchart/Code/Sample Outputs

Q1. 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" by creating
an object of the class Student.

class student{
String name;
int roll;
student(String name,int roll){
this.name = name;

40
FOCP II Lab Manual(CSL108)
2021-22

this.roll = roll;
}
}
public class basic{
public static void main(String[] args) {
student s1 = new student("John",1);
System.out.println(s1.name);
System.out.println(s1.roll);
}
}

Q2. Write a program to print the area and perimeter of a triangle having sides of 3,
4 and 5 units by creating a class named 'Triangle' without any parameter in its
constructor.

import java.util.*;

public class Perimeter {


public static void main(String[] args) {
triangle t1 = new triangle();
System.out.println("enter sides of triangle");
Scanner sc = new Scanner(System.in);

float s1 = sc.nextFloat();
float s2 = sc.nextFloat();
float s3 = sc.nextFloat();
t1.perimeter(s1,s2,s3);

float b = sc.nextFloat();
float h = sc.nextFloat();
t1.area(b,h);
}

}
class triangle{
float s1;
float s2;
float s3;

41
FOCP II Lab Manual(CSL108)
2021-22

float b;
float h;

public void perimeter(float s1,float s2,float s3){


this.s1=s1;
this.s2=s2;
this.s3=s3;
System.out.println("perimeter of entered triangle:
"+s1*s2*s3);
}
public void area(float b,float h){
this.b=b;
this.h=h;
System.out.println("area of entered triangle:
"+0.5*b*h);
}
}

Q3. Write a program to print the area of a rectangle by creating a class named
'Area' taking the values of its length and breadth as parameters of its constructor
and having a method named 'returnArea' which returns the area of the rectangle.
Length and breadth of the rectangle are entered through the keyboard.

import java.util.*;
class Area{

int l1;
int b1;
int l2;
int b2;

Area(int l1,int b1,int l2,int b2){


this.l1 = l1;
this.b1 = b1;
this.l2 = l2;
this.b2 = b2;

}
public int rectangle1(int l1,int b1){
return l1*b1;
}
public int rectangle2(int l2,int b2){
return l2*b2;

42
FOCP II Lab Manual(CSL108)
2021-22

public class Rectangle {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter parameters");

System.out.println("enter length & breadth of 1st


rectangle");
int l1 = sc.nextInt();
int b1 = sc.nextInt();
System.out.println("enter length & breadth of 2nd
rectangle");
int l2 = sc.nextInt();
int b2 = sc.nextInt();

Area rectangle = new Area(l1,b1,l2,b2);

System.out.println("area of rectangle1:
"+rectangle.rectangle1(l1,b1));
System.out.println("area of rectangle2:
"+rectangle.rectangle2(l2,b2));

Q4. Print the sum, difference and product of two complex numbers by
creating a class named 'Complex' with separate methods for each
operation whose real and imaginary parts are entered by the user.

import java.util.*;

class Complex {

int real, imaginary;

Complex()
{

43
FOCP II Lab Manual(CSL108)
2021-22

Complex(int tempReal, int tempImaginary)


{
real = tempReal;
imaginary = tempImaginary;
}

Complex addComp(Complex C1, Complex C2)


{
Complex temp = new Complex();

temp.real = C1.real + C2.real;

temp.imaginary = C1.imaginary + C2.imaginary;

return temp;
}

Complex subtractComp(Complex C1, Complex C2)


{

Complex temp = new Complex();

temp.real = C1.real - C2.real;

temp.imaginary = C1.imaginary - C2.imaginary;

return temp;
}

void printComplexNumber()
{
System.out.println("Complex number: "
+ real + " + "
+ imaginary + "i");
}
}

public class Main {

44
FOCP II Lab Manual(CSL108)
2021-22

public static void main(String[] args)


{

Complex C1 = new Complex(3, 2);

C1.printComplexNumber();

Complex C2 = new Complex(9, 5);

C2.printComplexNumber();

Complex C3 = new Complex();

C3 = C3.addComp(C1, C2);

System.out.print("Sum of ");
C3.printComplexNumber();

C3 = C3.subtractComp(C1, C2);

System.out.print("Difference of ");
C3.printComplexNumber();
}
}

Q5. Write a program to calculate the distance between two points (x1,
y1) and (x2, y2). All numbers and return values should be of type
double.
import java.util.*;
import java.lang.Math;

class distance{
double x1,x2,y1,y2;

45
FOCP II Lab Manual(CSL108)
2021-22

distance(double x1,double x2,double y1,double y2){

this.x1=x1;
this.x2=x2;
this.y1=y1;
this.y2=y2;

public static double dis(double x1,double x2,double


y1,double y2){
return Math.sqrt(Math.pow((x2-x1),2.0d)+Math.pow((y2-
y1),2.0d));
}

public class DistanceFormula {


public static void main(String[] args) {

Scanner sc = new Scanner(System.in);


System.out.println("enter cooordinates of points\
nx1,x2,y1,y2\n");
double x1 = sc.nextDouble();
double x2 = sc.nextDouble();
double y1 = sc.nextDouble();
double y2 = sc.nextDouble();

distance dis1 = new distance(x1,x2,y1,y2);

System.out.println("distance is: "


+dis1.dis(x1,x2,y1,y2)+" units");

46
FOCP II Lab Manual(CSL108)
2021-22

47
FOCP II Lab Manual(CSL108)
2021-22

PRACTICAL NO: 5
Student Name and Roll Number:

Semester /Section:

Date:

Faculty Signature:

Objective
To familiarize the students with the concept of Inheritance.

48
FOCP II Lab Manual(CSL108)
2021-22

Program Outcome
The students will learn the concept of inheritance.

Program Statement

1. Create a class named 'Shape' with a method to print "This is This is shape". Then
create two other classes named 'Rectangle', 'Circle' inheriting the Shape class, both
having a method to print "This is rectangular shape" and "This is circular shape"
respectively. Create a subclass 'Square' of 'Rectangle' having a method to print
"Square is a rectangle". Now call the method of 'Shape' and 'Rectangle' class by the
object of 'Square' class.

2. Create three classes:

Class Vehicle:

Vehicle Class will contain a display() function, which will say "This is a Vehicle".

Class Car:
Car Class will derive the Vehicle Class and overwrite its display() function. it will say
"This is a Car".

Class Bike:

Bike Class will derive the Vehicle Class and overwrite its display() function. it will say "This
is a Bike".

Write an application that reads an Integer N, which will denote the number of tyres in the
vehicle. You have to create an object of the appropriate class according to the value of N
and use it display() function.

If N = 2, Create a Bike Object.

If N = 4, Create a Car Object.

Create a Vehicle Object, otherwise.

Definition of Done:

49
FOCP II Lab Manual(CSL108)
2021-22

DoD 1: Each class definition is stored in its own .java file.

DoD 2: Switch statement is used for identifying the appropriate class for which the object is
to be invoked.

3. Define a class Box with the following instance variables: width, height and depth, all
of type float. Create a new class BoxWeigth that extends Box to include weight as
an instance variable. Write an application that tests the functionalities of both these
classes.
Definition of Done:
DoD 1: Three java files to be defined. One for each class definition: Box,
BoxWeight and BoxWeightDemo.
DoD 2: Box and BoxWeight should have three types of constructors defined: clone
of an object, all dimensions specified as arguments, no argument.
DoD 3: Super is used to call base class constructors in derived class
DoD 4: Get and set functions defined as applicable in Box and BoxWeight classes.
DoD 5: Function to display volume in Box class and weight in BoxWeigth class

Background Study
Inheritance can be defined as the process where one class acquires the properties
(methods and fields) of another. With the use of inheritance, the information is made
manageable in a hierarchical order.
The class which inherits the properties of other is known as subclass (derived class, child
class) and the class whose properties are inherited is known as superclass (base class,
parent class).

extends Keyword
extends is the keyword used to inherit the properties of a class. Following is the syntax of
extends keyword.
Syntax
class Super {
.....
.....

50
FOCP II Lab Manual(CSL108)
2021-22

}
class Sub extends Super {
.....
.....
}

Question Bank

1. What is the use of super keyword?


2. What is multi-level inheritance?
3. What is the usage of inheritance?
Flipped Questions
Q1. What is the output of the following?
class A
{
{
System.out.println(1);
}
}

class B extends A
{
{
System.out.println(2);
}
}

class C extends B
{
{
System.out.println(3);
}
}

public class MainClass


{
public static void main(String[] args)
{
C c = new C();
}
}

51
FOCP II Lab Manual(CSL108)
2021-22

Q2. What is the output of the following?

class A
{
public A()
{
System.out.println("Class A Constructor");
}
}

class B extends A
{
public B()
{
System.out.println("Class B Constructor");
}
}

class C extends B
{
public C()
{
System.out.println("Class C Constructor");
}
}

public class MainClass


{
public static void main(String[] args)
{
C c = new C();
}
}

Student Work Area


Algorithm/Flowchart/Code/Sample Outputs

52
FOCP II Lab Manual(CSL108)
2021-22

53
FOCP II Lab Manual(CSL108)
2021-22

PRACTICAL NO. 6
Student Name and Roll Number:

Semester /Section:

Date:

Faculty Signature:

Objective
To familiarize the students with the concept of Interfaces in Java.
Program Outcome

54
FOCP II Lab Manual(CSL108)
2021-22

The students will be able to understand where and how interfaces are implemented.
Problem Statement

1. 1. a) Write a program in java to check if a class can extends another class and/ can
implement one and more than one interface.

b) Write a program in java to check if an interface can extend other interface.


c) Write a program in java to check if an interface can also extend multiple interfaces.

2. Define the interface / class hierarchy as detailed in the following class diagram
Definition of Done:
DOD 1: The class definitions are defined as per the class diagram.
DOD 2: Each class definition is stored in its own .java file.
DOD 3: Base class constructors are invoked using super keyword
DOD 4: Function overriding is applied wherever applicable.

3. We have to calculate the area of a rectangle, a square and a circle. Create an abstract
class 'Shape' with three abstract methods namely 'RectangleArea' taking two parameters,
'SquareArea' and 'CircleArea' taking one parameter each. The parameters of
'RectangleArea' are its length and breadth, that of 'SquareArea' is its side and that of
'CircleArea' is its radius. Now create another class 'Area' containing all the three methods
'RectangleArea', 'SquareArea' and 'CircleArea' for printing the area of rectangle, square
and circle respectively. Create an object of class 'Area' and call all the three methods.

Background Study

55
FOCP II Lab Manual(CSL108)
2021-22

An interface in Java is a blueprint of a class. It has static constants and abstract


methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and
multiple inheritance in Java.
In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.

Flipped Practicals

1. What is the output of this program?


interface calculate {
void cal(int item);
}
class display implements calculate {
int x;
public void cal(int item) {
x = item * item;
}
}
class interfaces {
public static void main(String args[]) {
display arr = new display;
arr.x = 0;
arr.cal(2);
System.out.print(arr.x);
}
}
a) 0
b) 2
c) 4

56
FOCP II Lab Manual(CSL108)
2021-22

d) None of the mentioned

2. Which of the following package stores all the standard java classes?
a) lang
b) java
c) util
d) java.packages

3. Determine output of the following code.

interface A { }
class C { }
class D extends C { }
class B extends D implements A { }
public class Test extends Thread{
public static void main(String[] args){
B b = new B();
if (b instanceof A)
System.out.println("b is an instance of A");
if (b instanceof C)
System.out.println("b is an instance of C");
}
}

a) b is an instance of A.

b) b is an instance of C.

57
FOCP II Lab Manual(CSL108)
2021-22

c) b is an instance of A followed by b is an instance of C.

Question Bank

1. Can an interface be final?


2. Can an abstract class implement an interface?
3. Can you declare an interface method static?
4. What is the difference between abstract class and interface?

Student Work Area


Algorithm/Flowchart/Code/Sample Outputs

58
FOCP II Lab Manual(CSL108)
2021-22

Experiment No: 7
Student Name and Roll Number:

Semester /Section:

Date:

Faculty Signature:

Objective
To familiarize the students with package in Java.
Program Outcome
The students will learn the concept of package in Java. They will be able to understand
Problem Statement

1. Create a Java package called exercises. Inside the exercises package, create
another package (subpackage) called java. Create a Java class called PackageDemo
inside the java package. Insert a display() method inside the PackageDemo class.
Inside the method, insert this statement:System.out.println("PackageDemo

59
FOCP II Lab Manual(CSL108)
2021-22

executed");Write a PackageDemoDriver class within the same package to run the


display () method of PackageDemo class.

2. Write a java program outside the above defined package that imports the
package PackageDemo and calls its display() function.

Background Study

A java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two form, built-in package and user-defined
package.

There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql
etc.

Flipped Practicals

1. What will be the output of the following Java program?

package pkg;
class display
{
int x;
void show()
{
if (x > 1)
System.out.print(x + " ");
}
}
class packages
{
public static void main(String args[])
{
display[] arr=new display[3];

60
FOCP II Lab Manual(CSL108)
2021-22

for(int i=0;i<3;i++)
arr[i]=new display();
arr[0].x = 0;
arr[1].x = 1;
arr[2].x = 2;
for (int i = 0; i < 3; ++i)
arr[i].show();
}
}

Note : packages.class file is in directory pkg;


a) 0
b) 1
c) 2
d) 0 1 2

Qu Question Bank

1. What are packages? what is use of packages ?

2. What is difference between importing "java.applet.Applet" and "java.applet.* "?

3.What do you understand by package access specifier?

4. By default,all program import the java.lang package.


True/False ?

5. Java compiler stores the .class files in the path specified in CLASSPATH environmental
variable. True/False ?

6. User-defined package can also be imported just like the standard packages
True/False ?

7. A _______ is used to separate the hierarchy of the class while declaring an Import
statement.

8. All standard classes of Java are included within a package called _____.

61
FOCP II Lab Manual(CSL108)
2021-22

Student Work Area


Algorithm/Flowchart/Code/Sample Outputs

62
FOCP II Lab Manual(CSL108)
2021-22

PRACTICAL NO.8
Student Name and Roll Number:

Semester /Section:

Date:

Faculty Signature:

63
Objective
To familiarize the students with exception in java.

Program Outcome
The students will learn the concept of exceptions in Java.

FOCP II Lab Manual(CSL108)


2021-22
Problem Statement

1. Write a program that takes 5 integer command line arguments. Create a user
defined Exception named CheckArgumentException to check the number of
arguments passed through command line. If the number of arguments is less than
five, throw the CheckArgumentException, else print the addition of all five numbers.

Definition of Done:

DOD 1:Create a user-defined exception by the name


CheckArgumentException
DOD 2:Ask the user to enter the number of arguments
DOD 3:Use for loop to enter the arguments
DOD 4: Calculate the sum of the values entered

2. Create a class with a main() method that throws an object of class


Exception inside a try block. Give the constructor for Exception a String
argument. Catch the exception inside a catch clause and print the String
argument. Add a finally clause and print a message to prove you were
there.

Background Study
An exception (or exceptional event) is a problem that arises during the execution of a
program. When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore, these
exceptions are to be handled.
An exception can occur for many different reasons. Following are some scenarios where
an exception occurs.
 A user has entered an invalid data.
 A file that needs to be opened cannot be found.
 A network connection has been lost in the middle of communications or the JVM
has run out of memory.

QuestionQuestion Bank

1. When does Exceptions in Java arises in code sequence?


a) Run Time
b) Compilation Time
c) Can Occur Any Time
d) None of the mentioned

3. Which of these keywords must be used to monitor for exceptions?


a) try 64
b) finally
c) throw
d) catch
FOCP II Lab Manual(CSL108)
2021-22

Student Work Area


Algorithm/Flowchart/Code/Sample Outputs

65
FOCP II Lab Manual(CSL108)
2021-22

PRACTICAL NO. 9
Student Name and Roll Number:

Semester /Section:

Date:

Faculty Signature:

Objective
To familiarize the students with File handling.

66
FOCP II Lab Manual(CSL108)
2021-22

Program Outcome
The students will learn the concept of files in Java.

Problem Statement

1. 1. Write a program to check if the file exist is a file or directory.

2. W 2. Write a program to change the file permissions.

3.W 3. Write a program to perform simple read and write operation into file.

4. Write a program that writes an Serial No.(int), First Name (String), CGPA (float) and
Grade(char) into a text file using bufferedWriter and displays the contents using
bufferedReader.

Background Study

File handling is an important part of any application. Java has several methods for creating,
reading, updating, and deleting files.

Java File Handling

The File class from the java.io package, allows us to work with files.

To use the File class, create an object of the class, and specify the filename or directory name:

Example

import java.io.File; // Import the File class

67
FOCP II Lab Manual(CSL108)
2021-22

File myObj = new File("filename.txt"); // Specify the filename

QuestiQ Question Bank

1. Which of these exception is thrown in cases when the file specified for writing is not found?
a) IOException
b) FileException
c) FileNotFoundException
d) FileInputException

2. Which of these methods are used to read in from file?


a) get()
b) read()
c) scan()
d) readFileInput()

3. Which of these values is returned by read() method is end of file (EOF) is encountered?
a) 0
b) 1
c) -1
d) Null

Flipped Practicals

1. What will be the output of the following Java program?

1. import java.io.*;
2. class filesinputoutput
3. {
4. public static void main(String args[])
5. {
6. InputStream obj = new FileInputStream("inputoutput.java");
7. System.out.print(obj.available());
8. }
9. }

Note: inputoutput.java is stored in the disk.

68
FOCP II Lab Manual(CSL108)
2021-22

a) true
b) false
c) prints number of bytes in file
d) prints number of characters in the file

2. What will be the output of the following Java program?

1. import java.io.*;
2. public class filesinputoutput
3. {
4. public static void main(String[] args)
5. {
6. String obj = "abc";
7. byte b[] = obj.getBytes();
8. ByteArrayInputStream obj1 = new ByteArrayInputStream(b);
9. for (int i = 0; i < 2; ++ i)
10. {
11. int c;
12. while((c = obj1.read()) != -1)
13. {
14. if(i == 0)
15. {
16. System.out.print(Character.toUpperCase((char)c));
17. obj2.write(1);
18. }
19. }
20. System.out.print(obj2);
21. }
22. }
23. }

a) AaBaCa
b) ABCaaa
c) AaaBaaCaa
d) AaBaaCaaa

Student Work Area

69
FOCP II Lab Manual(CSL108)
2021-22

Algorithm/Flowchart/Code/Sample Outputs

70

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy