Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
67 views

Java Programming Lab Manual-22PLC25C 2022-23

Uploaded by

Vish K
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views

Java Programming Lab Manual-22PLC25C 2022-23

Uploaded by

Vish K
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

KLS’s Gogte Institute of Technology

Department of Information Science and Engineering

Lab Manual

Basics of Java Programming Lab (2PLC25C)

Basics of Java Programming Lab Manual


KLS GIT Department of ISE
Term Work -1.

Write a Java program to print an array after changing the rows


and columns of a two-dimensional array.

Theory Related to the Experiment:

• General syntax for declaring an array:

Base_Type[] Array_Name = new Base_Type[Length];

Examples:
80-element array with base type char:
char[] symbol = new char[80];
100-element array of doubles:
double[] reading = new double[100];

70-element array of int:


int[] specimen = new int[70];

Syntax for 2-D arrays is similar to 1-D arrays

Declare a 2-D array of ints named table

the table should have ten rows and six columns

int[][] table = new int[10][6];

• The transpose of a matrix is found by interchanging its rows into columns or


columns into rows.
• The transpose of the matrix is denoted by using the letter “T” in the superscript of the
given matrix. For example, if “A” is the given matrix, then the transpose of the matrix
is represented by A' or AT.

Steps for execution (to be written for only 1st Experiment):

1. Install Apache Netbeans on the system.

2. Create a project as Java Application.

Basics of Java Programming Lab Manual


KLS GIT Department of ISE
3. Add the code to generate transpose of a matrix.

Application of the experiment performed:

Output and Observation:

(Sample Output add the required output )

Enter the number of rows:

Enter the number of column:

Enter the elements of the matrix:

1 2

3 4

The elements in the original matrix are:

1 2

3 4

After transposing the elements are...

1 3

2 4

Marks:

Maximum Marks Marks Scored

Conducting the experiment 5

Calculations, results, graph, conclusion, and outcome 5

Viva voce 5

15

Checked on

Signature of the faculty member

Basics of Java Programming Lab Manual


KLS GIT Department of ISE
TermWork-2
Write a program to tokenize the given string and count the
number of tokens in a given string

Theory related to the Experiment:


• StringTokenizer class in Java is used to break a string into tokens.
• A StringTokenizer object internally maintains a current position within the string to be
tokenized.
• The String Tokenizer class allows an application to break strings into tokens.

Illustration

• StringTokenizer(String str): default delimiters like newline, space,


tab, carriage return, and form feed.
• StringTokenizer(String str, String delim): delim is a set of delimiters
that are used to tokenize the given string.
• StringTokenizer(String str, String delim, boolean flag): The first two
parameters have the same meaning wherein The flag serves the
following purpose. If the flag is false, delimiter characters serve to
separate tokens. If the flag is true, delimiter characters are
considered to be tokens.

Application of the experiment performed:

Basics of Java Programming Lab Manual


KLS GIT Department of ISE
Output and Observation:
(This is Sample Output)

Using Constructor 1 -

Hello

Students

How

are

you

Using Constructor 2 -

JAVA

Code

String

Marks:

Maximum Marks Marks Scored

Conducting the experiment 5

Calculations, results, graph, conclusion, and outcome 5

Viva voce 5

15

Checked on

Signature of the faculty member

Basics of Java Programming Lab Manual


KLS GIT Department of ISE
Term Work 3.
Write a program using switch statement to display the grade of
the marks scored in a subject, using following grading table.
Grade Marks
A 90-100
B 80-89
C 70-79
D 60-69
E 40-59
F <40

Theory Related to the Experiment:


switch (expression) {
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
.
.
.
case valueN:
// statement sequence
break;
default:
// default statement sequence
}
The switch statement
 The switch case statement is a multi-way branch with several choices. A switch is
easier to implement than a series of if/else statements.
Structure of Switch:
 The switch statement begins with a keyword, followed by an expression that equates
to a no long integral value.
 Following the controlling expression is a code block that contains zero or more labeled
cases.
 Each label must equate to an integer constant and each must be unique.

Application of the experiment performed:

Basics of Java Programming Lab Manual


KLS GIT Department of ISE
Output and Observation:
=========================================

This is program find out students grades

-----------------------------------

Enter The Marks Between 0 To 100:

=========================================

Enter The Mark: 80

=============================

Your Grade Is: B or Very Good

=============================

=========================================

This is program find out students grades

-----------------------------------

Enter The Marks Between 0 To 100:

=========================================

Enter The Mark: 92

=============================

Your Grade Is: A or Excellent

=============================

(sample)

Marks:

Basics of Java Programming Lab Manual


KLS GIT Department of ISE
Maximum Marks Marks Scored

Conducting the experiment 5

Calculations, results, graph, conclusion, and outcome 5

Viva voce 5

15

Checked on

Signature of the faculty member

Basics of Java Programming Lab Manual


KLS GIT Department of ISE
Term Work 4.
Write a program to generate the following number triangle for
given number of ‘N’ lines
Eg. For N=5
1
121
12321
1234321
123454321

Theory Related to the Experiment:


There are three types of looping statements in Java. They are as follows:
 For loop
 While loop
 Do while loop

for(initialization; condition; increment/decrement)


{
Statement(s);
}

The while statement or loop continually executes a block of statements while a particular
condition is true. The while statement continues testing the expression and executing its block
until the expression evaluates to false. The syntax to use while loop in java is given below.

while(condition)
{
Statement(s);
}

Do-while Loop in Java:

The difference between do-while and while is that do-while evaluates its expression at the
bottom of the loop instead of the top. Therefore, the statements within the do block are always
executed at least once.

Basics of Java Programming Lab Manual


KLS GIT Department of ISE
Note that the do-while statement ends with a semicolon. The condition expression must be a
boolean expression. The syntax to use the do-while loop is given below.

do{
Statement(s);
}
while(condition);

Application of the experiment performed:

Output and Observation:


Enter a number: 4

121

12321

1234321

Marks:

Maximum Marks Marks Scored

Basics of Java Programming Lab Manual


KLS GIT Department of ISE
Conducting the experiment 5

Calculations, results, graph, conclusion, and outcome 5

Viva voce 5

15

Checked on

Signature of the faculty member

Basics of Java Programming Lab Manual


KLS GIT Department of ISE
5. Design and develop a program to implement student class to
store student information like Name, USN, Branch, Division,
Semester, and CGPA, also write a function to display the
information of the student for a given USN.

Theory Related to the Experiment:


A class is created using the class keyword.

class Student {

String name;
int roll_no;
}

In the above declaration, Student is the name of a class. In other words, Student is a class.

In the body of the class, the attributes name and roll_no are defined.

Attributes are variables defined in a class. They specify the features (properties) of the class.

we can also define methods in a class. The variables and methods defined in a class are called members
of the class.

class Test {

public static void main(String[] args) {


// creating object st of class Student
Student st = new Student();

// accessing variable name of class


System.out.println(st.name);

// accessing method description of class


st.description();
}
}

Using standard values, using command line arguments, inputs through scanner class and user-
defined method. Cumulative Grade Point Average ( CGPA ) is the overall grade point average Your
grade point average (GPA) is calculated by dividing the total amount of grade points earned by the
total amount of credit hours attempted. Your grade point average may range from 0.0 to a 4.0. To get
the example student’s GPA, the total grade points are divided by the total credit hours attempted. Here
is the simple formula to calculate the GPA ( Grade point average formula )

Application of the experiment performed:

Basics of Java Programming Lab Manual


KLS GIT Department of ISE
Output and Observation: (Sample)

Enter the total no of students

Enter details of students1

usn:

Name:

AA

Branch:

CS

Div:

Sem:

CGPA:

Student details

USN NAME BRANCH SEM

1 AA CS 1

Marks:

Basics of Java Programming Lab Manual


KLS GIT Department of ISE
Maximum Marks Marks Scored

Conducting the experiment 5

Calculations, results, graph, conclusion, and outcome 5

Viva voce 5

15

Checked on

Signature of the faculty member

Basics of Java Programming Lab Manual


KLS GIT Department of ISE
6. Design and develop a program in Java to overload a function
to add two integers, add two double numbers and add
(concatenate) two strings.

Theory Related to the Experiment:

Function Overloading in Java: If a class has multiple methods having same name but
different in parameters, it is known as Function Overloading. Suppose you have to perform
addition of the given numbers but there can be any number of arguments, if you write the
method such as a(int, int) for two parameters, and b(int,int,int) for three parameters then it may
be difficult for you as well as other programmers to understand the behavior of the method
because its name differs.

Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

1) Method Overloading: changing no. of arguments

In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.

In this example, we are creating static methods so that we don't need to create instance for
calling methods.

class Adder{

static int add(int a,int b){return a+b;}


static int add(int a,int b,int c){return a+b+c;}

2) Method Overloading: changing data type of arguments

In this example, we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double arguments

class Adder{

Basics of Java Programming Lab Manual


KLS GIT Department of ISE
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}

Application of the experiment performed:

Output and Observation: (Sample)


1) 22
33
2) 22
24.9

Marks:

Maximum Marks Marks Scored

Conducting the experiment 5

Calculations, results, graph, conclusion, and outcome 5

Viva voce 5

15

Checked on

Signature of the faculty member

Basics of Java Programming Lab Manual


KLS GIT Department of ISE
7. Design and develop a program to implement the following
inheritance hierarchy by assuming suitable data members
and member functions for classes.

Person

Student Employee

UG student PG student

Theory Related to the Experiment:

Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).

The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields of
the parent class. Moreover, you can add new methods and fields in your current class also.

Terms used in Inheritance


o Class: A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a
derived class, extended class, or child class.
o Super Class/Parent Class: Super class is the class from where a subclass inherits the features.
It is also called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse
the fields and methods of the existing class when you create a new class. You can use the same
fields and methods already defined in the previous class.

Basics of Java Programming Lab Manual


KLS GIT Department of ISE
The syntax of Inheritance in Java
class Subclass-name extends Super class-name
{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from an existing class.
The meaning of "extends" is to increase the functionality.

In the terminology of Java, a class which is inherited is called a parent or super class, and the new
class is called child or subclass.

Application of the experiment performed:

Output and Observation:

Marks:

Basics of Java Programming Lab Manual


KLS GIT Department of ISE
Maximum Marks Marks Scored

Conducting the experiment 5

Calculations, results, graph, conclusion, and outcome 5

Viva voce 5

15

Checked on

Signature of the faculty member

Basics of Java Programming Lab Manual


KLS GIT Department of ISE
8. Design and develop a program to implement function
overriding for compute salary function for employee class
(Assume Project Manager is having 1.5 times more salary than
a programmer.

Person

Employee

Programmer Proj. Manager

Manager

Theory Related to the Experiment:

Method Overriding in Java:


If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java. In other words, If a subclass provides the specific
implementation of the method that has been declared by one of its parent class, it is known as
method overriding.

Usage of Java Method Overriding


o Method overriding is used to provide the specific implementation of a method which is already
provided by its super class.
o Method overriding is used for runtime polymorphism

Example of method overriding


The name and parameter of the method are the same, and there is IS-A relationship between
the classes, so there is method overriding.

//Java Program to illustrate the use of Java Method Overriding


//Creating a parent class.
class Vehicle{
//defining a method
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class

Basics of Java Programming Lab Manual


KLS GIT Department of ISE
class Bike2 extends Vehicle{
//defining the same method as in the parent class
void run(){System.out.println("Bike is running safely");}

public static void main(String args[]){


Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}

Application of the experiment performed:

Output and Observation: (Sample)

Marks:

Maximum Marks Marks Scored

Conducting the experiment 5

Basics of Java Programming Lab Manual


KLS GIT Department of ISE
Calculations, results, graph, conclusion, and outcome 5

Viva voce 5

15

Checked on

Signature of the faculty member

Basics of Java Programming Lab Manual


KLS GIT Department of ISE
9. Write a program to create area package called shapes and
define class called as box and implements the requisite
functions for box class. Demonstrate the importing of
shapes.box class from box package in another program and
call the functions of box class.

Theory Related to the Experiment:

Java Package:
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.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

Simple example of java package

The package keyword is used to create a package in java.


//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}

Application of the experiment performed:

Basics of Java Programming Lab Manual


KLS GIT Department of ISE
Output and Observation:

Marks:

Maximum Marks Marks Scored

Conducting the experiment 5

Calculations, results, graph, conclusion, and outcome 5

Viva voce 5

15

Checked on

Signature of the faculty member

Basics of Java Programming Lab Manual


KLS GIT Department of ISE
10. Write a java program to validate age of voter using user
defined exception.
The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that the normal flow of the application can be maintained. In this tutorial, we will
learn about Java exceptions, it's types, and the difference between checked and unchecked
exceptions.

What is Exception in Java?


Dictionary Meaning: Exception is an abnormal condition.

In Java, an exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.

What is Exception Handling?


Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException,
IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application.
An exception normally disrupts the normal flow of the application; that is why we need to
handle exceptions. Let's consider a scenario:

statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;

Suppose there are 10 statements in a Java program and an exception occurs at statement 5; the
rest of the code will not be executed, i.e., statements 6 to 10 will not be executed. However,
when we perform exception handling, the rest of the statements will be executed. That is why
we use exception handling in Java.

Basics of Java Programming Lab Manual


KLS GIT Department of ISE
Java Exception Keywords
Java provides five keywords that are used to handle the exception. The following table
describes each.

Keyword Description

Try The "try" keyword is used to specify a block where we should place an exception code. It means we ca
try block alone. The try block must be followed by either catch or finally.

Catch The "catch" block is used to handle the exception. It must be preceded by try block which means we ca
catch block alone. It can be followed by finally block later.

Finally The "finally" block is used to execute the necessary code of the program. It is executed whether an exc
is handled or not.

Throw The "throw" keyword is used to throw an exception.

Throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception
method. It doesn't throw an exception. It is always used with method signature.

Java Exception Handling Example


public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}

Application of the experiment performed:

Basics of Java Programming Lab Manual


KLS GIT Department of ISE
Output and Observation: (Sample)

Marks:

Maximum Marks Marks Scored

Conducting the experiment 5

Calculations, results, graph, conclusion, and outcome 5

Viva voce 5

15

Checked on

Signature of the faculty member

Basics of Java Programming Lab Manual


KLS GIT Department of ISE

You might also like