FJP Lab
FJP Lab
1
Integrated Development Environments
An integrated development environment, or IDE, is a graphical user interface
program that integrates all these aspects of programming and probably others (such
as a debugger, a visual interface builder, and project management). A command-line
environment is just a collection of commands that can be typed in to edit files,
compile source code, and run programs
There are sophisticated IDEs for Java programming that are available:
NetBeans IDE -- A pure Java IDE that should run on any system with Java 1.7 or
later. NetBeans is a free, "open source" program. It is essentially the open source
version of the next IDE. It can be downloaded from www.netbeans.org.
• public: Public is an access modifier, which is used to specify who can access this
method. Publicmeans that this Method will be accessible by any Class.
• void: It is the return type of the method. Void defines the method which will not return any
value.
• main: It is the name of the method which is searched by JVM as a starting point for
an applicationwith a particular signature only. It is the method where the main
execution occurs.
2
Algorithm to Find the Factorial of a Number
In this program, we will find the factorial of a number using recursion with user-defined values. Here, we
will ask the user to enter a value and then we will calculate the factorial by calling the function
recursively.
1. Start
2. Create an instance of the Scanner Class.
3. Declare a variable.
4. Ask the user to initialize the variable.
5. Declare a loop variable and another variable to store the factorial of the number.
6. Initialize both the variables to 1.
7. Use a while loop to calculate the factorial.
8. Run the loop till the loop variable is less than or equal to the number.
9. Update the factorial in each iteration.
10. Increment the loop variable in each iteration.
11. Print the factorial of the number.
12. Stop.
SOURCE CODE:
import java.util.Scanner;
class Slip1
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
Int ch, i, num, n, sum, cnt, flag, fact;
do
{
System.out.println("1 : Find Factorial");
System.out.println("2 : Display First 50 numbers");
System.out.println("3 : Find sum and average of N numbers");
System.out.println("4 : Exit");
System.out.print("Enter Choice = ");
ch = sc.nextInt();
switch(ch)
{
case 1 : System.out.print("Enter number = ");
3
n = sc.nextInt();
fact = 1;
for(i=1 ; i<=n ; i++)
fact = fact * i;
System.out.println("Factorial = " + fact);
break;
case 2: cnt=1;
n=1;
while(cnt<=50)
{
flag=1;
for(i=2 ; i<=n/2;i++)
{
if(n%i==0)
{
flag = 0 ;
break;
}
}
if(flag == 1)
{
System.out.println(n);
cnt++;
}
n++;
}
break;
case 3 : System.out.print("Enter limit = ");
n = sc.nextInt();
sum=0;
for(i=1 ; i<=n ; i++)
{
System.out.print("Enter number = ");
num = sc.nextInt();
sum = sum + num;
}
System.out.println("Sum = " + sum);
4
System.out.println("Avg = " + (float)sum/n);
break;
}
}while(ch!=4);
sc.close();
}
}
OUTPUT:
5
6
7
Conclusion:
References:
Herbert Schildt , “Java : The Complete Reference” Tata McGraw-Hill (7th Edition).
Questions:
1. What are the differences between C++ and Java?
2. Explain features of Java?
3. Why Java is platform independent?
4. Why main method declared as static in Java?
5. Explain control statements in Java?
8
Experiment No.2
Aim of the Experiment: Write a program in Java to implement a Calculator with simple
arithmetic operations such as add, subtract, multiply, divide, factorial etc. using switch case and
other simple java statements.
Objective:
To implement a Calculator with arithmetic operations and using switch case in Java.
Resources: Eclipse IDE 2018, JDK 1.8.0 is required
Course Outcome Addressed: CO1:Understand the basic principles of Java programming
language
Theory:
Java Operators:
In Java, an expression has two parts: operand and operator. The variables or constants that
operators act upon are called operands.
An operator in java is a symbol or a keyword that tells the compiler to perform a specific
mathematical or logical operations.
They are used in programs to manipulate data and variables. They generally form mathematical or
logical expressions. An expression is a combination of variables, constants, and operators.
For example, an expression is x+5. Here, the operand x is a variable, operand 5 is a constant, and
+ is an operator that acts on these two operands and produces the desired result.
There are three types of operators in java based on the number of operands used to perform an
operation.
1
1. Unary operator: The operator that acts on a single operand is called unary operator. A unary
operator uses a single variable.
2. Binary operator: The operator that acts on two operands is called binary operator. A binary
operator uses two variables.
3. Ternary operator: The operator that acts on three operands is called ternary operator. A ternary
operator uses three variables.
Based on the notation used, Java operator has been divided into two categories: Symbolic and
named.
If a symbol like +, -, *, etc is used as an operator, it is called symbolic operator. If a keyword is
used as an operator, it is called named operator.
The Java operators can be classified on the basis of symbols and named. They are as follows:
1. Symbolic operator in Java
• Arithmetic operators: +, -, *, /, etc.
• Relational operators: <, >, <=, >=, = =, !=.
• Logical operators: &&, ||, !.
• Assignment operators: =,
• Increment and decrement operators: + +, – –
• Conditional operators: ?:
• Bitwise operators: &, !, ^, ~, <<, >>, >>>
• Shift operators: <<, >>, >>>.
2. Named operators in Java
• Instanceof operator
2
Arithmetic Operators in Java
• Java Arithmetic operators are used to performing fundamental arithmetic operations such
as addition, subtraction, multiplication, and division on numeric data types.
• The numeric data types can be byte, short, int, long, float, and double. Java provides five
arithmetic operators.
3
10. code to be executed if all cases are not matched;
11.}
SOURCE CODE:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int choice;
int no1, no2, result;
do{
System.out.println("1.Add");
System.out.println("2.Subtract");
System.out.println("3.Multiply");
System.out.println("4.Divide");
System.out.println("5.Factorial");
System.out.println("6.Exit");
switch(choice){
case 1 :
System.out.println("Enter First Number");
no1 = in.nextInt();
result = no1+no2;
result = no1-no2;
4
System.out.println("Subtraction : " + result );
break;
case 3 :
System.out.println("Enter First Number");
no1 = in.nextInt();
result = no1*no2;
result = no1/no2;
result = 1;
case 6 :
System.out.println("Terminating");
break;
default :
System.out.println("Wrong Choice");
break;
}
5
}while ( choice != 6);
}
}
Output
6
7
Conclusion:
References:
Herbert Schildt , “Java : The Complete Reference” Tata McGraw-Hill (7th Edition).
Questions:
1. What is an Operator in Java?
2. What are the types of operators based on the number of operands?
3. What is an Arithmetic operator in Java?
4. What are the types of arithmetic operators? What are the priority levels of arithmetic
operation in Java?
5. What is a symbolic operator in Java? What are the types of operators based on symbols?
6. What is a Java Switch statement?
8
Experiment No.3
Aim of the Experiment: Write a program in Java with class Rectangle with the data fields
width,length, area and colour. The length, width and area are of double type and colour is of string
type. The methods are get_length(), get_width(), get_colour() and find_area(). Create two objects
of Rectangle and compare their area and colour. If the area and colour both are the same for the
objects then display "Matching Rectangle", otherwise display "Nonmatching Rectangle”.
Objective:
To understand the concept of multiple objects in Java.
Resources: Eclipse IDE 2018, JDK 1.8.0 is required
Course Outcome Addressed: CO2: Apply the concepts of classes and objects to write
programs in Java
Theory:
Java Classes:
Java is an object-oriented programming language. Everything in Java is associated with classes
and objects, along with its attributes and methods. For example: in real life, a car is an object. The
car has attributes, such as weight and color, and methods, such as drive and brake.
A Class is like an object constructor, or a "blueprint" for creating objects. To create a class, use
the keyword class.
class <class_name>{
field;
method;
}
• Local variables − Variables defined inside methods, constructors or blocks are called local
variables. The variable will be declared and initialized within the method and the variable
will be destroyed when the method has completed.
• Instance variables − Instance variables are variables within a class but outside any
method. These variables are initialized when the class is instantiated. Instance variables
can be accessed from inside any method, constructor or blocks of that particular class.
• Class variables − Class variables are variables declared within a class, outside any method,
with the static keyword.
A class can have any number of methods to access the value of various kinds of methods.
1
Java Objects:
Object is an instance of a class. An object in OOPS is nothing but a self-contained component
which consists of methods and properties to make a particular type of data useful.
Multiple Objects
You can also create an object of a class and access it in another class. This is often used for better
organization of classes (one class has all the attributes and methods, while the other class holds
the main() method (code to be executed)).
Remember that the name of the java file should match the class name
2
SOURCE CODE:
import java.util.Scanner;
class Rect {
private double w,l,a;
private String colour;
Scanner d=new Scanner(System.in);
void get_length()
{
System.out.println("enter the length");
l=d.nextDouble();
}
void get_width()
{
System.out.println("enter the width");
w=d.nextDouble();
}
void get_colour()
{
3
}
public class Rectangle{
public static void main(String[] args){
Rect R1=new Rect();
Rect R2=new Rect();
System.out.println("first rectangle");
R1.get_length();
R1.get_width();
R1.get_colour();
System.out.println("second rectangle");
R2.get_length();
R2.get_width();
R2.get_colour();
String c1=R1.show_colour();
String c2=R2.show_colour();
if((R1.find_area()==R2.find_area())&&(c1.compareTo(c2)==0))
System.out.println("matching rectangle");
else
Output
4
Conclusion:
References:
Herbert Schildt , “Java : The Complete Reference” Tata McGraw-Hill (7th Edition).
Questions:
5
Experiment No.4
Aim of the Experiment: Write a program in JAVA to demonstrate the method and constructor
overloading.
Objective:
To understand the method and constructor overloading in Java.
Resources: Eclipse IDE 2018, JDK 1.8.0 is required
Course Outcome Addressed: CO2: Apply the concepts of classes and objects to write
programs in Java
Theory:
Method in Java:
Method Declaration
The method declaration provides information about method attributes, such as visibility, return-
type, name, and arguments. It has six components that are known as method header, as we have
shown in the following figure.
1
Method Signature: Every method has a method signature. It is a part of the method declaration.
It includes the method name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. It specifies the
visibility of the method. Java provides four types of access specifier:
o Public: The method is accessible by all classes when we use public specifier in our
application.
o Private: When we use a private access specifier, the method is accessible only in the classes
in which it is defined.
o Protected: When we use protected access specifier, the method is accessible within the
same package or subclasses in a different package.
o Default: When we do not use any access specifier in the method declaration, Java uses
default access specifier by default. It is visible only from the same package only.
Return Type: Return type is a data type that the method returns. It may have a primitive data type,
object, collection, void, etc. If the method does not return anything, we use void keyword.
Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. Suppose, if we are creating a method for
subtraction of two numbers, the method name must be subtraction(). A method is invoked by its
name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter, left the
parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be performed. It
is enclosed within the pair of curly braces.
Naming a Method
While defining a method, remember that the method name must be a verb and start with
a lowercase letter. If the method name has more than two words, the first name must be a verb
followed by adjective or noun. In the multi-word method name, the first letter of each word must
be in uppercase except the first word. For example:
Single-word method name: sum(), area()
Multi-word method name: areaOfCircle(), stringComparision()
Types of Method
2
There are two types of methods in Java:
1. Predefined Method
2. User-defined Method
1. Predefined Method
In Java, predefined methods are the method that is already defined in the Java class libraries is
known as predefined methods. It is also known as the standard library method or built-in
method. We can directly use these methods just by calling them in the program at any point. Some
pre-defined methods are length(), equals(), compareTo(), sqrt(), etc. When we call any of the
predefined methods in our program, a series of codes related to the corresponding method runs in
the background that is already stored in the library.Each and every predefined method is defined
inside a class. Such as print() method is defined in the java.io.PrintStream class. It prints the
statement that we write inside the method. For example, print("Java"), it prints Java on the
console.
2. User-defined Method
The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.
Method Overloading:
Method Overloading is a feature that allows a class to have more than one method with the
same name, if their argument lists are different. This is an important feature in java, there are
several cases where we need more than one methods with same name, for example if we are
building an application for calculator, we need different variants of add method based on the user
inputs such as add(int, int), add(float, float) etc. Argument list means the parameters that a method
has: For example the argument list of a method add(int a, int b) having two int parameters is
different from the argument list of the method add(int a, int b, int c) having three int parameters.
Three ways to overload a method
In order to overload a method, the argument lists of the methods must differ in either of these:
1. Number of parameters.
For example: This is a valid case of overloading
add(int, int)
add(int, int, int)
3
add(int, float)
add(float, int)
Constructor in Java:
A constructor in Java is a special method that is used to initialize objects. The constructor is called
when an object of a class is created. It can be used to set initial values for object attributes. Every
time an object is created using the new() keyword, at least one constructor is called. Constructors
must have the same name as the class within which it is defined, Constructors do not return any
type, Constructors are called only once at the time of Object creation.
Types of Java Constructors
1. Default constructor (no-arg constructor)
This type of constructor is called whenever we create an object without passing any
argument to the constructor.
2. Parameterized constructor
This type of constructor is called if we want to initialize an object by passing a few
arguments in the constructor. I
Constructor overloading:
The constructor overloading can be defined as the concept of having more than one constructor
with different parameters so that every constructor can perform a different task.
The key advantages of making use of constructor overloading while writing Java programs are:
4
• The class instances can be initialized in several ways with the use of constructor
overloading.
• It facilitates the process of defining multiple constructors in a class with unique signatures.
• Each overloaded constructor performs various tasks for specified purposes.
SOURCE CODE:
4.a. Method overloading
package SapJava;
public class MethodOverload {
void sum (int a, int b)
{
System.out.println("sum is"+(a+b)) ;
}
void sum (int a, int b, int c)
{
System.out.println("sum is"+(a+b+c)) ;
}
void sum (double a, double b)
{
System.out.println("sum is"+(a+b));
}
public static void main (String[] args)
{
MethodOverload cal = new MethodOverload();
System.out.println("Method Overloading");
cal.sum (8,5); //sum(int a, int b) is method is called.
cal.sum (5,5,5); //sum(int a, int b,int c) is method is called.
cal.sum (4.6, 3.8); //sum(double a, double b) is called.
}
}
5
4.b.Constructor overloading
package SapJava;
public class Student {
int id; //instance variables of the class
String name;
Student(){
System.out.println("This a default constructor");
}
6
Conclusion:
References:
Herbert Schildt , “Java : The Complete Reference” Tata McGraw-Hill (7th Edition).
Questions:
7
Experiment No. 5
Aim of the Experiment: Write programs in Java to sort i) List of integers ii) List of names.
The objective of this assignment is to learn Arrays and Strings in Java
Arrays: An array is collection of homogenous or similar data items which are related and share
same common name. Arrays are single types of integers, floats or characters.
3. Initialization of arrays.
arrayname [index] = value;
For eg: a[0] = 35;
1
Two-dimensional Arrays: You need two-dimensional arrays to store a table of values.
For eg: inttable[][];
table = new int [2][3];
or
int table = new int[2][3];
or
int table[2][3] = {0,0,0,1,1,1};
or
int table[][] = {{0,0,0},{1,1,1}};
Algorithm:
STEP 1: START
STEP 2: Initialize array
STEP 3: Displaying elements of original array
STEP 4: Sort the array in ascending order
if(arr[i]>arr[j]) then
temp = arr[i]
arr[i]=arr[j]
arr[j]=temp
2
STEP 6: END
SOURCE CODE:
package fjp_50_46;
import java.util.Arrays;
import java.util.Scanner;
public class SortInt {
public static void main(String[] args) {
Scanner read=new Scanner(System.in);
int count,b,temp,c;
int a[]=new int[10];
System.out.println("How many integers You want to Enter?");
count=read.nextInt();
for(b=0;b<count;b++)
{
System.out.println("Enter values:");
temp=read.nextInt();
a[b]=temp;
}
System.out.println("The array before sorting:");
for(b=0;b<count;b++) {
System.out.println(a[b]+" ");
}
System.out.println("The array after sorting:");
for(b=0;b<count;b++)
{
for(c=0;c<count -b-1;c++)
{
if(a[c]>a[c+1])
{
temp=a[c];
a[c]=a[c+1];
a[c+1]=temp;
}
}
}
for(b=0;b<count;b++) {
System.out.println(a[b]+" ");
3
}
}
Output: -
4
package fjp_46_50;
import java.util.Scanner;
import java.util.Arrays;
public class SortNames {
public static void main(String[]args)
{
int i,j,n;
Scanner ip = new Scanner(System.in);
System.out.println("how many string you want to enter" );
n=ip.nextInt();
String name[]=new String[n+1];
System.out.println("enter string:");
for(i=0;i<n;i++)
name[i]=ip.next();
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(name[i].trim().compareTo(name[j].trim())>0)
{
String temp=name[i];
name[i]=name[j];
name[j]=temp;
}
}
}
System.out.println("sorted list is :");
for(i=0;i<n;i++)
System.out.println(" "+name[i]);
}
}
5
Output: -
Conclusion:
References:
Herbert Schildt, “Java : The Complete Reference” Tata McGraw-Hill (7th Edition).
6
Questions:
1. Explain Arrays in Java.
2. Explain Strings in Java
3. Give comparison of one dimensional array and two dimensional array.
4. Explain different strings methods.
5. Compare String class and StringBuffer class.
6. Which order of sorting is done by default?
7. How to sort array or list in descending order?
7
Experiment No.6
Aim of the Experiment: Write programs in Java to add two matrices
Course Outcome Addressed: CO3: Demonstrate the concepts of methods & Inheritance
Theory:
Arrays: An array is collection of homogenous or similar data items which are related and share
same common name. Arrays are single types of integers, floats or characters.
3. Initialization of arrays.
arrayname [index] = value;
For eg: a[0] = 35;
1
Int variable = arrayname.length;For eg: intlen =
a.length;
2
mat1[][],mat2[][],res[][] with same row number,column number.
4) Store the first matrix elements into the two-dimensional array mat1[][] using two for loops. i
indicates row number, j indicates column index.Similarly matrix 2 elements in to mat2[][].
5) Add the two matrices using for loop
• for i=0 to i<row
• for j=0 to j<col
• mat1[i][j] + mat2[i][j] and store it in to the matrix res at res[i][j] .
Algorithm:
STEP1: START
STEP 2: Take the two matrices to be added
STEP 3: Create a new Matrix to store the sum of the two matrices
STEP4: Traverse each element of the two matrices and add them. Store this sum in the new
matrix at the corresponding index.
STEP 4:Print the final new matrix
STEP 6: END
SOURCE CODE:
package fjp_46_50;
import java.util.Arrays;
import java.util.Scanner;
public class Matrix {
public static void main(String[] args) {
int row,col;
int[][]a = new int[20][20];
int[][]b = new int[20][20];
int[][]c = new int[20][20];
Scanner sc = new Scanner(System.in);
System.out.println("enter the number of rows and columns");
row = sc.nextInt();
col = sc.nextInt();
System.out.println("enter numbers in matrix a");
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
a[i][j]=sc.nextInt();
}
}
System.out.println("enter numbers in matrix b");
for(int i=0;i<row;i++)
3
{
for(int j=0;j<col;j++)
{
b[i][j]=sc.nextInt();
}
}
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
c[i][j]= a[i][j]+b[i][j];
}
}
System.out.println(" Matrix c is:");
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
System.out.println(c[i][j]);
}
}
}
}
Output:
4
Conclusion:-
References:
Herbert Schildt , “Java : The Complete Reference” Tata McGraw-Hill (7th Edition).
Questions:
1.Write programs in Java to subtract two matrice
5
Experiment No.7
Aim of the Experiment: Write a program in Java to create a player class. Inherit the classes
Cricket_player, Football_player and Hockey_player from player class
Course Outcome Addressed: CO3: Demonstrate the concepts of methods & Inheritance
Theory:
Inheritance
• Inheritance is a mechanism of reusing something that already exists rather than creating the
same all over again.
• Inheritance refers to properties sharing. It is possible to derive a new class from old one.
Thus, the new class will get the properties from the old one.
• The old class is called base class or super class or parent class.
• The new one is called the derived class or sub class or child class.
Types of Inheritance:
1. Single Inheritance: It has one parent class and one child class.
Syntax: class classname extends parentclassname
{
Variable declaration;
Method declaration;
}
The extends keyword signifies that the properties of the parent class are extended to the child
class. Now the child class will contain its own variables and methods plus that of the parent
class.
2. Multilevel Inheritance: A child class is derived from a derived class. This allow us to build
a chain of classes.
Syntax: class A
{ }
1
class B extends A
{ }
class C extends B
{ }
Player
Algorithm:
Create Base Class as "Player"
Step1] Create member variable "gname" as "String"datatype
Step2] Write Parameterized Constructor"Player" with argument "gname" and store this value
into member variable by using "this" keyword.
Step3] Stop
2
Create Derived Class as "Cricket_player "
Step1] Create member variable "no_of_player" as "int"datatype
Step3] Write Function "display" which will display the value of variable "gname" from Base
class "Player" and "no_of_player" from derived class "Cricket_player "
Step4] Stop
Step2] Write Parameterized Constructor "Football_player " with arguments "gname" and
"no_of_player". Pass the value of "gname" to Base Class "Player" using "super" keyword and
Store"no_of_player" value into member variable by using "this" keyword.
Step3] Write Function "display" which will display the value of variable "gname" from Base
class "Player" and "no_of_player" from derived class "Football_player "
Step4] Stop
Step3] Write Function "display" which will display the value of variable "gname" from Base
class "Player" and "no_of_player" from derived class "Hockey_player"
Step4] Stop
3
Source Code: -
package fjp_50_46;
import java.util.Scanner;
public class PlayerDetails {
public static void main(String[] args) {
Cricket ckt = new Cricket();
Football fb = new Football();
Hockey hk = new Hockey();
Scanner read = new Scanner(System.in);
int op1 , op2;
while(true)
{
System.out.println("\n 1.Enter Details 2.Display 3.Exit");
System.out.print("\nEnter your option : ");
op1 = read.nextInt();
switch(op1)
{
case 1:
System.out.println("\n 1.Football Player 2.Hockey
Player 3.Cricket Player");
System.out.print("\nEnter your option : ");
op2= read.nextInt();
switch(op2)
{
case 1:
System.out.print("Enter Name : ");
fb.name = read.next();
System.out.print("Enter age : ");
fb.age = read.nextInt();
System.out.print("Enter Skill : ");
fb.Skill = read.next();
break;
case 2:
System.out.print("Enter Name : ");
hk.name = read.next();
System.out.print("Enter age : ");
hk.age = read.nextInt();
System.out.print("Enter Skill : ");
4
hk.Skill = read.next();
break;
case 3:
System.out.print("Enter Name : ");
ckt.name = read.next();
System.out.print("Enter age : ");
ckt.age = read.nextInt();
System.out.print("Enter Skill : ");
ckt.Skill = read.next();
break;
}
break;
case 2:
System.out.println(" \n1.Football Player 2.Hockey
Player 3.Cricket Player");
System.out.print("\nEnter your option : ");
op2= read.nextInt();
switch(op2)
{
case 1:
System.out.println("Name : " + fb.name);
System.out.println("Age : " + fb.age);
System.out.println("Skill : " + fb.Skill);
break;
case 2:
System.out.println("Name : " + hk.name);
System.out.println("Age : " + hk.age);
System.out.println("Skill : " + hk.Skill);
break;
case 3:
System.out.println("Name : " + ckt.name);
System.out.println("Age : " + ckt.age);
System.out.println("Skill : " + ckt.Skill);
break;
}
break;
case 3:
System.exit(0);
}
5
}
}
}
class Player{
String name;
int age;
String Skill;
}
class Cricket extends Player{
}
class Football extends Player{
}
class Hockey extends Player{
}
Output: -
6
Conclusion: -
References:
Herbert Schildt , “Java : The Complete Reference” Tata McGraw-Hill (7th Edition).
Questions:
1. What is Inheritance in Java?
2. What is Is-A relationship in Java?
3. What is super class and subclass?
4. What is super class and subclass?
5. What are the types of inheritance in Java?
6. Why multiple inheritance is not supported in java through class
7
Experiment No.8
Aim of the Experiment: Write a Java Program which implements Interface
Course Outcome Addressed: CO4: Use the concepts of interfaces & packages for
program implementation
Theory:
Introduction:
An Interface is a kind of class that only contains the methods without any implementation. An
interface is a named collection of method definitions (without implementations). An interface
can also include constant declarations. Each variable that is defined in interface should be final
and static.
Defining Interfaces:
• Java does not support multiple inheritance. Instead, it provides an alternative approach
known as interfaces.
• Interface is a kind of class.
• Interface contains methods and variables but the methods are only abstract and variables are
final.
• The class that implements interface define the code for these abstract methods.
• The syntax for defining an interface:
interfaceinterfacename
{ variable declaration;
methods declaration;
}
• Methods declaration will contain only a list of methods without any body statements.
1
return_typemethodname(param);
For eg: interface area
{
final static float pi = 3.14;
floatcalc(float x, float y);
voiddisparea();
}
Algorithm:
Step1] Create interface named “Shape” with constant variable as “pi=3.14” and abstract method
“area()”
interface Shape
{
final float pi=3.14f;
public void area();
}
Step2] Create Class “Circle” with data member as “r” and constructor to initialize r and code for
abstract method is implemented. In that, area of circle is calculated and display.
public void area()
{
System.out.println("Area of Circle = "+(pi*r*r));
}
Step3] Create Class “Sphere” with data member as “r” and constructor to initialize r and code for
abstract method is implemented. In that, area of circle is calculated and display.
public void area()
{ System.out.println("Area of Sphere = "+(4*pi*r*r));
}
Step4] In main function, interface Shape-create reference variable and refer to implemented class
named ”Circle” and call method “area”
Shape s;
s = new Circle(r);
s.area();
2
Step5] In main function, interface Shape-create reference variable and refer to implemented class
named ”Sphere” and call method “area”
s=new Sphere(r);
s.area();
Source Code: -
package fjp_46_50;
public class Interface {
public static void main(String[] args) {
deptName D = new deptName();
D.ENTC();
D.CS();
D.AIDS();
}
}
interface Department {
public void ENTC();
public void CS();
public void AIDS();
}
class deptName implements Department{
public void ENTC()
{
System.out.println("Subjects for ENTC are : \n 1)Control Systems
\n 2)Fundamentals of Java Programming \n 3)Microcontroller \n\n");
}
public void CS()
{
System.out.println("Subjects for CS are : \n 1)DBMS \n 2)Data
Structures \n 3)Computer Networks\n\n");
}
public void AIDS()
{
System.out.println("Subjects for AIDS are : \n 1)Web Technology
\n 2)Statistics \n 3)Blockchain\n\n");
}
}
3
Output:
Conclusion:-
References:
Herbert Schildt , “Java : The Complete Reference” Tata McGraw-Hill (7th Edition).
Questions:
1. What is an interface in Java?
2. What is the use of interface in Java?
3. Suppose A is an interface. Can we create an object using new A()?
4. What is the difference between class and interface in Java?
5. Why an Interface can extend more than one Interface but a Class can’t extend more than
one Class
4
Experiment No.09
Aim of the Experiment: Write a Java program which use try and catch for exception
handling.
Theory:
An expectation is an unexpected event that occurs while executing the program, that disturbs the
normal flow of the code.
Exception handling in java helps in minimizing exceptions and helps in recovering from
exceptions. It is one of the powerful mechanisms to handle runtime exceptions and makes it bug-
free. Exception handling helps in maintaining the flow of the program. An exception handling is
defined as an abnormal condition that may happen at runtime and disturb the normal flow of the
program.
Applet:
Exception Hierarchy –
Following is the Exception Handling in Java handling hierarchy.
Throwable –
• It is the root class for the exception hierarchy in java.
• It is in the java.lang package.
Error –
• Subclass of Throwable.
• Consist of abnormal condition that is out of one’s control and depends on the
environment
• They can’t be handled and will always result in the halting of the program.
• Eg: StackOverFlowError that can happen in infinite loop or recursion
Exception –
• Subclass of Throwable.
• Consist of abnormal conditions that can be handled explicitly.
• If one handles the exception then our code will continue to execute smoothly.
1
Types of exception in Java
Checked Exceptions
• Those exceptions that are checked at compile-time comprises checked exceptions.
• They are child classes of Exception except for RuntimeException.
• The program will not compile if they are not handled.
• Example: IOException, ClassNotFoundException, etc.
•
Unchecked Exceptions
• Those exceptions that are checked at runtime comprises unchecked exceptions.
• They are child classes of RuntimeException.
• They give runtime errors if not handled explicitly.
• Example: ArithmeticException, NullPointerException etc.
The catch block is used to catch the exception thrown by statements in the try block. The catch
must follow try else it will give a compile-time error.
Try-catch syntax:
try{
}
catch(Exception e){
}
Try-catch Example:
public class ExceptionDemo {
public static void main (String[] args) {
int a=10;
for(int i=3;i>=0;i--)
try{
System.out.println(a/i);
}
catch(ArithmeticException e){
System.out.println(e);
}
}
2
Output:
3
5
10
java.lang.ArithmeticException: / by zero
Source Code: -
package fjp_46_50;
public class Exception {
public static void main(String[] args) {
int a,b,c;
try
{
a=0;
b=10;
c=b/a;
System.out.println("This line will not be executed");
}
catch(ArithmeticException e)
{
System.out.println("Divided by zero");
}
System.out.println("After exception is handled");
}
}
Output:
3
Conclusion: -
References:
Herbert Schildt , “Java : The Complete Reference” Tata McGraw-Hill (7th Edition).
Questions:
1. Why do we need exception handling in Java?
2. Name the different types of exceptions in Java.
3. What is the difference between exception and error in Java?
4. How can you handle exceptions in Java?
4
Experiment No.10
Aim of the Experiment: Write a Java program to draw oval, rectangle, line, text using
graphics class.
Course Outcome Addressed: CO6: Use Graphics class, AWT packages and manage input and
output files in Java
Theory:
Applet:
• An applet is a special kind of java program that is primarily used in Internet computing.
• It can be transported from one computer to another on internet and run using the applet
viewer or any java capable web browser such as HotJava or Netscape.
Initialization State:
o Initialization State:
▪ Applet enters the initialization state when it is first loaded.
▪ This is achieved by calling the init() method of Applet Class.
5
▪ The initialization occurs only once in the applet’s life cycle.
▪ This method is executed only once in applet life cycle.
▪ public void init()
▪ {……}
o Running State:
▪ Applet enter the running state when the system calls the start() method of Applet
class.
▪ This occurs automatically after the applet is initialized.
▪ The start() method may be called more than once.
public void start()
{…….}
o Idle or Stopped State:
▪ An applet becomes idle when it is stopped from running.
▪ We can also do so by calling the stop() method explicitly.
▪ If we use a thread to run the applet, then we must use stop() method to terminate the
thread.
▪ We can achieve by overriding the stop() method:
public void stop()
{………}
o Dead State:
▪ An applet is said to be dead when it is removed from memory.
▪ This occurs automatically by invoking destroy() method when we quit browser.
▪ Like initialization, destroying stage occurs only once in the applet’s life cycle.
▪ If the applet has created any resources like threads, we may override the destroy()
method to clean up these resources.
public void destroy()
{………}
o Display State:
▪ Applet moves to the display state whenever it has to perform some output operations
on the screen.
▪ This happens immediately after the applet enters into the running state.
▪ The paint() method is called to accomplish this task.
public void paint(Graphics g)
{………}
6
Algorithm:
Step1] Inside multiline comment, add applet tag
/*
<applet code="Slip12" width=400 height=400>
</applet>
*/
Step2] In paint() method, change color and call drawOval(), fillOval() method with co-ordinates
with the help of graphics “g”.
g.setColor(Color.red);
g.drawOval(200 , 10, 50,80);
g.setColor(Color.yellow);
g.fillOval(201 , 11, 49,79);
Step3] Next, change color and call drawRect(), fillRect() method with co-ordinateswith the help
of graphics “g”.
g.setColor(Color.blue);
g.drawRect(100 , 100, 50,100);
g.setColor(Color.cyan);
g.fillRect(101 , 101, 49,99);
Step4] Next, change color and call drawLine()method with co-ordinateswith the help of graphics
“g”.
g.setColor(Color.black);
g.drawLine(0 , 220 , 100 , 220);
Step5] Next, change color and call drawString() method with co-ordinates with the help of
graphics “g”.
g.setColor(Color.green);
g.drawString("Welcome" , 100 ,250);
Step6] Stop
7
Source Code: -
package fjp_50_46;
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
public class GApplet extends Applet {
public void paint(Graphics g)
{
g.drawString("My Applet", 10, 10);
g.drawLine(20, 20, 500, 20);
g.drawRect(20, 40, 200, 40);
g.fillRect(300, 40, 200, 40);
g.drawRoundRect(20, 100, 200, 40, 10, 10);
g.fillRoundRect(300 , 100 , 200 , 40 , 10 , 10);
g.setColor(Color.magenta);
g.drawOval(20, 160, 200, 100);
g.fillOval(300, 160, 200, 100);
}
Output:
Conclusion:
8
References:
Herbert Schildt , “Java : The Complete Reference” Tata McGraw-Hill (7th Edition).
Questions:
1. What is an applet?
2. What is the lifecycle of an applet?
3. How will you initialize an applet?
9
Experiment No.11
Aim of the Experiment: Write a Java program in which data is read from one file and
should be written in another file line by line
Theory:
FILES
Stream:
• A sequence of bytes is called as stream.
• Stream in which writing data to a stream is called as Output Stream.
• Stream in which reading data from a stream is called as Input Stream.
• Stream in which buffer in memory, such stream is called as a Buffered Stream.
• A binary Stream contains the binary data, while Character Stream contains the character
data. Character Streams are basically used to storing and retrieving text.
• There are four types of Stream:
o Reader: A stream to read characters.
o Writer: A stream to write characters.
o InputStream: A stream to read binary data.
o OutputStream: A stream to write binary data.
1
• Predefined Stream: System class define by the package java.lang package automatically by
the java programs.
o System.out: Standard Output by default, i.e. console.
o System.in: Standard Input provide by keyboard by default.
o System.err: For the outputting error.
1. FileReader:
• The FileReader class is a subclass of InputStreamReader.
• It is used to read characters from a file.
• Initially file opening must essential before read from or write to a file.
Syntax: FileReaderfileptrname = new FileReader(filename);
For eg: FileReaderfp = new FileReader(“sample.java”);
2. FileWriter:
• FileWriter provides a convenient way to writing characters to a file.
• To open a file for writing use the FileWriter class and create an instance from it.
FileWriter f = new FileWriter(“sample”);
• Constructors of FileWriter:
publicFileWriter(File file)
publicFileWriter(File file, boolean append)
publicFileWriter(String path)
publicFileWriter(String path, boolean append)
publicFileWriter(FileDescriptorfd)
• Methods in FileWriter Class:
write(String str) – Writes string or array of chars to file.
write(int n) – Writes a int value into a file.
flush – Writes any buffered chars to file.
close – Closes the file stream after performing a flush.
Algorithm:
2
Step3] Read character by character with help of read() method from file object “fr”and store it in
character type variable “c”.
Step4] Store character type “c” into file object “fw” with help of write() method and also print it
on screen
Step8] Stop
Source Code: -
package fjp_50_46_49_43;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
class Filetransfer {
public static void main(String arg[]) {
File inf = new File("A.txt");
File outf = new File("B.txt");
FileReader ins = null;
FileWriter outs = null;
try {
ins = new FileReader(inf);
outs = new FileWriter(outf);
int ch;
while ((ch = ins.read()) != -1)
{
outs.write(ch);
}
}
catch (IOException e)
3
{
System.out.println(e);
System.exit(-1);
}
finally
{
try {
ins.close();
outs.close();
}
catch (IOException e) {}
}
System.out.println("File Copied");
}
}
Output:
4
Conclusion: -
5
References:
Herbert Schildt , “Java : The Complete Reference” Tata McGraw-Hill (7th Edition).
Questions:
1. How do you read from and write to files using Java code?
2. What are the different ways of reading a file in Java?
3. What is the difference between InputStream and OutputStream in Java.
4. What is the difference between BufferedReader and FileReader in Java?
5. What are the basic methods in File class?