Advanced Java Programming Practical File
Advanced Java Programming Practical File
– 1
What is Java?
Java is a programming language and a platform. Java is a high level, robust, object-oriented
and secure programming language. Java was developed by Sun Microsystems (which is now
the subsidiary of Oracle) in the year 1995. James Gosling is known as the father of Java.
Before Java, its name was Oak. Since Oak was already a registered company, so James
Gosling and his team changed the name from Oak to Java.
Java SE serves as the foundation for all Java platforms, providing the core functionality of the
Java programming language. It encompasses a comprehensive set of APIs (Application
Programming Interfaces), libraries, and tools that developers leverage to create a wide range
of applications, from simple desktop utilities to complex enterprise systems.
At its core, Java SE defines the fundamental constructs of the Java language, including data
types, control flow statements, and object-oriented programming features such as classes,
interfaces, and inheritance. These language features enable developers to write code that is
readable, maintainable, and scalable.
In addition to language features, Java SE includes a rich collection of standard libraries that
provide functionality for common tasks such as input/output operations, networking, file
handling, concurrency, and collections manipulation. These libraries abstract away low-level
details and provide high-level APIs that simplify development and improve productivity.
Java SE also includes a robust runtime environment, known as the Java Virtual Machine
(JVM), which enables Java applications to run on any platform that supports Java. The JVM
provides features such as memory management, garbage collection, and bytecode
interpretation, ensuring that Java programs execute efficiently and reliably across different
operating systems and hardware architectures.
One of the key strengths of Java SE is its platform independence. Java programs are compiled
into platform-independent bytecode, which can be executed on any device that has a
compatible JVM installed. This "write once, run anywhere" capability has made Java SE a
popular choice for developing cross-platform applications.
Java SE finds widespread use in various domains, including desktop application development,
web development, server-side programming, and scientific computing. Developers use Java
1
SE to build graphical user interfaces (GUIs), web servers, middleware components, database
applications, and more.
Servlets and JSPs are used for developing web applications, providing a framework for
handling HTTP requests, generating dynamic web content, and managing user sessions. EJBs
(Enterprise JavaBeans) are components that encapsulate business logic and provide services
such as transaction management, security, and concurrency control.
JPA (Java Persistence API) is a framework for interacting with relational databases, allowing
developers to map Java objects to database tables and perform database operations using
object-oriented programming techniques. JMS (Java Message Service) provides a standard API
for building messaging applications, enabling communication between distributed components
using message queues and topics.
Java EE also includes features for security, such as authentication, authorization, and
encryption, to ensure the confidentiality, integrity, and availability of enterprise applications.
It provides mechanisms for managing user identities, securing communication channels, and
enforcing access control policies.
Another important aspect of Java EE is its support for scalability and high availability. It offers
features such as clustering, load balancing, and failover, allowing applications to scale
horizontally across multiple servers and handle large volumes of traffic with minimal
downtime.
Overall, Java EE provides a comprehensive platform for building robust, scalable, and secure
enterprise applications. Its rich set of APIs, specifications, and runtime environments enable
developers to tackle the challenges of enterprise computing and deliver high-quality software
solutions that meet the needs of modern businesses.
2
Java ME applications are typically deployed on devices with constrained resources, where
traditional Java SE or Java EE environments may be impractical due to their higher resource
requirements. Java ME applications are often written in Java but may also include native code
components for improved performance or access to device-specific features.
One of the key features of Java ME is its support for device diversity. It provides a set of APIs
that abstract away the differences between different types of devices, allowing developers to
write code that can run on a wide range of hardware platforms without modification. This
enables the development of cross-platform applications that can reach a larger audience of
users.
Java ME includes APIs for user interface development, networking, sensor data processing,
and device interaction, enabling developers to create a variety of applications, including mobile
games, utilities, and IoT applications. It also includes features for security, such as sandboxing
and code signing, to protect against malicious code execution and unauthorized access to
device resources.
Java ME applications are typically packaged as MIDlets (Mobile Information Device Profile
applications) and deployed to devices using over-the-air provisioning or side-loading. Once
installed, MIDlets run within the Java ME runtime environment, which provides features such
as memory management, garbage collection, and bytecode interpretation.
4. JavaFX:
JavaFX is a platform for building rich client applications with modern user interfaces and
advanced multimedia capabilities. It provides a set of high-level APIs for creating interactive
graphics, animations, and media content, making it ideal for developing applications with a
visually appealing and engaging user experience.
JavaFX applications can run on desktop computers, mobile devices, and web browsers, thanks
to its cross-platform support and integration with Java SE and Java EE. JavaFX leverages
hardware-accelerated graphics and media engines to deliver high-performance rendering of
graphical and multimedia content, enabling developers to create applications with smooth
animations, responsive user interfaces, and immersive visual effects.
One of the key features of JavaFX is its support for modern UI design paradigms, such as CSS
styling, FXML for declarative UI layout, and scene graph-based rendering. This allows
developers to create visually rich and expressive user interfaces that are consistent with modern
design trends and user expectations.
JavaFX includes a comprehensive set of APIs for creating UI components, handling user input,
managing application state, and integrating with backend services and data sources. It provides
support for standard UI controls, such as buttons, text fields, and lists, as well as advanced
features like charts, tables, and 3D graphics. JavaFX applications can be deployed as
standalone executables, web applications, or applets, making them accessible to users across
different platforms and environments. JavaFX applications can also be packaged and
distributed using standard Java deployment mechanisms, such as JAR files and Java Web Start.
3
Experiment No – 2
Compiler: A compiler interprets human-readable code into machine-specific code that can
be executed on different operating systems like Linux, Windows, or Mac OS. Most
IDEs usually come with built-in compilers for the language it supports.
Debugger: A tool that can assist developers to test and debug their applications and
graphically point out the locations of bugs or errors if any.
Build-in Terminal: Terminal is a text-based interface that can be used for interacting with
the machine’s operating system. Developers can directly run the scripts or commands within
an IDE with a built-in terminal/console.
Version Control: Version control helps bring clarity to the development of the
software. Some IDEs also support version control tools like Git, through which a user can
track and manage the changes to the software code.
Code snippets: IDEs support code snippets that are usually used to accomplish a single task
and can also reduce redundant work to some great extent.
Extensions and Plugins: Extensions and Plugins are used to extend the functionality of the
IDEs with respect to specific programming languages.
Code navigation: IDEs come with tools like code folding, class and method navigation, and
refactoring tools that make it simple to go through and analyse code.
4
Types Of Java IDEs
Standard IDEs:
Standard Integrated Development Environments (IDEs) like Eclipse, IntelliJ IDEA, and
NetBeans are robust platforms that offer a comprehensive suite of tools for Java development.
Eclipse, for instance, boasts a powerful code editor with features like syntax highlighting,
code completion, and refactoring tools, enhancing developers' productivity and code quality.
It integrates seamlessly with various build systems and version control tools, facilitating
collaborative software development. Similarly, IntelliJ IDEA provides intelligent code
assistance, advanced debugging capabilities, and seamless integration with popular
frameworks and libraries, streamlining the development process. NetBeans offers a user-
friendly interface with a wide range of plugins and extensions, catering to diverse
development needs. Standard IDEs are favoured by professional developers and enterprises
for their extensive feature sets, flexibility, and support for complex projects.
Lightweight IDEs:
Lightweight IDEs, such as JDeveloper, BlueJ, and JCreator, offer a simpler and more focused
approach to Java development. These IDEs are designed to be lightweight in terms of
resource consumption while still providing essential features for coding, compiling, and
running Java applications. BlueJ, for example, is specifically tailored for introductory
programming courses, featuring a clean and intuitive interface that helps students grasp
fundamental concepts effectively. JCreator offers a minimalistic yet powerful environment
for Java development, catering to developers who prefer a streamlined workflow. While
lacking the extensive feature sets of standard IDEs, lightweight IDEs excel in simplicity,
speed, and ease of use, making them suitable for small to medium-sized projects or
developers seeking a more minimalist development environment.
Web-based IDEs:
Text Editors:
Text editors like Sublime Text, Atom, and Visual Studio Code offer lightweight yet powerful
environments for editing code. While lacking the extensive feature sets of full-fledged IDEs,
5
text editors excel in simplicity, speed, and customization options. Sublime Text, for example,
provides a clean and minimalist interface with powerful editing capabilities, including multi-
caret editing, syntax highlighting, and plugin support. Atom, developed by GitHub, offers a
modern and customizable interface with built-in Git integration and a vast library of
community-created packages for extending functionality. Visual Studio Code, a highly
popular text editor from Microsoft, combines the simplicity of a text editor with the power
of an IDE, offering features like IntelliSense code completion, debugging, and built-in
terminal support. Text editors are favoured by developers who prefer lightweight tools,
minimal distractions, and flexibility in configuring their development environment. They are
widely used across various programming languages and platforms for tasks ranging from
quick code edits to full-scale software development projects.
Educational IDEs:
6
Experiment No - 3
7
Java Development with Eclipse IDE
While Eclipse supports multiple programming languages, it is particularly renowned for its
robust support for Java development. Eclipse offers a comprehensive suite of tools and features
tailored to Java developers, making it the IDE of choice for many Java projects. Some of the
key features for Java development in Eclipse include:
1. Java Compiler and Runtime Environment: Eclipse includes a built-in Java compiler and
runtime environment, allowing developers to compile and run Java applications directly within
the IDE. It supports the latest versions of the Java language and platform, ensuring
compatibility with modern Java projects.
2. Code Assistance: Eclipse provides advanced code assistance features for Java development,
including intelligent code completion, quick fixes, and code templates. These features help
developers write code faster and with fewer errors by providing context-aware suggestions and
automating repetitive tasks.
3. Integrated Debugger: Eclipse's integrated debugger offers powerful debugging capabilities
for Java applications. Developers can set breakpoints, step through code, inspect variables, and
analyse program behaviour in real-time, facilitating the debugging process and accelerating
bug fixes.
4. Refactoring Tools: Eclipse includes a set of robust refactoring tools specifically designed
for Java development. Developers can refactor their Java code with confidence, knowing that
Eclipse will automatically update references and ensure the integrity of the codebase.
5. JUnit Integration: Eclipse seamlessly integrates with JUnit, the de facto standard for unit
testing in Java. Developers can create, run, and analyse JUnit tests directly within the IDE,
making it easy to adopt test-driven development (TDD) practices and ensure the quality of their
Java code.
6. Maven and Gradle Support: Eclipse offers built-in support for popular build tools like
Maven and Gradle, simplifying dependency management and project configuration for Java
developers. It provides features like automatic project setup, dependency resolution, and build
automation, streamlining the build process.
7. Java EE Development: Eclipse provides extensive support for Java EE (Enterprise Edition)
development, allowing developers to build robust and scalable enterprise applications. It
includes tools for developing Servlets, JSPs, EJBs, and other Java EE components, as well as
integration with application servers like Apache Tomcat and WildFly.
8
2. Projects: Projects are the fundamental units of organization within Eclipse. Each project
represents a collection of files and resources related to a specific software development task or
application. Projects can contain source code, configuration files, libraries, and other assets
required for development.
3. Editors: Editors are the primary interface for viewing and editing files within Eclipse.
Eclipse provides a variety of editors tailored to different file types, including source code files,
XML documents, text files, and more. Editors offer features like syntax highlighting, code
completion, and refactoring tools to enhance productivity.
4. Views: Views are modular components that provide supplementary functionality within
Eclipse. Examples of views include the Project Explorer, Outline view, Problems view, and
Console view. Views display information, allow navigation, and provide access to various tools
and features of the IDE.
5. Perspectives: Perspectives define the layout and configuration of the Eclipse IDE for
specific tasks or roles. Each perspective consists of a set of views, editors, and toolbars arranged
to optimize productivity for a particular workflow. For example, the Java perspective is tailored
for Java development, while the Debug perspective is optimized for debugging activities.
6. Menu Bar and Toolbars: Eclipse includes a menu bar and toolbars that provide access to
various commands and functions. The menu bar contains top-level menus for actions like file
management, editing, navigation, and project configuration. Toolbars offer quick access to
frequently used commands and features, such as running/debugging applications, saving files,
and searching.
7. Plug-ins and Extensions: Eclipse's extensible architecture allows developers to enhance its
functionality through plug-ins and extensions. Plug-ins are modular components that extend
the capabilities of Eclipse by adding new features, tools, and integrations. Eclipse Marketplace
provides a centralized repository for discovering and installing a wide range of plug-ins to
customize and extend the IDE.
8. Preferences: Preferences allow users to customize various aspects of the Eclipse IDE
according to their preferences and requirements. Preferences cover a wide range of settings,
including editor preferences, project-specific settings, key bindings, and code formatting
options. Users can access and modify preferences through the Preferences dialog, accessible
from the Window menu.
9. Debugger: Eclipse includes a powerful built-in debugger for inspecting and debugging
applications. The debugger allows developers to set breakpoints, step through code, inspect
variables, and analyse program execution. It provides comprehensive debugging features for
various programming languages supported by Eclipse, including Java, C/C++, and PHP.
10. Task Management: Eclipse provides tools for managing tasks, issues, and to-do items
within the IDE. Developers can create, track, and prioritize tasks associated with their projects,
allowing for efficient project management and collaboration. Task management features
include task repositories, task lists, and integration with issue tracking systems like Bugzilla
and JIRA.
9
Experiment No – 4
10
Step 4) Install Eclipse.
11
Step 6) Click on “Eclipse IDE for Java Developers”
12
Step 8) Click on “LAUNCH” button.
13
Step 10) Click on “Create a new Java project” link
14
Step 12) Create Java Package.
1. Goto “src”.
2. Click on “New”.
3. Click on “Package”.
15
Step 14) Creating Java Class
16
Helloword.java file will be created as shown below:
17
Experiment No – 5
Program:
import java.lang.Thread;
18
}
class ThirdThread extends Thread {
public void run() {
for (int i = 0; i < 4; i++) {
System.out.println(i);
}
System.out.println("Third Thread Finished");
}
}
class MultiThread {
public static void main(String[] args) {
FirstThread a1 = new FirstThread();
SecondThread b1 = new SecondThread();
ThirdThread c1 = new ThirdThread();
a1.start();
b1.start();
c1.start();
}
}
Output:
19
Experiment No – 6
Program:
import java.awt.Graphics;
import java.applet.Applet;
Output:
20
Experiment No – 7
Program:
21
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
public class PersonDemo {
public static void main(String[] args) {
Person person1 = new Person();
person1.setName("John Doe");
person1.setAge(30);
System.out.println("Name: " + person1.getName());
System.out.println("Age: " + person1.getAge());
Person person2 = new Person("Jane Smith", 25);
System.out.println(person2);
}
}
Output:
22
Experiment No – 8
Aim: Write a Java socket program where client sends a text and server receives
and prints it.
Program:
File: MyServer.java
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(6666);
Socket s = ss.accept();
DataInputStream dis = new DataInputStream(s.getInputStream());
String str = dis.readUTF();
System.out.println("message=" + str);
ss.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
File: MyClient.java
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
23
try {
Socket s = new Socket("localhost", 6666);
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
Output:
24
Experiment No – 9
Program:
index.html
Servlet1.java
25
Servlet2.java
26
Output:
27
28
Experiment No – 10
Program:
newindex.html
validate.java
29
Output:
30
Experiment No – 11
Aim: Write a Java program to insert data into a table using JSP.
Program:
insert_form.jsp
InsertServlet.java
31
success.jsp
32
error.jsp
Output:
33
Experiment N– 12
Program:
form.jsp
LoginServlet.java
34
Output:
35
Experiment – 13
Program:
import java.io.FileOutputStream;
public class CreateJSP {
public static void main(String[] args) throws Exception {
String htmlContent = "<!DOCTYPE html>\n" +
"<html>\n" +
"<head>\n" +
" <title>My JSP Page</title>\n" +
"</head>\n" +
"<body>\n" +
" <h1>Welcome to JSP!</h1>\n" +
" <p>This is static content.</p>\n" +
" <p>This is <%= out.println(\"dynamic content\"); %>.</p>\n" +
"</body>\n" +
"</html>";
String jspContent = htmlContent;
FileOutputStream out = new FileOutputStream("index.jsp");
out.write(jspContent.getBytes());
out.close();
System.out.println("JSP file created successfully!");
}
}
Output:
36
37