Professional Documents
Culture Documents
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");
}
}
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.
Here, 4! is pronounced as "4 factorial", it is also called "4 bang" or "4 shriek".
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.
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:
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.
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.
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?
By string literal
By new keyword
String Literal
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";
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.
{}
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,
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.
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
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
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).
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
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.
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.
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
interface Language {
public void getType();
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.
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;
}
}
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:
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).
try...catch block
finally block
throw and throws keyword
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.
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.
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,
When we throw an exception, the flow of the program moves from the try block to the catch
block.