You are on page 1of 13

BCA 305: Practical on JAVA

Practical No. 1. Write a Java program that demonstrates program structure of java. (Fibonacci Series,
Factorial etc.)
Aim: Write a Java program that demonstrates program structure of java. (Fibonacci Series, Factorial
etc.)
Example
import java.util.*;

class First
{
public static void main(String[] args)
{
System.out.println("Hello Java"); System.out.println("My
First Java Program");
}
}

Steps For compile Java Program


 First Save Java program with same as class name with .java
extension. Example: First.java

 Compile: javac
Filename.java
Example, javac
First.java

Note: Here javac is tools or application programs or exe files which is used for
Compile theJava program.

Steps For Run Java Program


 For run java program use java tool.
 Run by: java
Filename
Example: java
First
 Note: Here java is tools or application programs or exe files which is used for run the Java
program
.
Factorial Program in Java: Factorial of n is the product of all positive descending integers. Factorial of n is
denoted by n!. For example:
4! = 4*3*2*1 = 24
5! = 5*4*3*2*1 = 120

Here, 4! is pronounced as "4 factorial", it is also called "4 bang" or "4 shriek".

The factorial is normally used in Combinations and Permutations (mathematics).

Fibonacci series in Java

The Fibonacci series is a series where the next term is the sum of the previous two terms. The first two terms
of the Fibonacci sequence are 0 followed by 1.

Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34

Suppose, our first two terms are:


firstTerm = 0
secondTerm = 1

The next terms in the Fibonacci series would be calculated as:


nextTerm = firstTerm + secondTerm; (0 + 1)
firstTerm = secondTerm; (1)
secondTerm = nextTerm; (1)

nextTerm = firstTerm + secondTerm; (1 + 1)


....
Practical No. 2. Write a Java program to demonstrate use of class and object.
Aim. Write a Java program to demonstrate use of class and object.
Object
Any entity that has state and behavior is known as an object.
In Object can be defined as an instance of a class. An object contains an address and takes up
some space in memory. Objects can communicate without knowing the details of each other's
data or code. The only necessary thing is the type of message accepted and the type of response
returned by the objects.

State: represents the data (value) of an object.

Behavior: represents the behavior (functionality) of an object such as deposit, withdraw, etc.

Identity: An object identity is typically implemented via a unique ID. The value of the ID is not
visible to the external user. However, it is used internally by the JVM to identify each object
uniquely.

Class
A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created. It is a logical entity. It can't be physical.
A class in Java can contain:

Fields, Methods, Constructors, Blocks, Nested class and interface

Collection of objects is called class. It is a logical entity. A class can also be defined as a
blueprint from which you can create an individual object. Class doesn't consume any space.

Syntax to declare a class:

class <class_name>
{
field;

method;

Practical No. 3. Write a Java program that demonstrates all string operations.
Aim. Write a Java program that demonstrates all string operations.

What is String in Java?

Generally, String is a sequence of characters. But in Java, string is an object that represents a
sequence of characters. The java.lang.String class is used to create a string object.
How to create a string object?

There are two ways to create String object:

 By string literal
 By new keyword
 String Literal

Java String literal is created by using double quotes. For Example:

String s="welcome";

Each time you create a string literal, the JVM checks the "string constant pool" first. If the string
already exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist
in the pool, a new string instance is created and placed in the pool. For example:

String s1="Welcome";

String s2="Welcome";//It doesn't create a new instance

Ex. String firstName = "John ";

String lastName = "Doe";

System.out.println(firstName.concat(lastName));

The concat() method appends (concatenate) a string to the end of another string.

Practical No. 4. Write a Java program to demonstrate use of constructor and finalize method.
Aim. Write a Java program to demonstrate use of constructor and finalize method.

Constructors in Java

In Java, a constructor is a block of codes similar to the method. It is called when an instance of
the class is created. At the time of calling constructor, memory for the object is allocated in the
memory. It is a special type of method which is used to initialize the object. Every time an object
is created using the new() keyword, at least one constructor is called. It calls a default constructor
if there is no constructor available in the class. In such case, Java compiler provides a default
constructor by default.

Rules for creating Java constructor

 There are two rules defined for the constructor.


 Constructor name must be the same as its class name
 A Constructor must have no explicit return type
 A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors

There are two types of constructors in Java:


1. Default constructor (no-arg constructor)
2. Parameterized constructor

Java Default Constructor


A constructor is called "Default Constructor" when it doesn't have any parameter.
Syntax of default constructor:
<class_name>()

{}

Java Parameterized Constructor

A constructor which has a specific number of parameters is called a parameterized constructor

Finalize method

 It is a method that the Garbage Collector always calls just before the deletion/destroying of the
object
 which is eligible for Garbage Collection, so as to perform clean-up activity. Clean-up activity means
closing the resources associated with that object like Database Connection,

Practical No. 5. Write a Java program to demonstrate use of method overloading.


Aim: Write a Java program to demonstrate use of method overloading.

Method Overloading in Java

Method Overloading allows different methods to have the same name, but different signatures where the
signature can differ by the number of input parameters or type of input parameters, or a mixture of both.

Method overloading is also known as Compile-time Polymorphism, Static Polymorphism, or Early binding
in Java. In Method overloading compared to parent argument, child argument will get the highest priority.

In Java, two or more methods may have the same name if they differ in parameters (different number of
parameters, different types of parameters, or both). These methods are called overloaded methods and this
feature is called method overloading. For example:
void func() { ... }
void func(int a) { ... }
float func(double a) { ... }
float func(int a, float b) { ... }

Here, the func() method is overloaded. These methods have the same name but accept different arguments.
Note: The return types of the above methods are not the same. It is because method overloading is not
associated with return types. Overloaded methods may have the same or different return types, but they must
differ in parameters.

Practical No. 6. Write a Java program to demonstrate use of wrapper class.


Aim: Write a Java program to demonstrate use of wrapper class.

Wrapper classes in Java


The wrapper class in Java provides the mechanism to convert primitive into object and object into primitive.
In autoboxing and unboxing feature convert primitives into objects and objects into primitives automatically.
The automatic conversion of primitive into an object is known as autoboxing and vice-versa unboxing.

Use of Wrapper classes in Java


Java is an object-oriented programming language, so we need to deal with objects many times like in
Collections, Serialization, Synchronization, etc.
Let us see the different scenarios, where we need to use the wrapper classes.

 Change the value in Method: Java supports only call by value. So, if we pass a primitive value, it
will not change the original value. But, if we convert the primitive value in an object, it will change the
original value.
 Serialization: We need to convert the objects into streams to perform the serialization. If we have a
primitive value, we can convert it in objects through the wrapper classes.
 Synchronization: Java synchronization works with objects in Multithreading.
 java.util package: The java.util package provides the utility classes to deal with objects.

 The eight classes of the java.lang package are known as wrapper classes in Java. The list of eight
wrapper classes are given below:
Primitive Type Wrapper class
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
Autoboxing
The automatic conversion of primitive data type into its corresponding wrapper class is known as autoboxing,
for example, byte to Byte, char to Character, int to Integer, long to Long, float to Float, boolean to Boolean,
double to Double, and short to Short.
Since Java 5, we do not need to use the valueOf() method of wrapper classes to convert the primitive into
objects.
Unboxing
The automatic conversion of wrapper type into its corresponding primitive type is known as unboxing. It is the
reverse process of autoboxing. Since Java 5, we do not need to use the intValue() method of wrapper classes
to convert the wrapper type into primitives.
Practical No. 7. Write a Java program to demonstrate use of package.
Aim. Write a Java program to demonstrate use of package.

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.


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

How to compile java package

If you are not using any IDE, you need to follow the syntax given below:
javac -d directory javafilename
For example

javac -d . Simple.java

The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to
keep the package within the same directory, you can use . (dot).

How to run java package program

You need to use fully qualified name e.g. mypack.Simple etc to run the class.

 To Compile: javac -d .
Simple.java
 To Run: java mypack.Simple

How to access package from another package?

There are three ways to access the package from outside the package.
import package.*;
import package.classname;
fully qualified name.
1) Using packagename.*

If you use package.* then all the classes and interfaces of this package will be
accessible but notsubpackages.
The import keyword is used to make the classes and interface of another package
accessible tothe current package.

Practical No. 8. Write a Java program that demonstrates inheritance.


Aim. Write a Java program that demonstrates inheritance.

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

 Class: A class is a group of objects which have common properties. It is a


template or blueprint from which objects are created.
 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.
 Super Class/Parent Class: Superclass is the class from where a subclass
inherits the features. It is also called a base class or a parent class.
 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.
The syntax of Java Inheritance

class Subclass-name extends Superclass-name

//methods and fields

The extends keyword indicates that you are making a new class that derives from
an existingclass. The meaning of "extends" is to increase the functionality. In the
terminology of Java, a class which is inherited is called a parent or superclass, and
the new class is called child or subclass.
Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel
and hierarchical. In java programming, multiple and hybrid inheritance is supported
through interfaceonly.
Single Inheritance Example

When a class inherits another class, it is known as a single inheritance. In the example
given below, Dog class inherits the Animal class, so there is the single inheritance.
Multilevel Inheritance Example

When there is a chain of inheritance, it is known as multilevel inheritance. As you can


see in theexample given below, BabyDog class inherits the Dog class which again
inherits the Animal class, so there is a multilevel inheritance.

Practical No. 9. Write a Java program to demonstrate interface.


Aim. Write a Java program to demonstrate interface.
An interface is a fully abstract class. It includes a group of abstract methods (methods without a
body).
We use the interface keyword to create an interface in Java. For example,

interface Language {
public void getType();

public void getVersion();


}
Here,
 Language is an interface.
 It includes abstract methods: getType() and getVersion().

Implementing an Interface
Like abstract classes, we cannot create objects of interfaces.
To use an interface, other classes must implement it. We use the implements keyword to
implement an interface.
In the above example, we have created an interface named Polygon. The interface contains an
abstract method getArea().
Here, the Rectangle class implements Polygon. And, provides the implementation of the
getArea() method.

Practical No. 10. Write a Java program that demonstrates inner class.
Aim. Write a Java program that demonstrates inner class.

Java Inner Classes


In Java, it is also possible to nest classes (a class within a class). The purpose of nested classes is
to group classes that belong together, which makes your code more readable and maintainable.

To access the inner class, create an object of the outer class, and then create an object of the
inner class:

class OuterClass {
int x = 10;

class InnerClass {
int y = 5;
}
}

public class Main {


public static void main(String[] args) {
OuterClass myOuter = new OuterClass();
OuterClass.InnerClass myInner = myOuter.new InnerClass();
System.out.println(myInner.y + myOuter.x);
}
}

Private Inner Class

Unlike a "regular" class, an inner class can be private or protected. If you don't want outside
objects to access the inner class, declare the class as private:

If you try to access a private inner class from an outside class, an error occurs:

Main.java:13: error: OuterClass.InnerClass has private access in OuterClass


OuterClass.InnerClass myInner = myOuter.new InnerClass();

Static Inner Class

An inner class can also be static, which means that you can access it without creating an object
of the outer class:

Practical No. 11. Write a Java program that demonstrates Exception (Divide by 0).
Aim. Write a Java program that demonstrates Exception (Divide by 0).

We know that exceptions abnormally terminate the execution of a program.


This is why it is important to handle exceptions. Here's a list of different approaches to handle
exceptions in Java.

 try...catch block
 finally block
 throw and throws keyword

1. Java try...catch block

The try-catch block is used to handle exceptions in Java. Here's the syntax of try...catch block:
try {
// code
}
catch(Exception e) {
// code
}

Here, we have placed the code that might generate an exception inside the try block. Every try
block is followed by a catch block.

When an exception occurs, it is caught by the catch block. The catch block cannot be used
without the try block.

In the example, we are trying to divide a number by 0. Here, this code generates an exception.

To handle the exception, we have put the code, 5 / 0 inside the try block. Now when an exception
occurs, the rest of the code inside the try block is skipped.

The catch block catches the exception and statements inside the catch block is executed.

If none of the statements in the try block generates an exception, the catch block is skipped.

2. Java finally block

In Java, the finally block is always executed no matter whether there is an exception or not.

The finally block is optional. And, for each try block, there can be only one finally block.

The basic syntax of finally block is:


try {
//code
}
catch (ExceptionType1 e1) {
// catch block
}
finally {
// finally block always executes
}

If an exception occurs, the finally block is executed after the try...catch block. Otherwise, it is
executed after the try block. For each try block, there can be only one finally block.

In the above example, we are dividing a number by 0 inside the try block. Here, this code
generates an ArithmeticException.

The exception is caught by the catch block. And, then the finally block is executed.

Note: It is a good practice to use the finally block. It is because it can include important cleanup
codes like,

 code that might be accidentally skipped by return, continue or break


 closing a file or connection

3. Java throw and throws keyword

The Java throw keyword is used to explicitly throw a single exception.

When we throw an exception, the flow of the program moves from the try block to the catch
block.

You might also like