[go: up one dir, main page]

0% found this document useful (0 votes)
15 views97 pages

CGI Programming

The document provides an overview of the Common Gateway Interface (CGI), which is a standard for interfacing web servers with application programs to facilitate dynamic web content generation. It explains the CGI process, including how client requests are handled, the differences between CGI and regular programming, and the methods for sending form data using GET and POST. Additionally, it covers the configuration of CGI, environment variables, and provides examples of CGI scripts in Perl and PHP.

Uploaded by

sandip
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)
15 views97 pages

CGI Programming

The document provides an overview of the Common Gateway Interface (CGI), which is a standard for interfacing web servers with application programs to facilitate dynamic web content generation. It explains the CGI process, including how client requests are handled, the differences between CGI and regular programming, and the methods for sending form data using GET and POST. Additionally, it covers the configuration of CGI, environment variables, and provides examples of CGI scripts in Perl and PHP.

Uploaded by

sandip
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
You are on page 1/ 97

CGI Programming

Common Gateway Interface


• CGI means the "Common Gateway Interface" for everything.
• set of standards that defines a standard way of passing information or web-user
requests to an application program and getting data back to forward it to users.
• essential parts of HTTP (Hyper-Text Transfer Protocol).
• It is the exchange of information between the web server and a custom script.
• When the users requested the web-page, the server sends the requested web-page.
The web server usually passes the information to all application programs that
process data and sends back an acknowledged message; this technique of passing
data back-and-forth between server and application is the Common Gateway
Interface.
• The current version of CGI is CGI/1.1 & CGI/1.2 is under process.
CGI Programming
• is not a kind of language but just a specification(set of rules) that helps to
establish a dynamic interaction between a web application and the browser /
client application.
• The CGI programs make possible communication between client and web servers.

• The CGI Process


• The basic principle of Common Gateway Interface (CGI) is that a Web server passes client
request information to CGI programs in system environment variables (and in some cases
through standard input or command line arguments) and all standard output of CGI programs
is returned to Web clients.

• Whenever the client browser sends a request to the webserver the CGI programs
send the output back to the web server based on the input provided by the
client-server.
Common Gateway Interface
• There are two main differences between ``regular'' programming, and CGI
programming.
• First,
• all output from your CGI program must be preceded by a MIME-type header.
• This is HTTP header that tells the client what sort of content it is receiving.
• Most of the time, this will look like: Content-type: text/html
• Secondly,
• your output needs to be in HTML, or some other format that a browser will be able to display.

• Most of the time, this will be HTML, but occasionally you might write a CGI
program that outputs a gif image, or other non-HTML content.
CGI Programming
• Whenever the client browser sends a request to the webserver the
CGI programs send the output back to the web server based on the
input provided by the client-server.
• CGI is the standard for programs to interface with HTTP servers.
• CGI programming is written dynamically generating webpages that
respond to user input or webpages that interact with software on the
server
CGI Programming

• Working of CGI
When a request is made by the client-server
to the webserver, the CGI uses external
script files to handle such requests.
• These files could be written in any language.
• The main objective of these script files is to
retrieve the data from the database quickly
and more efficiently.
• These scripts convert the retrieved data into
an Html format that sends the data to these
web servers in Html formatted page.
The architecture of CGI is shown below:
Common Gateway Interface
• What happens when a user clicks a hyperlink to browse a particular web-
page or URL (Uniform Resource Locator).
• The steps are:
• Browser contacts the HTTP web server for demanding the URL
• Parsing the URL
• Look for the filename
• If it finds that file, a request is sent back
• Web browser takes a response from the webserver
• As the server response, it either shows the received file or an error message.
• It may become possible to set-up an HTTP server because when a certain directory is
requested, that file is not sent back; instead, it is executed as a program, and that
program's output is displayed back to your browser.
Configuring CGI
• The steps are:
• Find out which user is running the Web-server
• Check for server configuration to see if you can run the scripts in a particular
directory
• Check for file's permission
• Make a clear assurance that scripts you made are readable and executable by
the webserver user
• Make sure the Python-Script's first line refers to a webserver that the
interpreter can run
Input to the Common Gateway Interface
• Input to CGI:
• environment variables,
• accessing from input
• When a CGI program is called, the information that is made available to it
can be roughly broken into three groups:
• Information about the client, server, and user
• Form data that the user supplied
• Additional pathname information
• Most information about the client, server, or user is placed in CGI
environment variables.
• Form data is either incorporated into an environment variable, or is
included in the “body” of the request.
• And extra path information is placed in environment variables.
Input to the Common Gateway Interface
• Programs can access this information as they would any environment
variable (e.g., via the %ENV associative array in Perl).
Environment Variable Description
GATEWAY_INTERFACE The revision of the Common Gateway Interface that the server uses.
SERVER_NAME The server's hostname or IP address.
SERVER_SOFTWARE The name and version of the server software that is answering the client request.
SERVER_PROTOCOL The name and revision of the information protocol the request came in with.
SERVER_PORT The port number of the host on which the server is running.
REQUEST_METHOD The method with which the information request was issued.
PATH_INFO Extra path information passed to a CGI program.
PATH_TRANSLATED The translated version of the path given by the variable PATH_INFO.
SCRIPT_NAME The virtual path (e.g., /cgi-bin/program.pl) of the script being executed.
DOCUMENT_ROOT The directory from which Web documents are served.
QUERY_STRING The query information passed to the program. It is appended to the URL with a “?”.
REMOTE_HOST The remote hostname of the user making the request.
REMOTE_ADDR The remote IP address of the user making the request.
AUTH_TYPE The authentication method used to validate a user.
REMOTE_USER The authenticated name of the user.
The user making the request. This variable will only be set if NCSA IdentityCheck flag is enabled, and
REMOTE_IDENT
the client machine supports the RFC 931 identification scheme (ident daemon).
CONTENT_TYPE The MIME type of the query data, such as “text/html”.
The length of the data (in bytes or the number of characters) passed to the CGI program through
CONTENT_LENGTH
standard input.
HTTP_FROM The email address of the user making the request. Most browsers do not support this variable.
HTTP_ACCEPT A list of the MIME types that the client can accept.
HTTP_USER_AGENT The browser the client is using to issue the request.
HTTP_REFERER The URL of the document that the client points to before accessing the CGI program.
Here's a simple Perl CGI script that uses environment variables to display various information
about the server:

#!/usr/local/bin/perl

print << EOF


Content-type: text/html

<HTML>
<HEAD><TITLE>About this Server</TITLE></HEAD>
<BODY><H1>About this Server</H1>
<HR><PRE>
Server Name: $ENV{'SERVER_NAME'}<BR>
Running on Port: $ENV{'SERVER_PORT'}<BR>
Server Software: $ENV{'SERVER_SOFTWARE'}<BR>
Server Protocol: $ENV{'SERVER_PROTOCOL'}<BR>
CGI Revision: $ENV{'GATEWAY_INTERFACE'}<BR>
<HR></PRE>
</BODY></HTML>
• By now, you should be reasonably comfortable designing CGI programs that create
simple virtual documents, like this one:

• #!/usr/local/bin/perl
• print "Content-type: text/html", "\n\n";
• print "<HTML>", "\n";
• print "<HEAD><TITLE>Simple Virtual HTML Document</TITLE></HEAD>", "\n";
• print "<BODY>", "\n";
• print "<H1>", "Virtual HTML", "</H1>", "<HR>", "\n";
• print "Hey look, I just created a virtual (yep, virtual) HTML document!", "\n";
• print "</BODY></HTML>", "\n";
• exit (0);
<HTML>
<HEAD><TITLE>About this Server</TITLE></HEAD>
<BODY><H1>About this Server</H1>
<HR><PRE>
Server Name: www.whatever.com
Running on Port: 80
Server Software: NCSA/1.4.2
Server Protocol: HTTP/1.0
CGI Revision: CGI/1.1
<HR></PRE>
</BODY></HTML>
Output from CGI : CGI and response headers
HTTP header
• we have taken the line that outputs "Content-type" for granted.
• But this is only one type of header that CGI programs can use.
• "Content-type" is an HTTP header that contains a MIME content type
describing the format of the data that follows.
• Other headers can describe:
• The size of the data
• Another document that the server should return (that is, instead of returning
a virtual document created by the script itself)
• HTTP status codes
• Table provides a quick listing of all the HTTP headers you might find
useful.
HTTP header
Header Description
Content-length The length (in bytes) of the output stream. Implies binary data.
Content-type The MIME content type of the output stream.
Date and time when the document is no longer valid and should be reloaded by
Expires
the browser.
Location Server redirection (cannot be sent as part of a complete header).
Pragma Turns document caching on and off.
Status Status of the request (cannot be sent as part of a complete header).
• https://www.oreilly.com/openbook/cgi/

• https://www.tutorialspoint.com/python/python_cgi_programming.ht
m#:~:text=First%20CGI%20Program,command%20to%20make%20file
%20executable.
Accessing Form Input
• Forms provide a way to get input from users and supply it to a CGI
program
Accessing Form Input: Query Strings
• One way to send form data to a CGI program is by appending the
form information to the URL, after a question mark.
• You may have seen URLs like the following:
http://some.machine/cgi-bin/name.pl?fortune
“?” character is known as a query string
When the server is passed a URL with a query string, it calls the CGI
program identified in the first part of the URL (before the “?”) and then
stores the part after the “?” in the environment variable
QUERY_STRING.
The following is a CGI program called name.pl that uses query
information to execute one of three possible UNIX commands.
Query Strings
The METHOD=GET attribute to the <FORM> tag in part
determines how the data is passed to the server

when the Submit Form! button is pressed the browser


sends the following request to the server:

The server executes the script called unix.pl in the cgi-bin


directory, and places the string “command=fortune” into
the QUERY_STRING environment variable
Since we used the GET method, all the form data is included in the URL.
So we can directly access this program without the form, by using the following URL:
http://some.machine/cgi-bin/unix.pl?command=fortune
POST Methods
• Using the POST method, the server sends the data as an input stream
to the program
<FORM ACTION="unix.pl" METHOD="POST">

The version of unix.pl that handles the form with POST


data follows. First, since the server passes information to
this program as an input stream, it sets the environment
variable CONTENT_LENGTH to the size of the data in
number of bytes (or characters). We can use this to read
exactly that much data from standard input.
#include <stdio.h>
#include <stdlib.h>
#include <string.h> https://www.oreilly.com/library/view/cgi-programming-
void main (void) on/9781565921689/05_chapter-02.html
{
char *http_user_agent;
printf ("Content-type: text/plain\n\n");
http_user_agent = getenv ("HTTP_USER_AGENT");
if (http_user_agent == NULL) {
printf ("Oops! Your browser failed to set the HTTP_USER_AGENT ");
printf ("environment variable!\n");
} else if (!strncmp (http_user_agent, "Mosaic", 6)) {
printf ("I guess you are sticking with the original, huh?\n");
} else if (!strncmp (http_user_agent, "Mozilla", 7)) {
printf ("Well, you are not alone. A majority of the people are ");
printf ("using Netscape Navigator!\n");
} else if (!strncmp (http_user_agent, "Lynx", 4)) {
printf ("Lynx is great, but go get yourself a graphic browser!\n");
} else {
printf ("I see you are using the %s browser.\n", http_user_agent);
printf ("I don't think it's as famous as Netscape, Mosaic or Lynx!\n");
}
exit (0);
}
Sending form data
• There are two methods for sending form data: GET and POST.
• The main difference between these methods is the way in which the
form data is passed to the CGI program.
• If the GET method is used, the query string is simply appended to the
URL of the program when the client issues the request to the server.
• This query string can then be accessed by using the environment
variable QUERY_STRING.
Form Data Decoding Process
• In order to access the information contained within the form, a
decoding protocol must be applied to the data.
• First, the program must determine how the data was passed by the
client.
• This can be done by examining the value in the environment variable
REQUEST_METHOD.
• If the value indicates a GET request, either the query string or the extra path
information must be obtained from the environment variables.
• if it is a POST request, the number of bytes specified by the
CONTENT_LENGTH environment variable must be read from standard input.
The algorithm for decoding form data follows:
• Determine request protocol (either GET or POST) by checking the
REQUEST_METHOD environment variable.
Form Data Decoding Process
• If the protocol is GET, read the query string from QUERY_STRING
and/or the extra path information from PATH_INFO.
• If the protocol is POST, determine the size of the request using
CONTENT_LENGTH and read that amount of data from the standard
input.
• Split the query string on the "&" character, which separates key-value
pairs (the format is key=value&key=value...).
• Decode the hexadecimal and "+" characters in each key-value pair.
• Create a key-value table with the key as the index. (If this sounds
complicated, don't worry, just use a high-level language like Perl. The
language makes it pretty easy.)
• Both GET and POST create an array (e.g. array( key1 => value1, key2 =>
value2, key3 => value3, ...)).
• This array holds key/value pairs, where keys are the names of the form
controls and values are the input data from the user.
• Both GET and POST are treated as $_GET and $_POST.
• These are superglobals, which means that they are always accessible,
regardless of scope - and you can access them from any function, class or
file without having to do anything special.
• $_GET is an array of variables passed to the current script via the URL
parameters.
• $_POST is an array of variables passed to the current script via the HTTP
POST method.
When to use GET?
• GET should NEVER be used for sending passwords or other sensitive
information!
• GET also has limits on the amount of information to send. The
limitation is about 2000 characters. However, because the variables
are displayed in the URL, it is possible to bookmark the page. This can
be useful in some cases
• Information sent from a form with the GET method is visible to
everyone (all variable names and values are displayed in the URL).
When to use POST?
• Information sent from a form with the POST method is invisible to
others (all names/values are embedded within the body of the HTTP
request) and has no limits on the amount of information to send.
• Moreover POST supports advanced functionality such as support for
multi-part binary input while uploading files to server.
• However, because the variables are not displayed in the URL, it is not
possible to bookmark the page.
• Developers prefer POST for sending form data.
Form Processing Using PHP : POST Method
<html>
<body>

<form action="welcome.php" method="post">


Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</body>
</html> Welcome.php
<html>
<body>

Welcome <?php echo $_POST["name"]; ?><br>


Your email address is: <?php echo
$_POST["email"]; ?>

</body>
</html>
Form Processing Using PHP : GET Method
<html>
<body>
<form action="welcome_get.php" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html> Welcome_get.php
<html>
<body>

Welcome <?php echo $_GET["name"]; ?><br>


Your email address is: <?php echo $_GET["email"]; ?>

</body>
</html>
JAVA
The principles for creating Java programming were
"Simple, Robust, Portable, Platform-independent, Secured, High Performance,
Multithreaded, Architecture Neutral, Object-Oriented, Interpreted, and Dynamic".
Java Attributes
• Familiar, Simple, Small
• Compiled and Interpreted
• Platform-Independent and Portable
• Object-Oriented
• Robust and Secure
• Distributed
• Multithreaded and Interactive
• High Performance
• Dynamic and Extensible
Java is Compiled and Interpreted
Hardware and
Programmer
Operating System

Source Code Byte Code


Text Editor Compiler Interpreter
.java file .class file
Notepad, javac java
emacs, vi appletviewer
netscape
Java is both compiled and an interpreted lang. First the java compiler translates
source code into the byte code instructions. In the next stage the java interpreter
converts the byte code instructions to Machine Code.
Architecture Neutral & Portable
 Java Compiler - Java source code (file with extension .java) to bytecode
(file with extension .class)
 Bytecode - an intermediate form, closer to machine representation
 A interpreter (virtual machine) on any target platform interprets the
bytecode.
 Porting the java system to any new platform involves writing an
interpreter.
 The interpreter will figure out what the equivalent machine dependent
code to run
Total Platform Independence
 Java’s Magic: The Byte Code : allows Java to solve
both the security and the portability problems is
that the output of a Java compiler is not
executable code but it is the Bytecode.
 Bytecode 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).
 JVM is an interpreter for bytecode. The fact that a
Java program is executed by JVM helps solve the
major problems associated with downloading
programs over the Internet.
 Translating a Java program into bytecode helps
makes it much easier to run a program in a wide
variety of environments.
 This is because only the JVM needs to be
implemented for each platform.
Some Salient Characteristics of Java
• Java is platform independent: the same • Java has some interesting
program can run on any correctly features:
implemented Java system • automatic type checking,
• Java is object-oriented: • automatic garbage collection,
• Structured in terms of classes, which • simplifies pointers; no directly
group data with operations on that data accessible pointer to memory,
• Can construct new classes by extending • simplified network access,
existing ones • multi-threading!
• Java designed as
• A core language plus
• A rich collection of commonly available
packages
• Java can be embedded in Web pages
Rich Class Environment
• Core Classes
• language
• Utilities
• Input/Output
• Low-Level Networking
• Abstract Graphical User Interface
• Internet Classes
TCP/IP Networking
WWW and HTML
Distributed Programs
Compiling and Executing a Java Program
• A Java source code compiler produces Java byte code
• Outputs one file per class: Model.class
• May be standalone or part of an IDE
• A Java Virtual Machine loads and executes class files
• May compile them to native code (e.g., x86) internally

54
History of java
 originally designed for interactive television,
 James Gosling, Patrick Naughton, Chris Warth, Mike Sheridan and Ed
Frank initiated the Java language project in June 1991.
 The idea was to develop a language which was platform-independent
and which could create embedded software for consumer electronic
devices,
 It took 18 months to develop and had an initial name as Oak,
 Renamed to Java in 1995, due to copyright issues.
 Java originally developed by James Gosling at Sun Microsystems and
released in 1995.
History of Java
• The small team of sun engineers called Green Team. Firstly, it was called "Greentalk" by
James Gosling, and the file extension was .gt.
• After that, it was called Oak and was developed as a part of the Green project.
• in 1995, Oak was renamed as "Java" because it was already a trademark by
Oak Technologies.
• Java is an island in Indonesia where the first coffee was produced (called Java coffee).
• Java was developed by James Gosling, who is known as the father of Java, in 1995.
James Gosling and his team members started the project in the early '90s.
• Initially it was designed for small, embedded systems in electronic appliances like set-
top boxes.
• However, it was best suited for internet programming. Later, Java technology was
incorporated by Netscape.
History of Java
• Java is just a name, not an acronym.
• Initially developed by James Gosling at Sun Microsystems (which is
now a subsidiary of Oracle Corporation) and released in 1995.
• In 1995, Time magazine called Java one of the Ten Best Products of
1995.
• JDK 1.0 was released on January 23, 1996.
• After the first release of Java, there have been many additional features
added to the language.
• Now Java is being used in Windows applications, Web applications, enterprise
applications, mobile applications, cards, etc.
• Each new version adds new features in Java.
Why Java Programming named "Java"?
• Why had they chose the name Java for Java language? The team
gathered to choose a new name. The suggested words were
"dynamic", "revolutionary", "Silk", "jolt", "DNA", etc. They wanted
something that reflected the essence of the technology:
revolutionary, dynamic, lively, cool, unique, and easy to spell, and fun
to say.
• According to James Gosling, "Java was one of the top choices along
with Silk". Since Java was so unique, most of the team members
preferred Java than other names.
• It is a kind of espresso bean. Java name was chosen by James Gosling
while having a cup of coffee nearby his office.
Versions of java
• 1995 version 1.0:
– The Java development kit was released for free by the sun
– 8-Packages 212-Classes
– Microsoft and other companies licensed Java
• 1997 version 1.1:
– 23 -Packages 504-Classes
– Improvement include better event handling inner classes , improved JVM.
– Microsoft developed its own 1.1 compatible Java Virtual
Machine for Internet Explorer
– Many browsers in use are still compatible only with 1.1
1999 version 1.2:
-It is also called as the Java 2 platform
-59 Packages -1520 Classes
-Code & tools distributed as the SDK
-A Java foundation class based on swings for improved graphics and user interfaces
-Collection API included list sets and hash map
Versions of java…
2000 VERSION 1.3:
- 76 Packages - 1842 Classes
- Java Sound (API for Digital & MIDI Sound)
•2002 VERSION 1.4:
- 135 Packages - 2991 Classes
- Improved XML support etc..,
•2004 VERSION 5.0 (1.5):
- 165 Packages - over 3000 Classes
- Faster startup metadata formatted Output
- Generic to operate on objects of various types
2006 Java SE 6:
– Scripting language support
2011 Java SE 7:
– JVM Support for dynamic language
– String in switch
– Allowing underscores in numeric literals
Versions of java…
2014 Java SE 8:
– for Each() method in Iterable interface.
- default and static methods in Interfaces.
- Functional Interfaces and Lambda Expressions.
2017 Java SE 9:
-Stream API Improvements
-Multi-Resolution Image API
March 2022 Java SE 18
Java Version History
1.Java SE 7 (28th July 2011)
1.JDK Alpha and Beta 2.Java SE 8 (18th Mar 2014)
(1995) 3.Java SE 9 (21st Sep 2017)
4.Java SE 10 (20th Mar 2018)
2.JDK 1.0 (23rd Jan 1996) 5.Java SE 11 (September 2018)
6.Java SE 12 (March 2019)
3.JDK 1.1 (19th Feb 1997) 7.Java SE 13 (September 2019)
8.Java SE 14 (Mar 2020)
4.J2SE 1.2 (8th Dec 1998) 9.Java SE 15 (September 2020)
5.J2SE 1.3 (8th May 2000) 10.Java SE 16 (Mar 2021)
11.Java SE 17 (September 2021)
6.J2SE 1.4 (6th Feb 2002) 12.Java SE 18 (to be released by March 2022)

7.J2SE 5.0 (30th Sep 2004)


8.Java SE 6 (11th Dec
2006)
Java Architecture
• Java Architecture is a collection of components, i.e., JVM, JRE, and JDK. It integrates the process of
interpretation and compilation. It defines all the processes involved in creating a Java program. Java
Architecture explains each and every step of how a program is compiled and executed.

Java Architecture can be explained by using the following steps:


There is a process of compilation and interpretation in Java.
Java compiler converts the Java code into byte code.
After that, the JVM converts the byte code into machine code.
The machine code is then executed by the machine.
The following figure represents the Java Architecture in which
each step is elaborate graphically.

Components of Java Architecture


The Java architecture includes the three main components:
• Java Virtual Machine (JVM)
• Java Runtime Environment (JRE)
• Java Development Kit (JDK)
Components of Java Architecture
• Java Virtual Machine
• The main feature of Java is WORA. WORA stands for Write Once Run Anywhere. The feature
states that we can write our code once and use it anywhere or on any operating system. Our
Java program can run any of the platforms only because of the Java Virtual Machine. It is a
Java platform component that gives us an environment to execute java programs. JVM's main
task is to convert byte code into machine code.
• JVM, first of all, loads the code into memory and verifies it. After that, it executes the code
and provides a runtime environment.
• Java Runtime Environment
• It provides an environment in which Java programs are executed. JRE takes our Java code,
integrates it with the required libraries, and then starts the JVM to execute it.
• Java Development Kit
• It is a software development environment used in the development of Java applications and
applets. Java Development Kit holds JRE, a compiler, an interpreter or loader, and several
development tools in it.
• These are the three main components of Java Architecture. The execution of a program is
done with all these three components.
What is JVM? Explain architecture of java in detail JAVA Run Time Environment(JRE)
along with suitable block diagram? Class Loader
Java class
JAVA (bytecode
Source
verifier) Libraries
(.java)
• The main feature of Java is WORA. WORA stands
for Write Once Run Anywhere.
• The feature states that we can write our code
once and use it anywhere or on any operating
JAVA Just In Time
system. Interpreter Compiler
• Our Java program can run any of the platforms JAVA
only because of the Java Virtual Machine. It is a Compiler
Java platform component that gives us an Run Time System
environment to execute java programs. JVM's
JAVA Bytecode
main task is to convert byte code into machine moves locally or
through network
code. (.class)
• JVM, first of all, loads the code into memory and Operating System
verifies it. After that, it executes the code and
provides a runtime environment.
Hardware
JAVA
Bytecode
(.class)

JAVA Virtual Machine(JVM)

Fig: Architecture of java


Java virtual machine (JVM).
• Java source code is compiled into bytecode by the Java compiler.
• Bytecode is not executable code for the target machine rather it is the object code of java virtual
machine (JVM). This bytecode will be stored in class files. During runtime, this bytecode will be
loaded, verified and JVM interprets the bytecode into machine code which will be executed in the
machine in which the Java program runs.
• Classloader loads all the class files required to execute the program.
• Classloader makes the Class program secure by separating the namespace for the classes obtained
through the network from Tak the classes available locally.
• Once the bytecode is loaded successfully, the next step is bytecode verification by bytecode
verifier.
• The bytecode verifier verifies the byte code to see if any security problems are there in the code.
• It checks the byte code and ensures the following.
• The code follows JVM specifications.
• There is no unauthorized access to memory.
• The code does not cause any stack overflows.
• There are no illegal data conversions in the code such as float to object references.
Java virtual machine (JVM)
• Once this code is verified and proven that there are no security issues with the code, JVM
will convert the byte code into machine code which will be directly executed by the machine
in This which the Java program runs.
• JVM is the simulated computer within a real computer.
• This is the "PL component that makes java programming language platform-neutral.
• All operating systems must have this JVM that is responsible for generating executable code
from bytecode generated by standard java compiler. If the operating system does not
incorporate JVM, we can install it.
• the component "Just in Time" (JIT) compiler is a component that helps the program
execution to happen faster. When the Java program is executed, the byte code is interpreted
by JVM. But this interpretation is a slower process. To overcome this difficulty, JRE includes
the component JIT compiler. JIT makes the execution faster.
• Once the bytecode is compiled into that particular machine code, it is cached by the JIT
compiler and will be reused for future needs. Hence the main performance improvement by
using the JIT compiler can be seen when the same code is executed again and again because
JIT makes use of the machine code which is cached and stored.
Java virtual machine (JVM)
• Mostly in other Programming Languages, compiler produce code for a particular system but Java
compiler produce Bytecode for a Java Virtual Machine.
• When we compile a Java program, then bytecode is generated. Bytecode is the source code that
can be used to run on any platform.
• Bytecode is an intermediary language between Java source and the host system.
• It is the medium which compiles Java code to bytecode which gets interpreted on a different
machine and hence it makes it Platform/Operating system independent.
JVM performs following operation
• The JVM performs following operation:
• Loads code
• Verifies code
• Executes code/ Linking the code with the library.
• Provides runtime environment
• JVM provides definitions for the:
• Memory area
• Class file format
• Register set
• Garbage-collected heap
• Fatal error reporting etc.

• JVM generates a .class(Bytecode) file, and that file can be run in any OS, but JVM
• should have in OS because JVM is platform dependent.
Java virtual machine (JVM)

• Java is called platform independent because of Java Virtual Machine.


• As different computers with the different operating system have their JVM,
when we submit a .class file to any operating system, JVM interprets the
bytecode into machine level language.
• VM is the main component of Java architecture, and it is the part of the JRE
(Java Runtime Environment).
• A program of JVM is written in C Programming Language, and JVM is
Operating System dependent.
• JVM is responsible for allocating the necessary memory needed by the Java
program.
• JVM is responsible for deallocating memory space.
JVM : It contains classloader, memory area, execution engine etc.
JVM : Components :
1. Classloader is a subsystem of JVM which is used to load class files. Whenever we
run the java program, it is loaded first by the classloader.
• There are three built-in classloaders in Java.
• Bootstrap ClassLoader: This is the first classloader which is the super class of Extension
classloader. It loads the rt.jar file which contains all class files of Java Standard Edition like
java.lang package classes, java.net package classes, java.util package classes, java.io package
classes, java.sql package classes etc.
• Extension ClassLoader: This is the child classloader of Bootstrap and parent classloader of
System classloader. It loades the jar files located inside $JAVA_HOME/jre/lib/ext directory.
• System/Application ClassLoader: This is the child classloader of Extension classloader. It
loads the classfiles from classpath. By default, classpath is set to current directory. You can
change the classpath using "-cp" or "-classpath" switch. It is also known as Application
classloader.
//Let's see an example to print the classloader name
public class ClassLoaderExample
{
public static void main(String[] args)
{
// Let's print the classloader name of current class.
//Application/System classloader will load this class
Class c=ClassLoaderExample.class;
System.out.println(c.getClassLoader());
//If we print the classloader name of String, it will print null because it is an
//in-built class which is found in rt.jar, so it is loaded by Bootstrap classloader
System.out.println(String.class.getClassLoader());
}
}
Output:
sun.misc.Launcher$AppClassLoader@4e0e2f2a null

These are the internal classloaders provided by Java. If you want to


create your own classloader, you need to extend the ClassLoader class.
JVM : Components :
2) Class(Method) Area
• Class(Method) Area stores per-class structures such as the runtime constant pool, field
and method data, the code for methods.
3) Heap
• It is the runtime data area in which objects are allocated.
4) Stack
• Java Stack stores frames. It holds local variables and partial results, and plays a part in
method invocation and return.
• Each thread has a private JVM stack, created at the same time as thread.
• A new frame is created each time a method is invoked. A frame is destroyed when its method invocation
completes.
5) Program Counter Register
• PC (program counter) register contains the address of the Java virtual machine instruction
currently being executed.
6) Native Method Stack
• It contains all the native methods used in the application.
JVM : Components :
7) Execution Engine : It contains:
1. A virtual processor
2.Interpreter: Read bytecode stream then execute the instructions.
3.Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles
parts of the byte code that have similar functionality at the same time, and
hence reduces the amount of time needed for compilation. Here, the term
"compiler" refers to a translator from the instruction set of a Java virtual machine
(JVM) to the instruction set of a specific CPU.
8) Java Native Interface
• Java Native Interface (JNI) is a framework which provides an interface to
communicate with another application written in another language like C, C++,
Assembly etc. Java uses JNI framework to send output to the Console or interact with
OS libraries.
Difference between C++ and Java

• The main difference between C++ and Java is that C++ is only a compiled language
while Java is both compiled and interpreted.
• The C++ compiler converts the source code into machine code and therefore, it is
platform dependent.
• However, Java source code is converted into bytecode by its compiler and following
that, the Java interpreter executes this bytecode at runtime and produces output.
The fact that Java is interpreted is the reason why it is platform-independent.
Structure of Java Program
Java program structure
• the way to write a java program or general format.
Section Description
Documentation Section You can write a comment in this section. These are optional
Package statement You can create a package with any name. A package is a group of classes that are defined by a name. That is, if
you want to declare many classes within one element, then you can declare it within a package. It is an optional
part of the program, Here, the package is a keyword that tells the compiler that package has been created.It is
declared as:
package package_name;

Import statements This line indicates that if you want to use a class of another package, then you can do this by importing it
directly into your program. Example: import calc.add;
Interface statement Interfaces are like a class that includes a group of method declarations. It's an optional section and can be used
when programmers want to implement multiple inheritances within a program.
Class Definition A Java program may contain several class definitions. Classes are the main and essential elements of any Java
program.
Main Method Class Every Java stand-alone program requires the main method as the starting point of the program. This is an
essential part of a Java program. There may be many classes in a Java program, and only one class defines the
main method. Methods contain data type declaration and executable statements.
Classes and Objects
• The class is the unit of programming
• A Java program is a collection of classes
• Each class definition (usually) in its own .java file
• The file name must match the class name
• A class describes objects (instances)
• Describes their common characteristics: is a blueprint
• Thus all the instances have these same characteristics
• These characteristics are:
• Data fields for each object
• Methods (operations) that do work on the objects

Appendix A: Introduction to Java 81


Grouping Classes: The Java API
• API = Application Programming Interface
• Java = small core + extensive collection of packages
• A package consists of some related Java classes:
• Swing: a GUI (graphical user interface) package
• AWT: Application Window Toolkit (more GUI)
• util: utility data structures (important to CS 187!)
• The import statement tells the compiler to make available classes and
methods of another package
• A main method indicates where to begin executing a class (if it is
designed to be run as a program)

Appendix A: Introduction to Java 82


Simple Java Program • Java code is case sensitive.
• To write a Java program, you must have to
//Name of this file will be "Hello.java" define class first.
• The name of the class in Java (which holds
public class Hello the main method) is the name of the Java
{ program, and the same name will be given
/* Author: www.w3schools.in in the filename. As mentioned above in the
Date: 2018-04-28 sample program; The name of the class is
Description: "Hello" in which the main method is, then
Writes the words "Hello Java" on the screen */ this file will be named "Hello.Java".

public static void main(String[] args)


{
System.out.println("Hello Java");
}
}

Output: Hello Java


A Little Example of import and main
import javax.swing.*;
// all classes from javax.swing
public class HelloWorld { // starts a class
public static void main (String[] args) {
// starts a main method
// in: array of String; out: none (void)
}
}
• public = can be seen from any package
• static = not “part of” an object

Appendix A: Introduction to Java 84


Processing and Running HelloWorld
• javac HelloWorld.java
• Produces HelloWorld.class (byte code)
• java HelloWorld
• Starts the JVM and runs the main method

Appendix A: Introduction to Java 85


References and Primitive Data Types
• Java distinguishes two kinds of entities
• Primitive types
• Objects
• Primitive-type data is stored in primitive-type variables
• Reference variables store the address of an object
• No notion of “object (physically) in the stack”
• No notion of “object (physically) within an object”

Appendix A: Introduction to Java 86


public class Hello •This creates a class called Hello.
•All class names must start with a capital letter.
•The public word means that it is accessible from any other classes.
/* Comments */ The compiler ignores comment block. Comment can be used anywhere in the program to add info about the
program or code block, which will be helpful for developers to understand the existing code in the future
easily.
Braces Two curly brackets {...} are used to group all the commands, so it is known that the commands belong to
that class or method.
public static void main •When the main method is declared public, it means that it can also be used by code outside of its class, due
to which the main method is declared public.
•The word static used when we want to access a method without creating its object, as we call the main
method, before creating any class objects.
•The word void indicates that a method does not return a value. main() is declared as void because it does
not return a value.
•main is a method; this is a starting point of a Java program.
You will notice that the main method code has been moved to some spaces left. It is
called indentation which used to make a program easier to read and understand.
String[] args It is an array where each element of it is a string, which has been named as "args". If your Java program is
run through the console, you can pass the input parameter, and main() method takes it as input.
System.out.println(); This statement is used to print text on the screen as output, where the system is a predefined class,
and out is an object of the PrintWriter class defined in the system. The method println prints the text on the
screen with a new line. You can also use print() method instead of println() method. All Java statement ends
with a semicolon.
Types of Statements in Java
• equivalent to sentences in natural languages.
• a statement is an executable instruction that tells the compiler what
to perform. It forms a complete command to be executed and can
include one or more expressions.
• A sentence forms a complete idea that can include one or more
clauses.
• Types of Statements
• Expression Statements
• Declaration Statements
• Control Statements
Types of Statements in Java : expressions
• Expressions that produce a value.
• For example, (6+9), (9%2), (pi*radius) + 2.
• expression enclosed in the parentheses will be evaluate first, after that rest of the
expression.
• Expressions that assign a value.
• For example, number = 90, pi = 3.14.
• Expression that neither produces any result nor assigns a value.
• For example, increment or decrement a value by using increment or decrement
operator respectively, method invocation, etc.
• These expressions modify the value of a variable or state (memory) of a program.
For example, count++, int sum = a + b; The expression changes only the value
of the variable sum. The value of variables a and b do not change, so it is also a
side effect.
Types of Statements in Java : Declaration Statements
• In declaration statements, we declare variables and constants by specifying their
data type and name. A variable holds a value that is going to use in the Java
program. For example:
int quantity;
boolean flag;
String message;
Also, we can initialize a value to a variable. For example:
int quantity = 20;
boolean flag = false;
String message = "Hello";
• Java also allows us to declare multiple variables in a single declaration
statement. Note that all the variables must be of the same data type.
int quantity, batch_number, lot_number;
boolean flag = false, isContains = true;
String message = "Hello how are you”;
Types of Statements in Java : Control Statement
• Control statements decide the flow (order or sequence of execution of statements) of a
Java program. In Java, statements are parsed from top to bottom. Therefore, using the
control flow statements can interrupt a particular section of a program based on a certain
condition.
Example of Statement

//declaration statement
int number;
//expression statement
number = 412;
//control flow statement
if (number > 10 )
{
//expression statement
System.out.println(number + " is greater than 100");
}
public class Student implements Cloneable { public class Calculattion {
public static void main(String[] args) { public static void main(String[] args) {
int num = 2; // TODO Auto-generated method stub
switch (num){
int sum = 0;
case 0:
System.out.println("number is 0"); for(int j = 1; j<=10; j++) {
break; sum = sum + j;
case 1: }
System.out.println("number is 1"); System.out.println("The sum of first 10 natural numbers is " +
break; sum);
default: }
System.out.println(num); }
}
For Statement
}
} public class Calculation {
SWITCH Case public static void main(String[] args) {
public class Calculation { // TODO Auto-generated method stub
public static void main(String[] args) { String[] names = {"Java","C","C++","Python","JavaScript"};
// TODO Auto-generated method stub
int i = 0; System.out.println("Printing the content of the array names
System.out.println("Printing the list of first 10 even :\n");
numbers \n"); for(String name:names) {
while(i<=10) {
System.out.println(name);
System.out.println(i);
i = i + 2;
}
} } } }
WHILE Statement }
public class Calculation { /A Java Program to demonstrate the use of if-
public static void main(String[] args) { else statement.
// TODO Auto-generated method stub //It is a program of odd and even number.
int i = 0; public class IfElseExample {
System.out.println("Printing the list of first 10 public static void main(String[] args) {
even numbers \n");
do {
//defining a variable
System.out.println(i);
int number=13;
i = i + 2;
//Check if the number is divisible by 2 or not
}while(i<=10);
if(number%2==0){
} System.out.println("even number");
} }else{
DO WHILE Statement System.out.println("odd number");
}
}
}
https://www.javatpoint.com/java-if-else IF ELSE Statement

https://www.javatpoint.com/control-flow-in-java
public class BreakExample {
public class ContinueExample {
public static void main(String[] args) {
public static void main(String[] args) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
for(int i = 0; i<= 10; i++) {
System.out.println(i);
for(int i = 0; i<= 2; i++) {
if(i==6) {
break;
for (int j = i; j<=5; j++) {
}
}
if(j == 4) {
}
continue;
}
}
System.out.println(j);
}
}
}

}
CheckPalindromeNumber.java

import java.util.Scanner;
//imports the Scanner class of the java.util package
public class CheckPalindromeNumber { //class definition
public static void main(String args[]) { //main method
int r, s=0, temp; //variables to be used in program
int x;
//It is the number variable to be checked for palindrome
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number to check: ");
//reading a number from the user
x=sc.nextInt();
//logic to check if the number id palindrome or not
temp=x;
while(x>0) {
r=x%10; //finds remainder
s=(s*10)+r;
x=x/10;
}
if(temp==s)
System.out.println("The given number is palindrome.");
else
System.out.println("The given number is not palindrome."); }
}

You might also like