Java Lab Record GT
Java Lab Record GT
Bilaspur, (C.G.)
Session :- 2021-22
Semester :- 4th
Lab Report
Subject :- Object Oriented Programming
(with JAVA) Laboratory
Submitted To - Submitted By -
Ms. Sonia Wadhwa Name- Gaurav Thawait
Branch – CSE
Roll No.- 300702220014
INDEX
[1]
9. Develop a Java program to demonstrate the use of 31
generics.
[2]
Introduction to JAVA
Java is a high-level, class-based, object-oriented programming language
that is designed to have as few implementation dependencies as
possible. It is a general-purpose programming language intended to let
programmers write once, run anywhere (WORA), meaning that
compiled Java code can run on all platforms that support Java without
the need to recompile. Java applications are typically compiled to
bytecode that can run on any Java virtual machine (JVM) regardless of
the underlying computer architecture. The syntax of Java is similar to C
and C++, but has fewer low-level facilities than either of them. The Java
runtime provides dynamic capabilities (such as reflection and runtime
code modification) that are typically not available in traditional compiled
languages. As of 2019, Java was one of the most popular programming
languages in use according to GitHub.
History of JAVA
James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java
language project in June 1991. Java was originally designed for
interactive television, but it was too advanced for the digital cable
television industry at the time. The language was initially called Oak after
an oak tree that stood outside Gosling’s office. Later the project went by
the name Green and was finally renamed Java.
The Java 1.0 compiler was re-written in Java by Arthur van Hoff to
comply strictly with the Java 1.0 language specification. With the advent
of Java 2 (released initially as J2SE 1.2 in December 1998 – 1999), new
versions had multiple configurations built for different types of
[3]
platforms. J2EE included technologies and APIs for enterprise
applications typically run in server environments, while J2ME featured
APIs optimized for mobile applications. The desktop version was
renamed J2SE. In 2006, for marketing purposes, Sun renamed new J2
versions as Java EE, Java ME, and Java SE, respectively
Principles
There were five primary goals in the creation of the Java language:
• It must be simple, object-oriented, and familiar.
• It must be robust and secure.
• It must be architecture-neutral and portable.
• It must execute with high performance.
• It must be interpreted, threaded, and dynamic.
Versions
As of September 2021, Java 8, 11 and 17 are supported as Long-Term
Support (LTS) versions. Major release versions of Java, along with their
release dates:
Version Date
JDK 1995
[4]
Java SE 6 December 11, 2006
Features of JAVA
Following are the notable features of java :
Object Oriented
Java is an object-oriented programming language. Everything in Java is
an object. Object-oriented means we organize our software as a
combination of different types of objects that incorporate both data and
behavior.
Object-oriented programming (OOPs) is a methodology that simplifies
software development and maintenance by providing some rules.
[5]
Basic concepts of OOPs are:
• Object: Any entity that has state and behavior is known as an
object. For example, a chair, pen, table, keyboard, bike, etc. It can
be physical or logical. An 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.
• Class: 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.
• Inheritance: When one object acquires all the properties and
behaviors of a parent object, it is known as inheritance. It provides
code reusability. It is used to achieve runtime polymorphism.
• Polymorphism: If one task is performed in different ways, it is
known as polymorphism. For example: to convince the customer
differently, to draw something, for example, shape, triangle,
rectangle, etc. In Java, we use method overloading and method
overriding to achieve polymorphism. Another example can be to
speak something; for example, a cat speaks meow, dog barks woof,
etc.
• Abstraction: Hiding internal details and showing functionality is
known as abstraction. For example, phone call, we don't know the
internal processing.
• Encapsulation: Binding (or wrapping) code and data together into
a single unit are known as encapsulation. For example, a capsule, it
is wrapped with different medicines. A java class is the example of
encapsulation. Java bean is the fully encapsulated class because all
the data members are private here.
[6]
Platform Independent
Java is platform independent because it is different from other
languages like C, C++, etc. which are compiled into platform specific
machines while Java is a write once, run anywhere language. A platform
is the hardware or software environment in which a program runs.
There are two types of platforms software-based and hardware-based.
Java provides a software-based platform.
The Java platform differs from most other platforms in the sense that it
is a software-based platform that runs on top of other hardware-based
platforms. It has two components:
• Runtime Environment
• API (Application Programming Interface)
Java code can be executed on multiple platforms, for example,
Windows, Linux, Sun Solaris, Mac/OS, etc. Java code is compiled by the
compiler and converted into bytecode. This bytecode is a platform-
independent code because it can be run on multiple platforms, i.e.,
Write Once and Run Anywhere (WORA).
Simple
Java is designed to be easy to learn. If you understand the basic concept
of OOP Java, it would be easy to master.
Secure
Java is best known for its security. With Java, we can develop virus-free
systems. Java is secured because:
• No explicit pointer
• Java Programs run inside a virtual machine sandbox
• Classloader: Classloader in Java is a part of the Java Runtime
Environment (JRE) which is used to load Java classes into the Java
Virtual Machine dynamically. It adds security by separating the
[7]
package for the classes of the local file system from those that are
imported from network sources.
• Bytecode Verifier: It checks the code fragments for illegal code that
can violate access rights to objects.
• Security Manager: It determines what resources a class can access
such as reading and writing to the local disk.
Java language provides these securities by default. Some security can
also be provided by an application developer explicitly through SSL,
JAAS, Cryptography, etc.
Architecture-neutral
Java is architecture neutral because there are no implementation
dependent features, for example, the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit
architecture and 4 bytes of memory for 64-bit architecture. However, it
occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.
Portable
Being architecture-neutral and having no implementation dependent
aspects of the specification makes Java portable. The compiler in Java is
written in ANSI C with a clean portability boundary, which is a POSIX
subset.
Robust
The English mining of Robust is strong. Java is robust because:
• It uses strong memory management.
• There is a lack of pointers that avoids security problems.
• Java provides automatic garbage collection which runs on the Java
Virtual Machine to get rid of objects which are not being used by a
Java application anymore.
[8]
• There are exception handling and the type checking mechanism in
Java. All these points make Java robust.
Multithreaded
With Java's multithreaded feature it is possible to write programs that
can perform many tasks simultaneously. This design feature allows the
developers to construct interactive applications that can run smoothly.
Interpreted
Java byte code is translated on the fly to native machine instructions and
is not stored anywhere. The development process is more rapid and
analytical since the linking is an incremental and light-weight process.
High Performance
Java is faster than other traditional interpreted programming languages
because Java bytecode is "close" to native code. It is still a little bit
slower than a compiled language (e.g., C++). Java is an interpreted
language that is why it is slower than compiled languages, e.g., C, C++,
etc.
Distributed
Java is distributed because it facilitates users to create distributed
applications in Java. RMI and EJB are used for creating distributed
applications. This feature of Java makes us able to access files by calling
the methods from any machine on the internet.
Dynamic
Java is considered to be more dynamic than C or C++ 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 accesses to objects at run-time.
[9]
Installation of Java
JavaFX Environment
We have to set the JavaFX environment on the system in order to run
JavaFX Applications. All the versions of Java after JDK 1.8, supports
JavaFX therefore we must have JDK 1.8 or later installed on our system.
There are various IDE such as Net-beans or Eclipse also supports JavaFX
Library. In this chapter, we will discuss the various ways of executing
JavaFX applications.
Install Java
Verify that it is already installed or not
• Open a command prompt by typing cmd in the search bar and press
Enter.
• Run the following command:
java -version
class HelloWorld {
public static void main (String args[]){
System.out.println("Hello world!");
}
}
3. Name the file HelloWorld same as class and save it as a Java source
file (*.java).
Step 2: Compile the Test Java Script
1. In the command prompt, change the directory to the file's location
and use the following syntax to compile the program
javac [filename]
2. Run the program with the following syntax:
[12]
java [filename]
The output shows that the program runs correctly, displaying the
Hello world! message.
[13]
Experiment - (1)
Write a program in Java to read from console employee details with following
details: Employee Id, Name of employee, Salary. Print the details of every
employee.
import java.util.Scanner;
class Employee {
int id;
String name;
float sal;
}
class Main2 {
public static void main(String args[]) {
[14]
for (int i = 0; i < k; i++) {
System.out.println("Employee id name and salary :" + emp[i].id + " " +
emp[i].name + " " + emp[i].sal);
}
}
}
Output :-
[15]
Experiment - (2)
Write a program to show the use 'this' keyword to call the default and
parameterized constructors.
class Student {
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}
Output :-
class A{
A(){System.out.println("hello a");}
A(int x){
[16]
this();
System.out.println(x);
}
}
class TestThis5{
public static void main(String args[]){
A a=new A(10);
}
}
Output :-
class A{
A(){
this(5);
System.out.println("hello a");
}
A(int x){
System.out.println(x);
}
}
class TestThis6{
public static void main(String args[]){
A a=new A();
}
}
Output :-
[17]
Experiment - (3)
Create a Shape Interface which has a member method area(). Derive two
subclasses Circle and Triangle from it. Using reference of Shape class fill the
required members in Circle and Triangle also display the area of Circle and
Triangle. Take input from user while filling data members.
import java.util.Scanner;
interface Shape{
public double area();
}
class Circle implements Shape{
Scanner s = new Scanner(System.in);
double radius = s.nextDouble();
class InterfaceDemo{
public static void main(String args[]){
System.out.println("Enter the Value of Radius=");
Circle c = new Circle();
System.out.println("Area of circle: " + c.area());
System.out.println("Enter the Value of Height=");
System.out.println("Enter the Value of Base=");
Triangle t = new Triangle();
System.out.println("Area of triangle: " + t.area());
[18]
}
}
Output :-
[19]
Experiment - (4)
Write a program to demonstrate the effect of access modifiers (default,
protected, public and private) on members with and without inheritance
within a package and outside a package.
Private class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
2) Default :
If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package. It cannot be accessed from outside the package. It
provides more accessibility than private. But, it is more restrictive than protected, and
public.
Example of default access modifier :
[20]
In this example, we have created two packages pack and mypack. We are accessing the
A class from outside its package, since A class is not public, so it cannot be accessed
from outside the package.
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
Import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot
be accessed from outside the package.
3) Protected :
The protected access modifier is accessible within package and outside the package
but through inheritance only.
The protected access modifier can be applied on the data member, method and
constructor. It can't be applied on the class.
It provides more accessibility than the default modifer.
Example of protected access modifier :
In this example, we have created the two packages pack and mypack. The A class of
pack package is public, so can be accessed from outside the package. But msg method
of this package is declared as protected, so it can be accessed from outside the class
only through inheritance.
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
[21]
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output :- Hello
4) Public :
The public access modifier is accessible everywhere. It has the widest scope among all
other modifiers.
Example of public access modifier :
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output :- Hello
[22]
class A{
protected void msg(){System.out.println("Hello java");}
}
public class Simple extends A{
void msg(){System.out.println("Hello java");}//C.T.Error
public static void main(String args[]){
Simple obj=new Simple();
obj.msg();
}
}
The default modifier is more restrictive than protected. That is why, there is a compile-
time error.
[23]
Experiment - (5)
Write a program to show inbuilt and user defined: checked and unchecked
exceptions.
Checked Exception :
import java.io.*;
class Example {
public static void main(String args[])
{
FileInputStream fis = null;
/*This constructor FileInputStream(File filename)
* throws FileNotFoundException which is a checked
* exception */
fis = new FileInputStream("B:/myfile.txt");
int k;
Output :-
[24]
Unchecked Exceptions :
[25]
Experiment - (6)
Write a program to show the use of various member methods of String
class.
class StringMethodsDemo {
public static void main(String[] args) {
String targetString = "Java is fun to learn";
String s1= "JAVA";
String s2= "Java";
String s3 = " Hello Java ";
[26]
Output :-
[27]
Experiment - (7)
Develop a Java program to demonstrate the use of HashSet, TreeSet,
ArrayList, LinkedList classes.
Array list :
import java.util.*;
public class ArrayListExample1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Mango");//Adding object in arraylist
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//Printing the arraylist object
System.out.println(list);
}
}
Output :- Compile by: javac ArrayListExample1.java
Run by: java ArrayListExample1
[Mango, Apple, Banana, Grapes]
Linkedlist :
import java.util.*;
public class LinkedList1{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
[28]
Output :- Ravi
Vijay
Ravi
Ajay
Hashset :
import java.util.*;
class HashSet1{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet();
set.add("One");
set.add("Two");
set.add("Three");
set.add("Four");
set.add("Five");
Iterator<String> i=set.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}
Output :- Five
One
Four
Two
Three
TreeSet :
import java.util.*;
class TreeSet1{
public static void main(String args[]){
//Creating and adding elements
TreeSet<String> al=new TreeSet<String>();
al.add("Ravi");
al.add("Vijay");
[29]
al.add("Ravi");
al.add("Ajay");
//Traversing elements
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output :- Ajay
Ravi
Vijay
[30]
Experiment - (8)
Develop a Java program to demonstrate the use of generics.
[31]
Experiment - (9)
Create and run an executable JAR.
Creating manifest file
To create manifest file, you need to write Main-Class, then colon, then space, then
classname then enter. For example:
myfile.mf
Main-Class: First
Creating executable jar file using jar tool
The jar tool provides many switches, some of them are as follows:
-c creates new archive file
-v generates verbose output. It displays the included or extracted resource on the
standard output.
-m includes manifest information from the given mf file.
-f specifies the archive file name
-x extracts files from the archive file
Now, let's write the code to generated the executable jar using mf file.
You need to write jar then swiches then mf_file then jar_file then .classfile as given
below:
jar -cvmf myfile.mf myjar.jar First.class
It is shown in the image given below:
Now it will create the executable jar file. If you double click on it, it will call the main
method of the First class.
First.java
import javax.swing.*;
public class First{
First(){
JFrame f=new JFrame();
[32]
JButton b=new JButton("click");
b.setBounds(130,100,100, 40);
f.add(b);
f.setSize(300,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new First();
}
}
[33]
Experiment - (10)
A Java program for a Client side and Server side.
Client side
// A Java program for a Client
import java.net.*;
import java.io.*;
[35]
Server side
// A Java program for a Server
import java.net.*;
import java.io.*;
socket = server.accept();
System.out.println("Client accepted");
}
catch(IOException i)
{
System.out.println(i);
}
}
System.out.println("Closing connection");
// close connection
socket.close();
in.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
Output :-
[38]