chapter-1-java
chapter-1-java
2
History of Java
• In 1991, a research group working as part of Sun Microsystems's "Green" project
headed by James Gosling was developing software to control consumer electronic
devices. The goal was to develop a programming language that could be used to
develop software for consumer electronic devices like TVs, VCRs, toasters, and the
like. As a result the team announced a new language named ―Oak.
• In 1992, the team demonstrated the application of their new language to control a
list of home applications using a hand-held device with a tiny touch-sensitive
screen.
• In 1994, the members of the Green project developed a World Wide Web (WWW)
browser completely in Java that could run Java applets. The browser was originally
called WebRunner, but is now known as HotJava.
• In 1995, Oak was renamed ―Java due to some legal snags. Many popular
companies including Netscape and Microsoft announced their support to Java.
3
Cont.….
• In 1997, Sun released the Servlet API, which revolutionized server-side Web
development.
• In 1999, Sun released the first version of the Java 2, Enterprise Edition (J2EE)
specification that included Java Server Pages (JSP) and Enterprise JavaBeans
(EJB) in a highly distributed enterprise middleware.
4
Java Buzzwords
Simple
Java syntax is similar to C and C++. However, most of the poorly used and
confusing parts form C++ are omitted or managed. For example pointer for
handling memory in C or C++ is not there in Java and it handles memory
automatically, and similarly, structs and typedef constructs are removed. So we say
that Java is simple to learn and simple to implement.
Object Oriented
Java is a true object-oriented programming language that supports encapsulation,
inheritance, and polymorphism. Almost everything in Java is an object. Since it is
object oriented, everything but the primitive data types is represented as class and
its instances and members.
5
Distributed
Java is designed as a distributed language for creating applications on networks. So,
application development for running in multiple machines to run concurrently and
interact with each other using java is very easy and efficient.
Robust
Java is a robust language. It provides many safeguards to ensure reliable code. It has
strict compile time and run time code checking. It handles all memory management
problems and also incorporates strong garbage collection facility.
Secure
Since Java was intended to work in the distributed environment, security was the issue
that was taken care. For example, applets running in a Web browser cannot access a
Web client's underlying file system or any other Web site other than that from which it
originated and all Java programs run in a virtual machine that protects the underlying
operating system from harm. Similarly the series of test and restriction of memory
manipulation also secure the application. Also, the absence of pointers in Java ensures
that programs cannot gain access to memory locations without proper authorization.6
Architecture Neutral
Since Java runs inside of a Virtual Machine (a program written in operating system
specific code that provides a common front-end to all operating systems), the program
does not depend on the underlying operating system or hardware.
Portable
The phrase write once, run anywhere is the major concept for the portability that Java
adheres by compiling Java code into byte-code, which then is interpreted by Virtual
Machine to operating system–specific instructions. Because of this, any Java code that
you write and compile into byte-code will run on any operating system for which there
exists a compatible Virtual Machine.
Compiled and Interpreted
Usually a computer language is either compiled or interpreted. Java combines both
these approaches thus making Java a two-stage system. First, Java compiler translates
source code into what is known as bytecode instructions. Bytecodes are not machine
instructions and therefore, in the second stage, Java interpreter generates machine code
that can be directly executed by the machine that is running the Java program. 7
High Performance
Though we say Java programs are interpreted, we cannot say that java does not have
high performance. The performance gain is due to the JIT (Just In Time) compilation
that cache the recurring process to speed up the interpretation.
Multithreaded
Java allows multithreading such that the applications have the capability to run
multiple things at the same time for e.g. writing a report and checking the spellings at a
time.
Dynamic and Extensible
Java is dynamic since it is capable of dynamically linking in new class libraries,
methods or functions, and objects.
Java programs support native methods. Native methods are the functions written in
other languages such as C and C++. This feature enables the programmers to use the
efficient functions available in languages other than Java. Native methods are linked
dynamically at runtime.
8
1.2. Object Oriented Programming
9
Object Oriented Programming
The fundamental idea behind object-oriented programming is to combine both states (also
called data or fields or attributes) and behaviors (also called functions or methods) that
operate on that data into a single unit. This unit is called an object. The data is hidden, so it
is safe from accidental alteration. An object‘s methods typically provide the only way to
access its data. In order to access the data in an object, we should know exactly what
methods interact with it. No other methods can access the data. Hence OOP focuses on
data portion rather than the process of solving the problem.
An object-oriented program typically consists of a number of objects, which
communicate with each other by calling one another‘s methods. This is called sending a
message to the object. This kind of relation is provided with the help of communication
between two objects and this communication is done through information called message.
In addition, object-oriented programming supports encapsulation, abstraction,
inheritance, and polymorphism to write programs efficiently. Some examples of
objectoriented programming language include Java, Simula, Smalltalk, C++, Python, C#,
Visual Basic .NET.
10
Classes and Objects
The concept of classes and objects is the heart of the OOP. A class is a framework that
specifies what data and what methods will be included in objects of that class. It serves
as a plan or blueprint from which individual objects are created. An object is a software
bundle of related data and methods created from a class. For example we can think of
the class Students. This class has some properties like name, address, marks, grade,
and so on. Similarly it can have the methods like findPercentage(), findGPA(), etc.
Now here we can see that from this class, we can create any number of objects of the
type Students. In programming we say that an object is an instance of the class.
Abstraction
Abstraction is the essence of OOP. Abstraction means the representation of the
essential features without providing the internal details and complexities. In OOP,
abstraction is achieved by the help of class, where data and methods are combined to
extract the essential features only. For example, if we represent chair as an object it is
sufficient for us to understand that the purpose of chair is to sit. So we can hide the
details of construction of chair and things required to build the chair. 11
OOP Principles
The three basic concepts underlying OOP are: encapsulation, inheritance, and
polymorphism.
Encapsulation
Encapsulation is the process of combining the data and methods into a single framework
called class. Encapsulation helps preventing the modification of data from outside the
class by properly assigning the access privilege to the data inside the class. So the term
data hiding is possible due to the concept of encapsulation, since the data are hidden
from the outside world.
Inheritance
Inheritance is the process of acquiring certain attributes and behaviors from parents. For
examples, cars, trucks, buses, and motorcycles inherit all characteristics of vehicles.
Object-oriented programming allows classes to inherit commonly used data and
functions from other classes. If we derive a class (called super class) from another class
(called sub class), some of the data and methods can be inherited so that we can reuse
the already written and tested code in our program, simplifying our program. 12
Polymorphism
Polymorphism means the quality of having more than one form. The representation
of different behaviors using the same name is called polymorphism. However the
behavior depends upon the attribute the name holds at particular moment. For
example if we have the behavior called communicate for the objects vertebrates,
then the communicate behavior applied to objects say dogs is quite different from
the communicate behavior to objects human. So here the same name communicate
is used in multiple process one for human communication, what we simply call
talking. The other is used fro communication among dogs, we may say barking,
definitely not talking.
13
1.3. Java Development Kit
14
JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine
because it doesn't physically exist. It is a specification that provides a runtime
environment.
JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE.
The Java Runtime Environment is a set of software tools which are used for
developing Java applications. It is used to provide the runtime environment.
JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is
a software development environment which is used to develop Java applications and
applets. It physically exists. It contains JRE + development tools.
15
1.4. A First Simple Java Program
First Java Program
o class keyword is used to declare a class in Java.
o public keyword is an access modifier that represents visibility. It means it is
visible to all.
o static is a keyword. If we declare any method as static, it is known as the static
method. The core advantage of the static method is that there is no need to create an
object to invoke the static method. The main() method is executed by the JVM, so it
doesn't require creating an object to invoke the main() method. So, it saves memory.
o void is the return type of the method. It means it doesn't return any value.
o main represents the starting point of the program.
o String[] args or String args[] is used for command line argument.
o System.out.println() is used to print statement. Here, System is a class, out is an
object of the PrintStream class, println() is a method of the PrintStream class.
16
Writing Your First Java Program
Here is the simple program in java and this can be written in any available text
editors like notepad, WordPad, etc.
1. public class Welcome
2. {
3. public static void main(String[]args)
4. {
5. System.out.println("NBPI");
6. }
7. }
17
Compiling Your First Java Program
Write the above code and save it as a filename Welcome.java (remember Capital
‘W’). Open a command prompt and navigate to the folder where you saved your
Welcome.java file. You are ready to compile here. To compile the java file use the
tool “javac” that comes along with Java 2 SDK as shown below:
javac Welcome.java
When this is done there are two possibilities: either there is no message and the
prompt appears or there are messages that show the errors. If there are errors, your
program will not compile and you must correct them to run the program.
Running Your First Java Program
After the successful compilation of Welcome.java, Welcome.class file is created.
This is the file that contains the byte-code. To run Welcome, type the following
from a command prompt in the folder that holds Welcome. class.
java Welcome
The result should be displayed to the screen as NBPI. 18
Understanding Your First Java Program
Line 1: public class Welcome
A new class called Welcome is being defined. You can create new classes by using
the keyword class followed by a name for the class.
Lines 2, 7 and 4, 6: the brace pair { and }
Define the body of the Welcome class by pair 2 and 7 i.e. everything that is
included between lines 2 and 7 is part of the Welcome class. Similarly body of the
main method is defined by lines 4 and 6.
Line 3: public static void main( String[] args )
It defines a method, or function, that is a member of the Welcome class called main.
main is the entry point for java applications that is run using a tool java. Let's
closely look at the sub parts in the method:
19
public
The keyword public is known as an access modifier; an access modifier defines who can
and cannot see this method (or variable.) There are three possible values for access
modifiers: public, protected, and private, each having their own restrictions, which we will
cover later. In this case, it is saying that this function, main, is publicly available to anyone
who wants to call it. This is essential for the main function; otherwise the Java Runtime
Engine would not be able to access the method, and hence could not launch our
application.
static
The static keyword tells the compiler that there is one and only one method (or
variable) to be used for all instances of the class. This functionality will be explained more
later, but for now remember that main functions have to be static in a class.
void
The term void refers to the return type. Method can return values; for example, integers,
floating-point values, characters, strings, and more. If a function does not return any value,
it is said to return void. In this declaration it is saying that the main function does not
20
return a value.
main
The word main is the name of the function. As previously mentioned, main is a special
function that must be defined when writing a Java application. It is the entry-point into
your class that the Java Runtime Engine processes when it starts; it will control the flow
of your program.
( String[] args )
The portion enclosed in parentheses next to the function name is the parameter list passed
to the method. You can pass any type of data for that method to work with. In this case, the
main method accepts an array (a collection or set of items) of String objects that represent
the command-line arguments the user entered when he launched the application. See
below for explanation: java Welcome one two three four
The command line then would have four items sent to it: one, two, three, and four. The
variable arguments would contain an array of these four strings as:
args[0] = "one"
args[1] = "two"
args[2] = "three"
21
args[3] = "four"
Line 5: System.out.println( "NBPI" );
Let's break apart this statement:
System
System is actually a class that the Java language provides for you. This class is used to
access the standard input (keyboard), standard output (monitor), and standard error
(usually a monitor unless you have a separate error output defined).
out
The System class's out property (represents output device) is defined as follows:
public static final PrintStream out
All the keywords used have usual meaning. The final keyword says that this variable
cannot change in value. The PrintSteam class contains a collection of print, println,
and write methods that know how to print different types of variables This is how
println can print out so many different types of values.
println
This is the method of PrintStream class that prints the content passed as a parameter
adding new line in it.
22