0% found this document useful (0 votes)
3 views46 pages

OOPS With Java Lab File

This document serves as a manual for learning Object-Oriented Programming using Java, targeted at 4th Semester Computer Science and Engineering students. It covers the basics of Java, programming principles, laboratory practices, course objectives, outcomes, and a list of experiments to be performed. Additionally, it includes guidelines for lab conduct, program-specific outcomes, and the history and features of Java.

Uploaded by

gurkeeratbambra
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views46 pages

OOPS With Java Lab File

This document serves as a manual for learning Object-Oriented Programming using Java, targeted at 4th Semester Computer Science and Engineering students. It covers the basics of Java, programming principles, laboratory practices, course objectives, outcomes, and a list of experiments to be performed. Additionally, it includes guidelines for lab conduct, program-specific outcomes, and the history and features of Java.

Uploaded by

gurkeeratbambra
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Object Oriented Programming

(with JAVA)

(Semester 4th)

Prepared By:
Mr. Rupesh Mude
Assist. Professor
Department Of CSE

Department of Computer Science and Engineering


PREFACE

This manual will introduce you to the Java programming language. It’s aimed at beginning programmers, but
even if you’ve written programs before and just want to add Java to your list of languages, It will get you
started.

Java is a powerful high-level, object-oriented programming language created by James Gosling. It has simple
easy-to-use syntax, making it the perfect language for someone trying to learn computer programming for the
first time.

This practical manual will be helpful for students of 4th Semester Computer Science and Engineering streams
for better understanding the course from the point of view of applied aspects.

This manual is designed for those readers who wish to start learning to program in an object-
oriented programming language. It has been designed primarily as a first programming text. It is
also suitable for those who already have some experience with another programming language,
and who now wish to move on to an object-oriented one. Indeed, much of the material is based on
courses delivered by the author to students with a wide range of both non-programming and
programming backgrounds. The language we use to teach object-oriented programming is Java.

Department of Computer Science and Engineering


List of DOs & DON’Ts.
DOs
 Do Keep proper discipline in the Labs.

 Do login with your own user id and password.

 Do fill the lab book Properly

 Do Remove your shoes before entering the lab

 Do arrange the chairs properly before leaving

 Do attend the lab on time. Only 5 minute’s relaxations will be given for attendance

 Switch off the supply after performing experiment.

 Maintain silence and proper discipline in the lab.

DON’Ts.
 Don’t open unwanted sites/ program during regular classes.

 Don’t waste paper by taking unwanted printouts.

 Don’t cut/remove cables of the system.

 Don’t install any S/w unwanted data without the permission of lab-incharge.

 Don’t replace any accessories of the system without permission.

 Don’t leave the system ON after the work. Shutdown the system properly

Department of Computer Science and Engineering


PROGRAM SPECIFIC OUTCOMES (PSOs)

A graduate of the Computer Science and Engineering Program will demonstrate:

PSO1:-Ability to understand and comprehend basic skill set of science, mathematics and computer science engineering
to solve problems of computing domain.

PSO2:- : Ability to apply fundamental and advanced programming skills to solve real life problems using algorithm
paradigms. Ability to understand the practices and strategies in software project development.

PSO3:- The ability to apply modern computer languages, environments and platforms with knowledge of operating
system, networking, databases to solve real world and multi-disciplinary problems in creating innovative career paths to
be an entrepreneur, and a zest for higher studies.

Department of Computer Science and Engineering


PROGRAM OUTCOMES (POs)
Engineering Graduates will be able to:
1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex
engineering problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural sciences, and
engineering sciences.
3. Design / development of solutions: Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with appropriate consideration for the
public health and safety, and the cultural, societal, and environmental considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and research methods
including design of experiments, analysis and interpretation of data, and synthesis of the information to
provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with an
understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal,
health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice
7. Environment and sustainability: Understand the impact of the professional engineering solutions in
societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the
engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in diverse
teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and write effective
reports and design documentation, make effective presentations, and give and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and leader in
a team, to manage projects and in multi disciplinary environments.
12. Life- long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.

Department of Computer Science and Engineering


COURSE OBJECTIVES:

1. To be able to introduce core programming basics and various Operators of Java programming
language.
2. To demonstrate about Java like Class, Object, Constructor and Polymorphism
3. To understand about Functions, Modules and Regular Expressions in Java Programming

COURSE OUTCOMES:
1. Use an integrated development environment to write, compile, run, and test simple object-oriented
Java programs.
2. Implement Object Oriented programming concept using basic syntaxes of control Structures,
strings and function for developing skills of logic building activity.
3. Identify classes, objects, members of a class and the relationships among them needed for a finding
the solution to specific problem
4. Demonstrates how to achieve reusability using inheritance, interfaces and packages and describes
faster application development can be achieved.
5. Demonstrate understanding and use of different exception handling mechanisms and concept of
multithreading for robust faster and efficient application development

Department of Computer Science and Engineering


Chhattisgarh Swami Vivekananda Technical University, Bhilai (C.G.)
Program / Semester: [Link] (IV) Branch: Computer Science &Engineering
Subject: Object Oriented Programming (with JAVA) Laboratory
Course Code: B022422(022)
Total / Minimum-Pass Marks (End Semester Exam): 40 / 20 L: 0 T: 0 P: 2 Credit(s):
List of Experiments:
(At least Ten experiments are to be performed by each student)
1. Write a program in Java to read from console employee details of 5 employees with following details:
Name of employee, Department, Age, Salary. Print the details of every employee.
2. Write a program to show the use 'this' keyword to call the default and parameterized constructors.
3. Write a program in Java to display the count of number of objects created and finalized. Provide unique
IDs to every object while creation and display the same ID during finalization.
4. 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.
5. 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.
6. Write a program to show inbuilt and user defined: checked and unchecked exceptions.
7. Write a program to show the use of various member methods of String class.
8. Create two threads T1 and T2. The thread T1 should print numbers from 1 to 10 and thread T2 prints
characters from A to J. Ensure that T2 starts first and T1 should only start when T2 finishes. (Note: use
join())
9. Demonstrate using a Java program, how DEADLOCK occurs between threads and also give solution
program.
10. Write a program to merge the contents of text files [Link] and [Link] into [Link]. The contents of [Link]
should appear first and then [Link] in the destination file [Link].
11. Develop a GUI application that gives text equivalent of any numeric value entered by the user ranging
from 0 to 9.
12. Develop a GUI application to implement Date of Birth validator. The DOB should only be in the form
"dd/mm/yyyy". Use customized exception handling method as the validator.
13. Develop an Applet to insert username and password into a MySQL (or any) database. 14. Develop an
Applet to display all the usernames and passwords present in a MySQL (or any) database.
15. Develop two applications in Java using Sockets to communicate with each other using text messages.
16. Develop two applications in Java using RMI to communicate with each other using text messages.
17. Develop a Java program to demonstrate the use of HashSet, TreeSet, ArrayList, LinkedList classes.
18. Develop a Java program to demonstrate the use of Vector, HashMap, TreeMap, Hashtable classes.
19. Develop a Java program to demonstrate the use of generics.
20. Create and run an executable JAR. Laboratory Equipments / Machine Requirements: Windows
operating system, 4GB RAM, 500GB HDD, JDK8 and Netbeans IDE.

Recommended Books:
1. Maurice Naftalin, Philip Wadler, “Java Generics and Collections”, O'Reilly Media, Inc.

Department of Computer Science and Engineering


2. Benjamin J Evans, David Flanagan., “Java in a Nutshell”, O'Reilly Media, Inc.

Department of Computer Science and Engineering


INDEX

S.N. Name of Experiment P.N.


1. Introduction to JAVA, History of java, Principle,
Features, Installation of JAVA.
2. 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.

3. Write a program to show the use 'this' keyword to call


the default and parameterized constructors.

4. 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.

5. 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.

6. Write a program to show inbuilt and user defined:


checked and unchecked exceptions.

Department of Computer Science and Engineering


7. Write a program to show the use of various member
methods of String class.

8. Develop a Java program to demonstrate the use of


HashSet, Tree Set, Array List, LinkedList classes.

9. Develop a Java program to demonstrate the use of


generics.

10. Create and run an executable JAR.

11. A Java program for a Client side and Server side.

Department of Computer Science and Engineering


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 byte code 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 Naught on 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.

Sun Microsystems released the first public implementation as Java 1.0 in 1996. It promised
write once, run anywhere (WORA) functionality, providing no-cost run-times on popular
platforms.

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

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

Department of Computer Science and Engineering


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

JDK 1.0 January 23, 1996

JDK 1.1 February 19, 1997

J2SE 1.2 December 8, 1998

J2SE 1.3 May 8, 2000

J2SE 1.4 February 6, 2002


J2SE 5.0 September 30, 2004

Department of Computer Science and Engineering


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.
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.

Department of Computer Science and Engineering


• 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.

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.
Department of Computer Science and Engineering
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
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.

Department of Computer Science and Engineering


• 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 any more.

• 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.

Department of Computer Science and Engineering


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

Download Java for Windows 10


• Using your preferred web browser, navigate to the Oracle Java
Downloads page.
• On the Downloads page, click the x64 Installer download link under the Windows
category. At the time of writing this article, Java version 17 is the latest long-term
support Java version.

Install Java on Windows 10


After downloading the installation file, proceed with installing Java on your Windows
system.
Follow the steps below:

Step 1: Run the Downloaded File


Double-click the downloaded file to start the installation.

[10]

Department of Computer Science and Engineering


Step 2: Configure the Installation Wizard
After running the installation file, the installation wizard welcome screen appears.
1. Click Next to proceed to the next step.
2. Choose the destination folder for the Java installation files or stick to the
default path. Click Next to proceed.
3. Wait for the wizard to finish the installation process until the
Successfully Installed message appears. Click Close to exit the wizard.

Set Environmental Variables in Java


Set Java environment variables to enable program compiling from any directory.
To do so, follow the steps below:

Step 1: Add Java to System Variables


1. Open the Start menu and search for environment variables.
2. Select the Edit the system environment variables result.
3. In the System Properties window, under the Advanced tab, click
Environment Variables…
4. Under the System variables category, select the Path variable and click Edit
5. Click the New button and enter the path to the Java bin directory
Note: The default path is usually C:\Program Files\Java\jdk-
17.0.1\bin.
6. Click OK to save the changes and exit the variable editing window.

Step 2: Add JAVA_HOME Variable


Some applications require the JAVA_HOME variable. Follow the steps below to
create the variable:
1. In the Environment Variables window, under the System variables
category, click the New… button to create a new variable.
2. Name the variable as JAVA_HOME.
3. In the variable value field, paste the path to your Java jdk directory and click
OK.
4. Confirm the changes by clicking OK in the Environment Variables and
System properties windows.

Department of Computer Science and Engineering


Test the JAVA installation
Run the java -version command in the command prompt to make sure
Java installed
correctly:
Running the java command to see Java version on Windows.
If installed correctly, the command outputs the Java version. Make sure everything
works by writing a simple program and compiling it. Follow the steps below:
Step 1: Write a Test Java Script
1. Open a text editor such as Notepad++ and create a new file.
2. Enter the following lines of code and click Save:

class HelloWorld {
public static void main (String args[]){ [Link]("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:

java [filename]
The output shows that the program runs correctly, displaying the
Hello world! message.

Department of Computer Science and Engineering


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 [Link];
class Employee {
int id;
String name;
float sal;
}

class Main2 {
public static void main(String args[]) {

Scanner sc = new Scanner([Link]);


[Link]("Enter How many
employee:"); int k = [Link]();

Employee emp[] = new Employee[k];

for (int i = 0; i < k; i++) {


emp[i] = new Employee();

[Link]("Enter " + (i + 1) + " Employee

data :"); [Link]("Enter employee id :");


emp[i].id = [Link]();
[Link]("Enter employee
name :"); emp[i].name = [Link]();

Department of Computer Science and Engineering


[Link]("Enter employee
salary :"); emp[i].sal = [Link]();

[Link]("\n\n============ All employee details are


:==========
==\n");

for (int i = 0; i < k; i++) {


[Link]("Employee id name and salary :" + emp[i].id + " " +
emp[i].name + " " + emp[i].sal);

}
}
}

Department of Computer Science and Engineering


Output :-

Department of Computer Science and Engineering


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){
[Link]=roll
no;
[Link]=nam
e; [Link]=fee;
}
void display(){[Link](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);
[Link]();
[Link]();
}
Output :-

Department of Computer Science and Engineering


Calling default constructor from parameterized constructor:

class A{
A(){[Link]("hello
a");} A(int x){

this();
[Link](x
);
}
}
class TestThis5{
public static void main(String
args[]){ A a=new A(10);
}
}

Output
:-

Department of Computer Science and Engineering


Calling parameterized constructor from default constructor:

class A{
A(){
this(5
);
[Link]("hello a");
}
A(int x){
[Link](x
);
}
}
class TestThis6{
public static void main(String
args[]){ A a=new A();
}

}
Output :-

Department of Computer Science and Engineering


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 [Link];
interface Shape{
public double area();
}
class Circle implements Shape{
Scanner s = new Scanner([Link]);
double radius = [Link]();

public double area(){


return 3.14 * radius * radius;
}
}
class Triangle implements Shape{
Scanner sc = new
Scanner([Link]); double height
= [Link](); double base =
[Link]();

public double area(){


return (height * base)/2;
}
}

class InterfaceDemo{

Department of Computer Science and Engineering


public static void main(String args[]){
[Link]("Enter the Value of
Radius="); Circle c = new Circle();
[Link]("Area of circle: " +
[Link]()); [Link]("Enter the Value
of Height="); [Link]("Enter the
Value of Base="); Triangle t = new Triangle();
[Link]("Area of triangle: " +
[Link]());
}
}

Department of Computer Science and Engineering


Output :-

Department of Computer Science and Engineering


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(){[Link]("Hello java");}
}
public class Simple{
public static void main(String args[]){ A obj=new
A(); [Link]([Link]);//Compile Time
Error [Link]();//Compile Time Error
}
}

Role of Private Constructor :


If you make any class constructor private, you cannot create the instance of that
class from outside the class. For example:

class A{
private A(){}//private constructor
void msg(){[Link]("Hello java");}
}
public class Simple{
public static void main(String
args[]){ A obj=new A();//Compile
Time Error
}
}

Department of Computer Science and Engineering


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 :
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
[Link] package
pack; class A{
void
msg(){[Link]("Hello");}
}
//save by
[Link] package
mypack;
Import pack.*;
class B{
public static void main(String
args[]){ A obj = new A();//Compile
Time Error [Link]();//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.

Department of Computer Science and Engineering


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
[Link]
package pack;
public class A{
protected void msg(){[Link]("Hello");}
}

//save by [Link]
package
mypack; import
pack.*; class B
extends A{
public static void main(String
args[]){ B obj = new B();
[Link]();
}
}
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 :

Department of Computer Science and Engineering


//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B{
public static void main(String args[]){ A obj
= new A();
[Link]();
}
}

Output :- Hello

Java Access Modifiers with Method Overriding :


If you are overriding any method, overridden method (i.e. declared in subclass) must not be more
restrictive.

class A{
protected void msg(){[Link]("Hello java");}
}
public class Simple extends A{
void msg(){[Link]("Hello java");}//[Link] public
static void main(String args[]){
Simple obj=new Simple();
[Link]();
}
}

The default modifier is more restrictive than protected. That is why, there is a compile- time error.

Department of Computer Science and Engineering


Experiment - (5)

Write a program to show inbuilt and user defined: checked and unchecked exceptions.

Checked Exception :
import [Link].*; 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:/[Link]");
int k;

/* Method read() of FileInputStream class also throws


* a checked exception: IOException */

while(( k = [Link]() ) != -1)


{ [Link]((char)k);
}
/*The method close() closes the file input stream
* It throws IOException*/
[Link]();
}
}

Output :-

Exception in thread "main" [Link]: Unresolved compilation problems: Unhandled


exception type FileNotFoundException
Unhandled exception type IOException
Unhandled exception type IOException

Unchecked Exceptions :

Department of Computer Science and Engineering


public class Unchecked_Demo {
public static void main(String args[]) { Int
num[] = {1, 2, 3, 4};
[Link](num[5]);
}
}

Output :- Exception in thread "main" [Link]: 5 at


Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)

Department of Computer Science and Engineering


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 ";

[Link]("Char at index 2(third position): " + [Link](2));


[Link]("After Concat: "+ [Link]("-Enjoy-"));
[Link]("Checking equals ignoring case: " +[Link](s1));
[Link]("Checking equals with case: " +[Link](s1)); [Link]("Checking
Length: "+ [Link]()); [Link]("Replace function: "+
[Link]("fun", "easy")); [Link]("SubString of targetString: "+
[Link](8)); [Link]("SubString of targetString: "+
[Link](8, 12)); [Link]("Converting to lower case: "+
[Link]()); [Link]("Converting to upper case: "+
[Link]()); [Link]("Triming string: " + [Link]());
[Link]("searching s1 in targetString: " + [Link](s1));
[Link]("searching s2 in targetString: " + [Link](s2));

char [] charArray = [Link]();


[Link]("Size of char array: " + [Link]);
[Link]("Printing last element of array: " + charArray[3]);
}
}

Department of Computer Science and Engineering


Output :-

Department of Computer Science and Engineering


Experiment - (7)

Develop a Java program to demonstrate the use of HashSet, TreeSet, ArrayList, LinkedList
classes.

Array list :
import [Link].*;
public class ArrayListExample1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
[Link]("Mango");//Adding object in arraylist
[Link]("Apple");
[Link]("Banana");
[Link]("Grapes");
//Printing the arraylist object
[Link](list);
}
}
Output :- Compile by: javac [Link]
Run by: java ArrayListExample1
[Mango, Apple, Banana, Grapes]

Linkedlist :
import [Link].*;
public class LinkedList1{
public static void main(String args[]){ LinkedList<String>
al=new LinkedList<String>(); [Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");

Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}

Output :- Ravi Vijay Ravi Ajay

Department of Computer Science and Engineering


Hashset :
import [Link].*;
class HashSet1{
public static void main(String args[]){
//Creating HashSet and adding elements HashSet<String>
set=new HashSet(); [Link]("One");
[Link]("Two"); [Link]("Three");
[Link]("Four"); [Link]("Five");
Iterator<String> i=[Link]();
while([Link]())
{
[Link]([Link]());
}
}
}
Output :- Five One Four Two
Three

TreeSet :
import [Link].*;
class TreeSet1{
public static void main(String args[]){
//Creating and adding elements TreeSet<String> al=new
TreeSet<String>(); [Link]("Ravi");
[Link]("Vijay");

[Link]("Ravi");
[Link]("Ajay");
//Traversing elements Iterator<String> itr=[Link]();
while([Link]()){ [Link]([Link]());
}
}
}

Output :- Ajay
Ravi
Vijay

Department of Computer Science and Engineering


Experiment - (8)

Develop a Java program to demonstrate the use of generics.

public class TestGenerics4{


public static < E > void printArray(E[] elements) { for ( E element :
elements){ [Link](element );
} [Link]();
}
public static void main( String args[] ) { Integer[] intArray = {
10, 20, 30, 40, 50 };
Character[] charArray = { 'J', 'A', 'V', 'A', 'T','P','O','I','N','T' };

[Link]( "Printing Integer Array" );


printArray( intArray );
[Link]( "Printing Character Array" );
printArray( charArray );
}
}
Output :- Printing Integer Array
10
20
30
40
50

Printing Character Array


JAVAT
PO
I

Department of Computer Science and Engineering


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:
[Link]
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 [Link] [Link] [Link]
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.

[Link]
import [Link].*;
public class First{ First(){
JFrame f=new JFrame();

JButton b=new JButton("click");


[Link](130,100,100, 40);
Department of Computer Science and Engineering
[Link](b);

[Link](300,400);
[Link](null);
[Link](true);

[Link](JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new First();
}
}

Department of Computer Science and Engineering


Experiment - (10)

A Java program for a Client side and Server side.

Client side
// A Java program for a Client import
[Link].*;
import [Link].*;

public class Client


{
// initialize socket and input output streams private Socket
socket = null;
private DataInputStream input = null;
private DataOutputStream out = null;

// constructor to put ip address and port public


Client(String address, int port)
{
// establish a connection
try
{
socket = new Socket(address, port);
[Link]("Connected");

// takes input from terminal


input = new DataInputStream([Link]);

// sends output to the socket


out = new DataOutputStream([Link]());
}
catch(UnknownHostException u)
{
[Link](u);
}
catch(IOException i)

Department of Computer Science and Engineering


{
[Link](i);

// string to read message from input


String line = "";

// keep reading until "Over" is input while


(![Link]("Over"))
{
try
{
line = [Link]();
[Link](line);
}
catch(IOException i)
{
[Link](i);
}
}

// close the connection


try
{
[Link]();
[Link]();
[Link]();
}
catch(IOException i)
{
[Link](i);
}
}

public static void main(String args[])


{
Client client = new Client("[Link]", 5000);
}

Department of Computer Science and Engineering


}

Server side
// A Java program for a Server import [Link].*;
import [Link].*;

public class Server


{
//initialize socket and input stream private Socket socket
= null; private ServerSocket server = null; private
DataInputStream in = null;

// constructor with port public Server(int


port)
{
// starts server and waits for a connection try
{
server = new ServerSocket(port);
[Link]("Server started");

[Link]("Waiting for a client ...");

socket = [Link](); [Link]("Client


accepted");

// takes input from the client socket in = new


DataInputStream(
new BufferedInputStream([Link]())); String line = "";

// reads message from client until "Over" is sent while


(![Link]("Over"))
{
try
{
line = [Link]();

[Link](line);

}
Department of Computer Science and Engineering
catch(IOException i)
{
[Link](i);
}
}
[Link]("Closing connection");

// close connection
[Link]();
[Link]();
}
catch(IOException i)
{
[Link](i);
}
}

public static void main(String args[])


{
Server server = new Server(5000);
}
}

Output :-

To run on Terminal or Command Prompt


Open two windows one for Server and another for Client
1. First run the Server application as ,
$ java Server Server started
Waiting for a client …
2. Then run the Client application on another terminal as,
$ java Client
It will show – Connected and the server accepts the client and shows, Client accepted

3. Then you can start typing messages in the Client window. Here is a sample input to the Client
Hello
I made my first socket connection
Over
Which the Server simultaneously receives and shows, Hello
Department of Computer Science and Engineering
I made my first socket connection
Over
Closing connection

Department of Computer Science and Engineering

You might also like