Sie sind auf Seite 1von 41

A

PRACTICAL TRAINING REPORT

ON

“JAVA”

TAKEN AT:

CENTRE OF ELECTRONIC GOVERNANCE, JAIPUR

SESSION: 2019-2020

GOVERNMENT POLYTECHNIC COLLEGE NEEMRANA

ALWAR

SUBMITTED TO: SUBMITTED BY:

MR. MUKESH GOTHWAL HITESH YADAV

(HEAD OF DEPARTMENT) (CS-III YEAR)

(COMPUTER SCIENCE DEPARTMENT)


CANDIDATE’S DECLARATION

I hereby declare that the work, which is being presented in Practical Training, entitled “ Java”
in partial fulfillment for the award of Degree of “Diploma in Electronics” and submitted to the
Department of Electronics Engineering, Government Women Polytechnic College, Ajmer is
a record of my own investigations carried under the Guidance of Shri Alok Mathur, Assistant
Professor, Centre for Electronic Governance, Jaipur .

I have not submitted the matter presented in this report anywhere for the award of any other
work.

Hitesh yadav
Roll No. :
Government Polytechnic College, neemrana
ACKNOWLEDGMENET

I would like to express my sincere gratitude and deep debt to our Head of Department Mr.
mukesh gothwal..and our training in-charge Ms. Priyanka nehra for their encouragement and
valueable advice.

I pay thank to Mr. ALOK MATHUR who has given guidance and a light to me during this
practical training. His versatile knowledge about “JAVA” has eased me in the critical times
during the span of this practical training Seminar.

I take this opportunity to express my gratitude to all those people who have been directly and
indirectly with me during the competition of this practical training seminar.

I acknowledge here out debt to those who contributed significantly to one or more steps. I take
full responsibility for any remaining sins of omission and commission.

Hitesh yadav
DIPLOMA IN COMPUTER SCIENCE
COMPANY PROFILE

Centre for Electronic Governance, Jaipur


(Established by Department of Technical Education, Govt. of Rajasthan)

Centre for Electronic Governance is an autonomous body of Government of Rajasthan under the
Department of Technical Education.

CEG get recognition in IT Training programs like Big data, Hadoop, AWS Cloud Computing,
CCNA Trainings, Android App Development, Java, ASP.NET Training, ASP.NET MVC 5
using Razor, Entity Framework, WCF, PHP, Auto CAD, Red Hat Certification training, C, C++,
Linux Training program, Embedded Training programs etc. in Jaipur.CEG is authorized
education partner of CISCO, Red HAT, Microsoft, Autodesk.

Training programs run at CEG are approved by Department of Technical Education, Govt. of
Rajasthan . CEG is also working as study Centre of IGNOU for MCA, BCA, CIT, PGDIS and
ACISE programs. CEG started software development and Live Project training to give exposure
to real-time applications to students.

CEG also Conduct Summer Training programs for M.Sc., B.Tech, M.Tech and for Diploma
students. 3D Printing & Robotic Lab has established as per Govt. of Rajasthan instruction.
Centre for Electronics Governance is working as Central Placement Cell (CPC) as a Nodal
Agency on behalf of Department of Technical Education Govt. of Rajasthan. State Level Central
Placement Cell works for placement of Engineering, Diploma and Non Technical students of
Rajasthan.

CEG organized State level centralized admission of B.Tech./B.E., B.Arch. MBA, MCA and
BHMCT
INDEX

Chapter Contents s Page No.

1. Introduction

2. Hardware & Software Requirement

3. Java OOP Concepts

4. Inheritance

5. Exception Handling

6. Multithreading in Java

7. Applet

8. JDBC

9. Database

10. AWT and Swings

11. Conclusion

12. References
Chapter 1
INTERODUCTION

1.1 What is Java


Java is a general-purpose computer programming language that is concurrent, class-
based, object-oriented. Java is a popular general-purpose programming language and computing
platform. It is fast, reliable, and secure. According to Oracle, the company that owns Java, Java
runs on 3 billion devices worldwide.

Java was originally developed by James Gosling at Sun Microsystems (which has since been
acquired by Oracle Corporation) and released in 1995 as a core component of Sun
Microsystems’ Java platform.

The Oracle implementation is packaged into two different distributions:


1. Java Runtime Environment (JRE) which contains the parts of the Java SE platform
required to run Java programs and is intended for end users.
2. Java Development Kit (JDK) which is intended for software developers and includes
development tools such as the Java compiler, Javadoc, Jar, and a debugger.

1.2 Features of Java


Simple
Java was designed to be easy for the Professional programmer to learn and to use effectively. If
you are an experienced C++ programmer, learning Java will be even easier. Because Java
inherits the C/C++ syntax and many of the object oriented features of C++. Most of the
confusing concepts from C++ are either left out of Java or implemented in a cleaner, more
approachable manner.

Secure
The Java platform provides various features for security of Java applications. Some of the high-
level features that Java handles are:
- provides secure platform for developing and running applications
- automatic memory management, reduces memory corruption and vulnerabilities
- provides secure communication by protecting the integrity and privacy of data transmitted

Portable
For programs to be dynamically downloaded to all the various types of platforms connected to
the Internet, some means of generating portable executable code is needed .As you will see, the
same mechanism that helps ensure security also helps create portability. Indeed, Java’s solution
to these two problems is both elegant and efficient.

Object-Oriented
Java was not designed to be source-code compatible with any other language. This allowed the
Java team the freedom to design with a blank slate. One outcome of this was a clean usable,
pragmatic approach to objects. The object model in Java is simple and easy to extend, while
simple types, such as integers, are kept as high-performance non-objects.

Robust
The multi-platform environment of the Web places extraordinary demands on a program,
because the program must execute reliably in a variety of systems. The ability to create robust
programs was given a high priority in the design of Java. Java is strictly typed language; it
checks your code at compile time and run time.

Java virtually eliminates the problems of memory management and de-allocation, which is
completely automatic. In a well-written Java program, all run time errors can –and should –be
managed by your program.

Multithreaded
Java was designed to meet the real-world requirement of creating interactive, networked
programs. To accomplish this, Java supports multithreaded programming, which allows you to
write programs that do many things simultaneously. The Java run-time system comes with an
elegant yet sophisticated solution for multiprocess synchronization that enables you to construct
smoothly running interactive systems. Java's easy-to-use approach to multithreading allows you
to think about the specific behavior of your program, not the multitasking subsystem.
1.3 Byte Code
The key that allows the Java to solve the security and portability problems is that the output of
Java compiler is Byte code. Byte code is a highly optimized set of instructions designed to be
executed by the Java run-time system, which is called the Java Virtual Machine (JVM). That is,
in its standard form, the JVM is an interpreter for byte code.
Translating a Java program into byte code helps makes it much easier to run a program in a wide
variety of environments. The reason is, once the run-time package exists for a given system, any
Java program can run on it.

1.4 Java Virtual Machine (JVM)


Beyond the language, there is the Java virtual machine. The Java virtual machine is an important
element of the Java technology. The virtual machine can be embedded within a web browser or
an operating system. Once a piece of Java code is loaded onto a machine, it is verified. As part of
the loading process, a class loader is invoked and does byte code verification makes sure that the
code that’s has been generated by the compiler will not corrupt the machine that it’s loaded on.
Byte code verification takes place at the end of the compilation process to make sure that is all
accurate and correct. So byte code verification is integral to the compiling and executing of Java
code.

Java programming uses to produce byte codes and executes them. The first box indicates that the
Java source code is located in a. Java file that is processed with a Java compiler called javac. The
Java compiler produces a file called a. class file, which contains the byte code. The .Class file is
then loaded across the network or loaded locally on your machine into the execution
environment is the Java virtual machine, which interprets and executes the byte code.
1.5 Java Architecture
Java architecture provides a portable, robust, high performing environment for development.
Java provides portability by compiling the byte codes for the Java Virtual Machine, which is then
interpreted on each platform by the run-time environment. Java is a dynamic system, able to load
code when needed from a machine in the same room or across the planet.

Compilation of code
When you compile the code, the Java compiler creates machine code (called byte code) for a
hypothetical machine called Java Virtual Machine (JVM). The JVM is supposed to execute the
byte code. The JVM is created for overcoming the issue of portability. The code is written and
compiled for one machine and interpreted on all machines. This machine is called Java Virtual
Machine.

Compiling and interpreting Java Source Code


During run-time the Java interpreter tricks the byte code file into thinking that it is running on a
Java Virtual Machine. In reality this could be a Intel Pentium Windows 95 or Sun SARC station
running Solaris or Apple Macintosh running system and all could receive code from any
computer through Internet and run the Applets.
1.6 Applications of Java
Java technology is everywhere, powering 3 billion devices worldwide. It's more than likely that
you have used Java one way or the other. Here are some of the applications of Java.
1. Android apps - Java programming language using Android SDK (Software Development
Kit) is usually used for developing Android apps.
2. Web apps - Java is used to create Web applications through Servlets, Struts or JSPs.
Some of the popular web applications written in Java are: Google.com, Facebook.com,
eBay.com, LinkedIn.com etc.
3. Software Development - Softwares like Eclipse, OpenOffice, Vuze, MATLAB etc use
Java.
4. Big Data Processing - You can use popular software framework like Hadoop (which
itself is written in Java) to process Big Data. To use Hadoop, you need to understand Java
programming.
5. Trading System - You can build trading applications having low latency using the Oracle
Extreme Java Trading Platform.
6. Embedded Devices - While C/C++ programming languages are still popular choices for
working with embedded systems, Oracle's Java Embedded technologies provide platform
and runtime for billions of embedded devices like: televisions, SIM card, Blu-ray Disc
players etc.
Besides these applications, Java is also used for game development, scientific applications (like
natural language processing), and many others.

1.7 Java Terminologies


Java - Java is a set of technologies (programming language and computing platform) for creating
and running software. However, Java is often used to refer Java programming language for
simplicity.

Java programming language - A powerful, general-purpose, platform-independent, object-


oriented programming language.

Java EE, Java ME and Java SE - Java EE, Java ME and Java SE stands for Java Platform
Enterprise Edition, Micro Edition, and standard edition respectively.
Java EE is targeted for applications which run on servers. Java ME is targeted for resource-
limited devices like embedded devices. And, Java SE is the basic Java environment used for
creating standard programs.

JVM - JVM (Java Virtual Machine) is an abstract machine that enables your computer to run a
Java program.

JRE - JRE (Java Runtime Environment) contains JVM, supporting libraries, and other
components to run a Java program. However, it doesn't contain any compiler and debugger.

JDK - JDK (Java Development Kit) contains JRE and tools such as compilers and debuggers for
developing Java applications .
Chapter 2
HARDWARE & SOFTWARE REQUIREMENT

Operating System:

 Windows 7, Windows 8 or Windows 10


 Linux

Hardware:

 Processor (CPU) with 2 gigahertz (GHz) frequency or above


 A minimum of 1 GB of RAM
 Monitor Resolution 1024 X 768 or higher
 A minimum of 20 GB of available space on the hard disk
 Internet Connection
 Keyboard and a Microsoft Mouse or some other compatible pointing device

SOFTWARE:
Editor : Notepad, NetBeans or other editor
Software : JDK 1.8 or more
Database : MySQL or other
Chapter 3
JAVA OOP CONCEPTS

3.1 OOP Concept


Object-oriented programming aims to implement real-world entities like inheritance, hiding,
polymorphism etc in programming. The main aim of OOP is to bind together the data and the
functions that operate on them so that no other part of the code can access this data except
that function.
The Object class is the parent class of all the classes in java by default. In other words, it is
the topmost class of java.

There are four main OOP concepts in Java. These are:


 Abstraction. Abstraction means using simple things to represent complexity. We all
know how to turn the TV on, but we don’t need to know how it works in order to enjoy
it. In Java, abstraction means simple things like objects, classes, and variables represent
more complex underlying code and data. This is important because it lets avoid repeating
the same work multiple times.

 Encapsulation. This is the practice of keeping fields within a class private, then
providing access to them via public methods. It’s a protective barrier that keeps the data
and code safe within the class itself. This way, we can re-use objects like code
components or variables without allowing open access to the data system-wide.

 Inheritance. This is a special feature of Object Oriented Programming in Java. It lets


programmers create new classes that share some of the attributes of existing classes. This
lets us build on previous work without reinventing the wheel.

 Polymorphism. This Java OOP concept lets programmers use the same word to mean
different things in different contexts. One form of polymorphism in Java is method
overloading. That’s when different meanings are implied by the code itself. The other
form is method overriding. That’s when the different meanings are implied by the
values of the supplied variables.
3.2 Access Modifiers in Java
As the name suggests access modifiers in Java helps to restrict the scope of a class,
constructor , variable , method or data member. There are four types of access modifiers
available in java:
1. Default – No keyword required
2. Private
3. Protected
4. Public

1. Default: When no access modifier is specified for a class, method or data member – It
is said to be having the default access modifier by default. The data members, class
or methods which are not declared using any access modifiers i.e. having default
access modifier are accessible only within the same package.

2. Private: The private access modifier is specified using the keyword private. The
methods or data members declared as private are accessible only within the class in
which they are declared. Any other class of same package will not be able to access
these members. Classes or interface can not be declared as private.

3. Protected: The protected access modifier is specified using the keyword protected.
The methods or data members declared as protected are accessible within same
package or sub classes in different package.
4. Public: The public access modifier is specified using the keyword public. The public
access modifier has the widest scope among all other access modifiers. Classes,
methods or data members which are declared as public are accessible from every
where in the program. There is no restriction on the scope of a public data members.

3.3 Method Overloading in Java


If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading. If we have to perform only one operation, having same name of the
methods increases the readability of the program.

Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for
three parameters then it may be difficult for you as well as other programmers to understand
the behavior of the method because its name differs.
Method overloading increases the readability of the program.

3.4 Method Overriding in Java


If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in java.
In other words, If subclass provides the specific implementation of the method that has been
provided by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding


o Method overriding is used to provide specific implementation of a method that is
already provided by its super class.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


method must have same name as in the parent class
method must have same parameter as in the parent class.

3.5 Java constructor:


A constructor in Java is a method which is used to initialize objects. Constructor method of a
class has the same name as that of the class, they are called or invoked when an object of a
class is created and can't be called explicitly. Attributes of an object may or may not be
available while creating objects, if no attribute is available then default constructor is called,
some of the attributes may be known initially. It is optional to write constructor method(s) in
a class but due to their utility they are used.

Types of java constructors


There are two types of constructors in java:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
Default constructor is used to provide the default values to the object like 0, null etc.
depending on the type.
Java parameterized constructor
A constructor which has a specific number of parameters is called parameterized constructor.
Chapter 4
INHERITANCE

4.1 What is Inheritance


Inheritance is a mechanism in which one class acquires the property of another class. For
example, a child inherits the traits of his/her parents. With inheritance, we can reuse the fields
and methods of the existing class. Hence, inheritance facilitates Reusability and is an
important concept of OOPs.

Types of Inheritance
There are Various types of inheritance in Java:
1. Single Inheritance:
In Single Inheritance one class extends another class (one class only).

In above diagram, Class B extends only Class A. Class A is a super class and Class B
is a Sub-class.

2. Multiple Inheritance:
In Multiple Inheritance, one class extending more than one class. Java does not
support multiple inheritance.
As per above diagram, Class C extends Class A and Class B both.

3. Multilevel Inheritance:
In Multilevel Inheritance, one class can inherit from a derived class. Hence, the
derived class becomes the base class for the new class.

As per shown in diagram Class C is subclass of B and B is a of subclass Class A.

4. Hierarchical Inheritance:
In Hierarchical Inheritance, one class is inherited by many sub classes.
As per above example, Class B, C, and D inherit the same class A.
5. Hybrid Inheritance:
Hybrid inheritance is a combination of Single and Multiple inheritance.

As per above example, all the public and protected members of Class A are inherited
into Class D, first via Class B and secondly via Class C.

Java Inheritance Syntax:


class subClass extends superClass
{
//methods and fields
}

4.2 Encapsulation
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism
that binds together code and the data it manipulates.Other way to think about encapsulation
is, it is a protective shield that prevents the data from being accessed by the code outside this
shield.
 Technically in encapsulation, the variables or data of a class is hidden from any other
class and can be accessed only through any member function of own class in which they
are declared.
 As in encapsulation, the data in a class is hidden from other classes, so it is also known
as data-hiding.
 Encapsulation can be achieved by: Declaring all the variables in the class as private and
writing public methods in the class to set and get the values of variables.

Advantages of Encapsulation:
Data Hiding: The user will have no idea about the inner implementation of the class. It will
not be visible to the user that how the class is storing values in the variables. He only knows
that we are passing the values to a setter method and variables are getting initialized with that
value.

Increased Flexibility: We can make the variables of the class as read-only or write-only
depending on our requirement. If we wish to make the variables as read-only then we have to
omit the setter methods like setName(), setAge() etc. from the above program or if we wish to
make the variables as write-only then we have to omit the get methods like getName(),
getAge() etc. from the above program

Reusability: Encapsulation also improves the re-usability and easy to change with new
requirements.
Chapter 5
Exception Handling

5.1 What is Exception Handling


Exception handling in Java is very robust and easy to understand and use. Exceptions in java
can arise from different kind of situations such as wrong data entered by user, hardware
failure, network connection failure, Database server down etc.

Java being an object oriented programming language, whenever an error occurs while
executing a statement, creates an exception object and then the normal flow of the program
halts and JRE tries to find someone that can handle the raised exception. The exception object
contains a lot of debugging information such as method hierarchy, line number where the
exception occurred, type of exception etc. When the exception occurs in a method, the
process of creating the exception object and handing it over to runtime environment is
called “throwing the exception”.

Once runtime receives the exception object, it tries to find the handler for the exception.
Exception Handler is the block of code that can process the exception object. If appropriate
exception handler is found, exception object is passed to the handler to process it. The
handler is said to be “catching the exception”. If there are no appropriate exception handler
found then program terminates printing information about the exception.

Exception is an event that interrupts the normal flow of execution. It is a disruption during
the execution of the Java program.
There are two types of errors:
1. Compile time errors
2. Runtime errors
Compile time errors can be again classified again into two types:
 Syntax Errors
 Semantic Errors
5.2 Java Exception Handling Keywords
1. try-catch – We use try-catch block for exception handling in our code. try is the start of
the block and catch is at the end of try block to handle the exceptions. We can have
multiple catch blocks with a try and try-catch block can be nested also. catch block
requires a parameter that should be of type Exception.

2. throw – We know that if any exception occurs, an exception object is getting created
and then Java runtime starts processing to handle them. Sometime we might want to
generate exception explicitly in our code, for example in a user authentication program
we should throw exception to client if the password is null. throw keyword is used to
throw exception to the runtime to handle it.

3. throws – When we are throwing any exception in a method and not handling it, then
we need to use throws keyword in method signature to let caller program know the
exceptions that might be thrown by the method. The caller method might handle these
exceptions or propagate it to it’s caller method using throws keyword. We can provide
multiple exceptions in the throws clause and it can be used with main() method also.

4. finally – finally block is optional and can be used only with try-catch block. Since
exception halts the process of execution, we might have some resources open that will
not get closed, so we can use finally block. finally block gets executed always, whether
exception occurred or not.

5.3 Try Catch Block


Java provides an inbuilt exceptional handling.
1. The normal code goes into a TRY block.
2. The exception handling code goes into the CATCH block

try{

statement(s)

catch (exceptiontype name){


statement(s)

Example

class JavaException {

public static void main(String args[]) {

int d = 0;

int n = 20;

try {

int fraction = n / d;

System.out.println("This line will not be Executed");

} catch (ArithmeticException e) {

System.out.println("In the catch Block due to Exception = " + e);

System.out.println("End Of Main");

}
Chapter 6
Multithreading in Java

6.1 Multithreading in Java


Multithreading in java is a process of executing multiple threads simultaneously. Thread is
basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking.
But we use multithreading than multiprocessing because threads share a common memory
area. They don't allocate separate memory area so saves memory, and context-switching
between the threads takes less time than process.
Java Multithreading is mostly used in games, animation etc.

6.2 Advantage of Java Multithreading


1) It doesn't block the user because threads are independent and you can perform multiple
operations at same time.
2) You can perform many operations together so it saves time.
3) Threads are independent so it doesn't affect other threads if exception occur in a single
thread.

6.3 Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to
utilize the CPU. Multitasking can be achieved by two ways:
o Process-based Multitasking(Multiprocessing)
o Thread-based Multitasking(Multithreading)

1) Process-based Multitasking (Multiprocessing)


o Each process have its own address in memory i.e. each process allocates separate
memory area.
o Process is heavyweight.
o Cost of communication between the process is high.
o Switching from one process to another require some time for saving and loading
registers, memory maps, updating lists etc.
2) Thread-based Multitasking (Multithreading)
o Threads share the same address space.
o Thread is lightweight.
o Cost of communication between the thread is low.

6.4 Thread in java


A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of
execution.
Threads are independent, if there occurs exception in one thread, it doesn't affect other
threads. It shares a common memory area.

As shown in the above figure, thread is executed inside the process. There is context-
switching between the threads. There can be multiple processes inside the OS and one
process can have multiple threads.
6.5 Life Cycle of Thread
Chapter 7
Applet in Java

7.1 Introduction of Applet


An applet is a Java program that runs in a Web browser. An applet can be a fully functional
Java application because it has the entire Java API at its disposal.

An applet is a Java class that extends the java.applet.Applet class. A main() method is not
invoked on an applet, and an applet class will not define main(). Applets are designed to be
embedded within an HTML page.When a user views an HTML page that contains an applet,
the code for the applet is downloaded to the user's machine. A JVM is required to view an
applet. The JVM can be either a plug-in of the Web browser or a separate runtime
environment. The JVM on the user's machine creates an instance of the applet class and
invokes various methods during the applet's lifetime. Applets have strict security rules that
are enforced by the Web browser. The security of an applet is often referred to as sandbox
security, comparing the applet to a child playing in a sandbox with various rules that must be
followed.

7.2 Life Cycle of an Applet:


Four methods in the Applet class give you the framework on which you build any serious
applet:
 init: This method is intended for whatever initialization is needed for your applet. It
is called after the param tags inside the applet tag have been processed.
 start: This method is automatically called after the browser calls the init method. It is
also called whenever the user returns to the page containing the applet after having
gone off to other pages.
 stop: This method is automatically called when the user moves off the page on which
the applet sits. It can, therefore, be called repeatedly in the same applet.
 destroy: This method is only called when the browser shuts down normally. Because
applets are meant to live on an HTML page, you should not normally leave resources
behind after a user leaves the page that contains the applet.
 paint: Invoked immediately after the start() method, and also any time the applet
needs to repaint itself in the browser. The paint() method is actually inherited from
the java.awt.

7.3 A "Hello, World" Applet:


The following is a simple applet named HelloWorldApplet.java:
import java.applet.*;
import java.awt.*;
public class HelloWorldApplet extends Applet
{
public void paint (Graphics g)
{
g.drawString ("Hello World", 25, 50);
}
}

7.4 Commonly used methods of Graphics class:


1. public abstract void drawString(String str, int x, int y): is used to draw the specified
string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with the
specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle
with the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used to draw oval
with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with
the default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line
between the points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver
observer): is used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used to fill a circular or elliptical arc.
10. public abstract void setColor(Color c): is used to set the graphics current color to the
specified color.
11. public abstract void setFont(Font font): is used to set the graphics current font to the
specified font.

Simple example of Applet by appletviewer tool:

//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome to applet",150,150);
}
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/

To execute the applet by appletviewer tool, write in command prompt:


c:\>javac First.java
c:\>appletviewer First.java
Chapter 8
JDBC

8.1 Java Database Connectivity

JDBC is a Java API for executing SQL statements. JDBC is standing for Java Database
Connectivity. It consists of a set of classes and interfaces written in the Java programming
language. JDBC provides a standard API for tool/database developers and makes it possible
to write database applications using a pure Java API.

Using JDBC, it is easy to send SQL statements to virtually any relational database. One can
write a single program using the JDBC API, and the program will be able to send SQL
statements to the appropriate database.

What Does JDBC ?


Simply put, JDBC makes it possible to do three things:
 Establish a connection with a database
 Send SQL statements
 Process the results.

8.2 Use of JDBC and ODBC


JDBC may be taken to represents java Data base connectivity. The java Application program
Interface (API) makes a connection between java application and applet and a database
management system (DBMS or RDBMS).
The bridge between a java program and a database is a JDBC-DBC driver .A conceptual
structure of using a java API in a client to handle a database in a server is shown below:--
8.3 Driver
Driver A Java program need a link called driver, which can understand JDBC requests and
translate them into a format that can be understood by a database and vice versa.
JDBC Driver is a software component that enables java application to interact with the
database.
There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)

8.4 Using a JDBC


To use the JDBC language application or applet, the following steps have been followed: -
1. Import the java.sql package.
2. Load the driver.
3. Establish a connection to the database.
4. Create a statement.
5. Execute the statement.
6. Retrieve the results.
7. Close the connection and the statement.

1. Importing SQL package. The command is import.Java.sql.*

2. Loading the driver loading the driver is done using following method:
Class. for Name(“sun. Jdbc.odbc.JdbcOdbc Driver ”);
The driver specified is available in JDK 5.0 10

3. Establishing connection : Connection is establishing with the database using the


following method define in the Driver Manager class :
Connection connect = Driver Manager. Getconnection (“jdbc:odbc: database”) where “jdbc:
odbc: database” is database the URL object specifying the protocol, sub protocol and
database name.
4. Prepare statement :In this step, statement object that is required to send a query to the
database is prepared. This statements is prepared using the following methods defined in
Connection interface:
Statement stmt=connect.createStatement ();

5.Execute Query : The SQL query that is to be sent to the database is executed by calling the
following method on statement object ,which returns a ResultsSet object:
ResultSet reset = stmnt.exicute Query (“select * from database”);

6.Retrive the result:The result return by the database to the Query executed
are extract from ResultSet using the method defined in ResultSet interface.
While(Reset.next())
System.out.println (“Name: ”+reset.getString (“name”));

7. Close the statements and connection using the close method, the statement and
connection are closed:

8.5 Example to Connect Java Application with mysql database

import java.sql.*;
class MysqlCon{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sweta","root","");
//here sonoo is database name, root is username and password
Statement stmt=con.createStatement();
. ResultSet rs=stmt.executeQuery("select * from emp");
. while(rs.next())
. System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
. }catch(Exception e){ System.out.println(e);}
. }
. }
Chapter 9
Database

A database management system (DBMS) is computer software designed for the purpose of
managing databases, a large set of structured data, and run operations on the data requested
by numerous users. Typical examples of DBMSs include Oracle, DB2, Microsoft Access,
Microsoft SQL Server, MySQL, SQLite. DBMSs are typically used by Database
administrators in the creation of Database systems.

Data: - It is the row information provided by the user to the computer.


Database: - A database is a collection of related records (data) organized in a tabular form
with appropriated field hints.
Data Base Management: - Data base management concert of all the operation, which we
perform on over database. Editing new records modifying and deleting existing records
arranging and filtering on records etc.
Data Base Management System (DBMS): - DBMS is software or a graph of software,
which provides facility to, manages to play and perform all the operation related to data base
management.
Relational Data Base Management System (RDBMS): - A RDBMS provides facility to
establish a relationship between two or more table of related data and to extracted the
complete information. MS Access is a RDBMS and the companion software of MS-office
pages. In MS-Access is a data base is a collection of tables, queries froms, reports, pages,
micros and modules which we used to manage and present data these components one is also
called object of database

9.1 MySQL

MySQL is an Oracle-backed open source relational database management system (RDBMS)


based on Structured Query Language (SQL). MySQL runs on virtually all platforms,
including Linux, UNIX and Windows. Although it can be used in a wide range of
applications, MySQL is most often associated with web applications and online publishing.
MySQL is an important component of an open source enterprise stack called XAMPP.
XAMPP is a web development platform that uses Windows as the operating
system, Apache as the web server, MySQL as the relational database management system
and PHP as the object-oriented scripting language.

Originally conceived by the Swedish company MySQL AB, MySQL was acquired by Sun
Microsystems in 2008 and then by Oracle when it bought Sun in 2010. Developers can use
MySQL under the GNU General Public License (GPL), but enterprises must obtain a
commercial license from Oracle.

Today, MySQL is the RDBMS behind many of the top websites in the world and countless
corporate and consumer-facing web-based applications, including Facebook, Twitter and
YouTube.

How MySQL works

MySQL is based on a client-server model. The core of MySQL is MySQL server, which
handles all of the database instructions (or commands). MySQL server is available as a
separate program for use in a client-server networked environment and as a library that can
be embedded (or linked) into seperate applications.

MySQL operates along with several utility programs which support the administration of
MySQL databases. Commands are sent to MySQLServer via the MySQL client, which is
installed on a computer.

MySQL was originally developed to handle large databases quickly. Although MySQL is
typically installed on only one machine, it is able to send the database to multiple locations,
as users are able to access it via different MySQL client interfaces. These interfaces send
SQL statements to the server and then display the results.

Core MySQL features

MySQL enables data to be stored and accessed across multiple storage engines, including
InnoDB, CSV, and NDB. MySQL is also capable of replicating data and partitioning tables
for better performance and durability. MySQL users aren't required to learn new commands;
they can access their data using standard SQL commands.
MySQL is written in C and C++ and accessible and available across over 20 platforms,
including Mac, Windows, Linux and Unix. The RDBMS supports large databases with
millions records and supports many data types including signed or unsigned integers 1, 2, 3,
4, and 8 bytes long; FLOAT; DOUBLE; CHAR; VARCHAR; BINARY; VARBINARY;
TEXT; BLOB; DATE; TIME; DATETIME; TIMESTAMP; YEAR; SET; ENUM; and
OpenGIS spatial types. Fixed- and variable-length string types are also supported.

For security, MySQL uses an access privilege and encrypted password system that enables
host-based verification. MySQL clients can connect to MySQL Server using several
protocols, including TCP/IP sockets on any platform. MySQL also supports a number of
client and utility programs, command-line programs and administration tools such as MySQL
Workbench.
Chapter 10
AWT and Swings

Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based


applications in java.
Java AWT components are platform-dependent i.e. components are displayed according to
the view of operating system. AWT is heavyweight i.e. its components are using the
resources of OS.
The java.awt package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.

AWT Example by Inheritance


simple example of AWT where we are inheriting Frame class. Here, we are showing Button
component on the Frame.
importjava.awt.*;
class First extends Frame{
First(){
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible
. }
. public static void main(String args[]){
. First f=new First();
. }}
10.1 Introduction to Swings
Swing API is a set of extensible GUI Components to ease the developer's life to create
JAVA based Front End/GUI Applications. It is build on top of AWT API and acts as a
replacement of AWT API, since it has almost every control corresponding to AWT controls.
Swing component follows a Model-View-Controller architecture to fulfill the following
criterias.
 A single API is to be sufficient to support multiple look and feel.
 API is to be model driven so that the highest level API is not required to have data.
 API is to use the Java Bean model so that Builder Tools and IDE can provide better
services to the developers for use.
MVC Architecture
Swing API architecture follows loosely based MVC architecture in the following manner.
 Model represents component's data.
 View represents visual representation of the component's data.
 Controller takes the input from the user on the view and reflects the changes in
Component's data.
 Swing component has Model as a seperate element, while the View and Controller
part are clubbed in the User Interface elements. Because of which, Swing has a
pluggable look-and-feel architecture.
Swing Features
 Light Weight − Swing components are independent of native Operating System's
API as Swing API controls are rendered mostly using pure JAVA code instead of
underlying operating system calls.
 Rich Controls − Swing provides a rich set of advanced controls like Tree,
TabbedPane, slider, colorpicker, and table controls.
 Highly Customizable − Swing controls can be customized in a very easy way as
visual apperance is independent of internal representation.
 Pluggable look-and-feel − SWING based GUI Application look and feel can be
changed at run-time, based on available values.

The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
10.3 Difference between AWT and Swing
There are many differences between java awt and swing that are given below.

1) AWT components are platform-dependent. Java swing components are platform-


independent.
2) AWT components are heavyweight. Swing components are lightweight.
3) AWT doesn't support pluggable look and feel. Swing supports pluggable look
and feel.
4) AWT provides less components than Swing. Swing provides more powerful
componentssuch as tables, lists, scrollpanes, colorchooser, tabbedpane etc.
5) AWT doesn't follows MVC(Model View Controller) where model represents data,
view represents presentation and controller acts as an interface between model and view.
Swing follows MVC.

10.4 Java Swing class hierarchy


The class JComponent, descended directly from Container, is the root class for most of
Swing’s user interface components.

Swing contains components that you’ll use to build a GUI. I am listing you some of the
commonly used Swing components.
Chapter 8
Conclusion

Java offers the real possibility that most programs can be written in a type-safe language.
However, for Java to be broadly useful, it needs to have more expressive power than it does
at present.

The Java training allows its aspirants to gain extensive) knowledge of the advanced
programming technique and it covers all . Java is widely used because it is a very easy to
learn language with a rich standard library.

Java is a high-level, object programming language. It runs on a variety of platforms, such as


Windows, Mac OS, and the various versions of UNIX. Java is fast, secure, and reliable. From
laptops to datacenters, game consoles to scientific supercomputers, cell phones to the
Internet, Java is everywhere!

To create a small web application in cell phone to a large enterprise application that run on
internet, we use Java/ J2EE programming language. Java programming is simple, object-
oriented, robust, secure, architecture-neutral and portable, high performance, interpreted,
threaded and dynamic.
Chapter 11
References

 Java Complete Reference – Herbert Schildt


 Programming with Java - E Balagurusamy
 A programmer guide – Java Certification (Mughal, Khalid)
 The Java™ Tutorials - Oracle Documentation https://docs.oracle.com/javase/tutorial
 Core Java - Java Beginners Tutorial javabeginnerstutorial.com/core-java/

Das könnte Ihnen auch gefallen