0% found this document useful (0 votes)
31 views9 pages

JDS Book

The document outlines the evolution and features of the Java programming language, highlighting its platform independence, object-oriented nature, and robust security measures. It details significant releases from J2SE 1.4 in 2002 to Java SE 17, emphasizing Java's portability and high performance. Additionally, it introduces basic Java program structure, including standalone applications and applets, while providing examples of simple Java programs.

Uploaded by

srinidhi
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)
31 views9 pages

JDS Book

The document outlines the evolution and features of the Java programming language, highlighting its platform independence, object-oriented nature, and robust security measures. It details significant releases from J2SE 1.4 in 2002 to Java SE 17, emphasizing Java's portability and high performance. Additionally, it introduces basic Java program structure, including standalone applications and applets, while providing examples of simple Java programs.

Uploaded by

srinidhi
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/ 9

10

Programming with Java


Table 2.1 (Contd.)
Year
Development
2002 J2SE with SDK 1.4 was released.
2004 JZSE with JDK 5.0 (instead of JDK 1.5)WAs released. This is known as J2SE 5.0.
also rems.
2006 Java SE6 was released, With this release. Sun changed the name from J2SE' to Java SE' and
from the version name.
2011 Java SE7was released.

Ihe most striking feature of the language is that it is a platform-neutral language. Java is the .
programming language that is not tied to any particular hardware or operating system. Programs developed
in Java can be executed anywhere on any system. We can callJava as a revolutionary technology because
it has brought in a fundamental shift inhow we develop and use programs. Nothing like this has happened
to the software industry before.

2.2 JAVA FEATURES


The inventors of Java wanted to design a language which could offer solutions to some of the problems
encountered in modern programming. They wanted the language to be not only reliable, portable and
distributed but also simple, compact and interactive. Java can be described with the following attributes:
Java 2 Features Additional Features of Enhancements in Enhancements in Enhancements in
J2SE 5.0 Java SE 6 Java SE7 Java SE 17
"Compiled and " Ease of Development " ScriptingLanguage "Language " Improved support
Interpreted " Scalability and Support Enhancements tools
Platform-Independent Performance " XML Processing and NIO 2.0 Standardized
and Portable Monitoring and Web Services Parallel statements
Object-Oiented Manageability "JDBC 4.0Support Programming New macOS
" Robust and Secure Desktop Client " Annotation-based Dynamic
" Distributed Core XML Support
Rendering
Programming Language Pipeline
"Familiar, Simple and Supplementary character Dynamic Compilation Support " New API for
Small support
" Multithreaded and
Accessing Large
"JDBCRowSet lcons
Interactive
New System
High Performance
and Security
"Dynamic and Extensible Properties
Although the above appears to be alist of buzzwords, they aptly describe the full potential of the
language. These features have made Java the first application language of the World Wide Web. Java will
also become the premier language for general-purpose standalone
applications.
Compiled and Interpreted
Usually acomputer language is either compiled or interpreted. Java combines both
thus making Java a two-stage system First Java compiler these approaches
translates source code into
bytecode instructions. Bytecodes are not machine instructions and therefore, in the what is known as
interpreter generates machine code that can be directly executed by the machinethat second
is
stage, Java
program. We can thus say that Java is both a compiled and an interpreted running the Java
language.
|Platform-Independent and Portable
The most significant contribution of Java over other
moved from one computer system to another, anywhere languages is its portability.Java programs can be easIly
and anytime. Changes and upgrades in operating
systems, processors and system resources Will not Torce any changes in Java
why Java has become a popular language tor programming on Internet which proarams This is the reason
interconnects diferent kinds
Java Evolution 11

of systems worldwide. We can download a Java applet from a remote computer onto our local system via
Intemet and execute it locally. This makes the Internet an extension of the user's basic system providing
practically unlimited number of accessible applets and applications.
Java ensures portability in two ways. First, Java compiler generates bytecode instructions that
can be implemented on any machine. Secondly, the size of the primitive data types are machine
independent.

Lobject-Oriented
Java is atrue object-oriented language. Almost everything in Java is an object. All program code and data
Teside within objects and classes. Java comes with an extensive set of classes, arranged in packages, that
we can use in our program_ by inheritance. The object model in Java is simple andeasy to extend.
Robust and Secure
Java is a robust language. It provides many safeguards to ensure reliable code. It has strict compile
time and run time checking for data types It is designed as a garbage-collected language relieving the
programmers virtually all memory management problems. Java also incorporates the concept of exception
handling which captures serious errors and eliminates any risk of crashing the system.
Security becomes an important issue for a language that is used for programming on Internet.Threat
of viruses and abuse of resources are everwhere. Java systems not only verify all memory aCceSs but
also ensure that no viruses are communicated with aD applet/The absence of pointers in Java ensures that
programs cannot gain access to memory locations without proper authorization.
Distributed
Java is designed as a distributed language for creating applications on networks. It has the ability to share
Doth data and programs. Java applications can open and access remote objects on Internet as easily as
they can do in a local system. This enables multiple programmers at multiple remote locations to collaborate
and work together on a single project.

Simple, Smalland Familiar


Java is asmall and simple language Many features of Cand C++ that are either redundant or sources of
unreliable code are not part of Java. Fer-exemple, Java does not use pointers, preprocessor header fles,
goto statement and many others] It also eliminates operator overloading and multiple inheritance. For more
detailed comparison of Java wIthCand C++, refer to Section 2.3.
Familiarity is another striking feature of Java. To make the language look familiar to the existing
programmers, it was modeled on C and C++ languagesJava uses many constructs of C and C++ and
therefore, Java code "looks like aC+4" code. In fact, Java is asimplified version of C++.

Multithreaded and Interactive


Multithreaded means handling multiple tasks simultaneously. Java supports multithreaded programs.This
means that we need not wait for the application to finish one task before beginning another For example,
we can listen to an audio clip while scrolling a page and at the same time download an applet from a
distant computer. Thís feature greatly improves the interactive performance of graphical applications.
The Java runtime comes with tools that support multiprocess synchronization and construct smoothly
running interactive systems.
High Performance
Java performance is impressive for an interpreted language, mainly due to the use of intermediate bytecode
According to Sun, Java speed is comparable to the native C/C++. Java architecture is also designed to
reduce overheads during runtime. Further the incorporation of multireading enhances the overall execution
speed of Java programs.
3 Overview of Java
Language
KEY TERMS
Re ldentifier I main I putblic I static void string Iargs I println | double I Math |
sqrt I package
ionort IInterface lOkens Literals Operators | Separators I Unicode I Keyword I Statement IVirtual
ihine ICommand Line Arguments IFreeform I Classes and their relationships | Inheritance Association
I
JAogregation Composition IRealization I UML Notations

3.1 INTRODUCTION
Lava is a general-purpose, object-oriented programming language. We can develop two types of Java
programs:
1, Standalone applications
2. Web applets
They are implemented as shown in Fig. 3.1.(Standalone applications are programs writen in Java to
cary out certain tasks on a standalone local compute In fact, Java can be used to develop programs

Java
Source
Code

Java
Compiler

Applet Application
Type Type

Java enabled Java


Web Browser Interpreter

Output Output

Fig. 3.1 Two ways of using Java


24 Programming with Java
like C and C++
for all kinds of applications, which earlier, were developed using languages AS ia
out earlier, HotJava itself is a Java application programExecuting a stanoalone dava
two steps:
program pointey
1. Compilingsource code into bytecode using javac compiler.
2. Executing the bytecode program using java interpreter/
programs developed for Internet applications. An applet located on
Applets are smal Java lnternet executed on a local computer (Client)
and everything from simple animated graphics h
acomputer
Java-capable browser
(Servern) can developvia
can be We downloaded applets for doing
Complex games and utilities. Since applets are embedded in an HTML (Hypertext Markup Language
document and run inside a Web page, creating and running applets are more complex than Creating an

Standalone programs can read and write files and perform certain operations that applets cannot do. An
application.

applet can only run within a Web browser. which Would


shall consider some simple application programs, demonstrate
In this chapter, we application programs. We shall also discusS here the basic elements of
the
dieva
general structure of Java application program. Creation of applets will be
in executing a Java
language and steps involved

main kunutin n owa


later in Chapter 14.

3.2 SIMPLE JAVA PROGRAM


and execute them
to write a few simple example programs
The best way to learn a new language is output.
of text as
begin with avery simple program that prints a line

Program 3.1 Asinp tolltuwg ga


9class Sample One

public static void main (String args [ )

C+ + .");
System. out .println ("Java is better than

salient features
Program 3.1 is perhaps the simplest of all Java programs. Nevertheless, it brings out some
understand the unigue features that
of the language. Let us therefore discuss the program line by line and
constitute a Java program.

Class Declaration
The first Iine
class SampleOne
declares a class, which is an object-oriented construct As stated earlier, Java is atrue object-oriented
language and therefore, everything must be placed Tnside a classclass is a keyword and declares that
anew class/definition follows. SampleOne is a Java identiier that specifies the name of the class to be
defined.
25
Overview of Java Language

OpeningBrace
class definition in Java matching closing brace "}.
Every inthelast line in thebegina
appeaing
wit h an
example, Thia opening
s similerbreca "" class
to C++ and enda with a(Note
Construct. that a class definition
ends with a sermicolon)
inCt+
The Main Ling
Thethirdline
nublic static void maln (8Ling aqa )
asfines a method named main Concoptually, this is similar to the main) function in C/C++. Every Java
application program must include the maln( ) method, This Is the starting point for the interpreter to begin
execution of the program. A Java application can have
the any number of classes but only one of them
mustinclude a main method to initiate the execution. (Note that Java applets will not use the main method
aall)
This line contains anumber of keywords, public, static and void.
Public: The keyword public is an access specifier that declares the ma1n
method as unprotected and therefore making ít accessible to all
other classes. This is s imilar. to the C++ public modifier.
Static: Next appears the keyword static, which declares this method as one
that belongs to the entire class and not a part of any objectsS OL
the class The main must always be declared as static since the
interpreter uses this method before any objects are created. More
about static methods and variables will be discussed later
in Chapter 8.
Void: The type modifier void states that the main method does not return
any value (but simply prints some text to the screen.)
All parameters to a method are declared inside a pair of parentheses. Here, String args[] declares a
parameter named args, which contains an array of objects of the class type String. 2

The Output Line 2


The only executable statement in the program is
System. out .println ("Java is better th¡n C+t.")
is a true obiect
This is similar to the printf( ) statement of C or cout << construct of C++, Since Java
member of the out
oriented language, every method must be part of an object The println method is a
Object,which is a static data member of System class. This line prints the string
Jaya is better than C++.
to the end of the string. This
10 the screen.Jhe method printin always appends a newline character
at the end of the statement.
means that any subsequent output will start on a new line. Note the semicolon
program are
Every Java statement must end with a semicolon. (Saving, compiling, and executing a Java
discussed in Section 3.8)

3.3 MORE OF JAVA


accomplish
ASSume that we would like to compute and print the square root of a number. A Java program to
nis is shown in Proaram 3.2. This is aslightly complex program. This program when compiled and run
produces the output
y = 2. 23607
Overiew of Java Language 27

3.4 AN
APPLICATION WITH TWO CLASSES
Both the examples discussed above use
will generally require multiple onlv one class that contains the main
classes. Program 3.3 illustrates a Java method. Area-ite appicatron
application with Wo classes.
Program 3.3 Aprogram with multiple classes
class Roam

float lenath:
loat breadth;
oid getdata (float a float b)

length = a;
breadth = b;

de: not (ha4c


class RoomArea
alva
public static void main (String argsi 1) ( w t T
float area;
Room rooml = new Room ( ):
/ Creates an object rooml
rooml.getdata (14, 10) ; 7/ Assigns values to length and
area = breadth
rooml.length *
rooml. breadth;
System. out. println ("Area =" + area) ;
Lystatcnt to Pnt m
) nnt lme
Program 3.3 defines two classes Room and RoomnArea. The Room class
defines two variables and one
method to assign values to these variables. The class RoomArea contains the
the execution.
main method that initiates
The main method declares a local variable area and a Room type
obiect room1 and then assigns values
to the data members of Room class by using the getdata method. Finally, it
calculates the area and prints
the results. Note the use of dot operator to access the variables and methods of
Room class. Classes and
methods are discussed in Chapter 8. The use of the keyword new is explained later in this Chapter.
shuctwe hypucat
3.5 JAVAPROGRAM STRUCTURE3 Dsbe he
As we have seen in the previous examples, a Java program may contain many classes of which only
one class defines a.main method. Classes contain data members and methods that operate on the data
members of the class. Methods may contain data type declarations and executable statements. To write a
Java program, we first define classes and then put them together. AJava program may contain one or more
sections as shown in Fig. 3.2.

Documentation Section
The documentation section comprises a set of comment lines giving the nane of the program, the author
and other details, which the programmer would like to refer to at a later stage Comments must explain why
28 Programming with Java

and what of classes and how of algorithms. This would greatly help in maintaining the program.
to the twO styles of comments discussed earlier, Java also uses a third style of comment /** In
documentation comment, This form of comment is used for generating documentation automaticall.
addlir.
Documentation Section Suggested

Package Slatement Optional

Import Statements Optional

Interface Slatements Optional

Class Definitions Optional

Main Method Class


Essential
Main Method Definition

Fig. 3.2General structure of a Java program

Package Statement
a package
The first statement allowed in a Java file is a package statement. This statement declares
name and informs the compiler that the classes defined here belong to this package. Example:
package student;

The package statement is optional That is, our classes do not have to be part of package. More abou
packages will be discussed in Chapter 11.

Import Statements
The next thËng after apackage statement (but before apy class definitions) may be a number of import
statemeFts.This is similar to the #include statement in CExample:
import student.test;
This statement instructs the interpreter to load the test class contained in the package student/ Using
import statements, we can have access to classes that are part of other named packages. More on import
statements in Chapter 11.
(o) this sjatint nport al nput
Interface Statements
buput metti
3 An interface is like a class but includes a group of method declarations. This is also an optional
section and
feature in the program. Interface is a new
is used only when we wish to implement the multiple inheritance
10.
concept in Java and is discussed in detail in Chapter
3 Class Definitions
elements of a
A Java program may contain multiple class definitions. Classes are the primary and essential
Java program These classes are used to map the objects of real-world problems. The number of classes
used depends on the complexity of the problem.
Overview of Java Language 29

S|Main Method Class


Since every Java standalone progranm requires a main method as its starting point, this
class is the
part of a Java program. Asimple Java program may contain onlv this part. The main method createsessenual
of various classes and establishes communications between them On ObjeGis
program terminates and the control passes back to the reaching the end of main, tne
operating systerr?
3.6 JAVA TOKENS4) Eplain abut Java tokenslo) wtat ae
AJava program is basically a collection of classes, A class is defined by a set of
and methods containing executable statements (see Fig, 3.3). Most statements declaration statements
contain expressions, which
describe the actions carried out on data. Smallest individual units in a program are known as
compiler recognizes them for building up expressions and statements. tokens| The
In simple terms, a Java program is a collection of tokens,
includes five types of tokens. They are:
comments and white spaces. Java language
1. Reserved Keywords
2. Identifiers
3. Literals
4. Operators
5. Separators 4
Java Character Set
The smallest units of Java language are the characters used to write Java tokens. These characters are
defined by the Unicode character set, an emerging standard that tries to create characters for a large
number of scripts worldwide.

Tokens

Declaration statement
Variables
Section
Declaration statement

Tokens
Method 1

Expressions and
Statements

Tokens
Method 2 Methods
Section

Fig. 3.3 Elements of Java class


30 Programming with Java

The Unicode is a 16-bit character coding system and currently supports more than 34,000
characters derived from 24 languages from America, Europe, Middle East, Africa and Asia (includingdefinen
However, most of us use only the basic ASCIl characters, which include letters, digits and punch
marks, used in nomal English. We, therefore, have used only ASCIl character set (a subset of UNICo
character set) in developing the programs in this book.
4 Keywords
Keywords are an essential part of a langquage definition, They implement specitic teatures of the languan
Java language has reserved 50 words as kevwords. Table 3.1 lists these keywords. These keywor
combined with operators and separators according to a syntax, form definition of the Java language
Understanding the meanings of al these words is important for Java programmers.
Since keywords have specific meaning in Java, we cannot use them as names for variables, classe.
methods, and so on All keywords are to be written in lower-case letters. Since Java is case-sensitive. ona
can use these wOTOS as identifiers by changing one or more letters to upper cáse. However, it is a ba4

pracice and should be avoided. writa ay 6 rmn lalte 3I


Identifiers
methods, variables, obiects
ldentifiers are prOgrammer-designed tokens. Thev are used for naming classes,
labels, packages and intefaces in a program. Java identifiers folow the following rules:
characters.
1. They can have alphabets, digits, and the underscore and dollar sign
2. They must not begin with a digit.
3. Uppercase and lowercase letters are distinct.
4. They can be of any length.

Table 3.1 Java Keywords


assert boolean break
abstract
catch char
case
byte
continue default
Const
class
else enum
do double
final finally float
extends
goto if implements
for
instanceof int interface
import
native new package
long
protected public return
private
short static strictfp super
synchronized this throw
switch
transient try Void
throws
volatile while

Note: VWe should also not attempt to use the boolean values true and false of null as names in our programs.

ldentifier must be meaningful, short enough to be quickly and easily typed and long enough to be
descriptive and easily read. Java developers have followed some naming conventions.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy