java final material

141
1 6,7(2 nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 32090290 3 rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499 Lesson 1: Object-Oriented Programming Concepts If you've never used an object-oriented programming language before, you'll need to learn a few basic concepts before you can begin writing any code. This lesson will introduce you to objects, classes, inheritance, interfaces, and packages. Each discussion focuses on how these concepts relate to the real world, while simultaneously providing an introduction to the syntax of the Java programming language. Object-Oriented Programming Concepts : What Is an Object? Objects are key to understanding object-oriented technology. Look around right now and you'll find many examples of real-world objects: your dog, your desk, your television set, your bicycle. Real-world objects share two characteristics: They all have state and behavior. Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail). Bicycles also have state (current gear, current pedal cadence, current speed) and behavior (changing gear, changing pedal cadence, applying brakes). Identifying the state and behavior for real-world objects is a great way to begin thinking in terms of object- oriented programming. Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields (variables in some programming languages) and exposes its behavior through methods (functions in some programming languages). Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication. Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation a fundamental principle of object-oriented programming. Consider a bicycle, for example: By attributing state (current speed, current pedal cadence, and current gear) and providing methods for changing that state, the object remains in control of how the outside world is allowed to use it. For example, if the bicycle only has 6 gears, a method to change gears could reject any value that is less than 1 or greater than 6. Bundling code into individual software objects provides a number of benefits, including: 1. Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Once created, an object can be easily passed around inside the system. 2. Information-hiding: By interacting only with an object's methods, the details of its internal implementation remain hidden from the outside world. 3. Code re-use: If an object already exists (perhaps written by another software developer), you can use that object in your program. This allows specialists to implement/test/debug complex, task-specific objects, which you can then trust to run in your own code.

Upload: sneha

Post on 07-Feb-2016

27 views

Category:

Documents


0 download

DESCRIPTION

java book

TRANSCRIPT

Page 1: Java Final Material

1 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Lesson 1: Object-Oriented Programming Concepts

If you've never used an object-oriented programming language before, you'll need to learn a few basicconcepts before you can begin writing any code. This lesson will introduce you to objects, classes,inheritance, interfaces, and packages. Each discussion focuses on how these concepts relate to the real world,while simultaneously providing an introduction to the syntax of the Java programming language.

Object-Oriented Programming Concepts:

What Is an Object?Objects are key to understanding object-oriented technology. Look around right now and you'll find manyexamples of real-world objects: your dog, your desk, your television set, your bicycle.Real-world objects share two characteristics: They all have state and behavior. Dogs have state (name, color,breed, hungry) and behavior (barking, fetching, wagging tail). Bicycles also have state (current gear, currentpedal cadence, current speed) and behavior (changing gear, changing pedal cadence, applying brakes).Identifying the state and behavior for real-world objects is a great way to begin thinking in terms of object-oriented programming.

Software objects are conceptually similar to real-world objects: they too consist of state and related behavior.An object stores its state in fields (variables in some programming languages) and exposes its behaviorthrough methods (functions in some programming languages). Methods operate on an object's internal stateand serve as the primary mechanism for object-to-object communication. Hiding internal state and requiringall interaction to be performed through an object's methods is known as data encapsulation — a fundamentalprinciple of object-oriented programming.Consider a bicycle, for example:By attributing state (current speed, current pedal cadence, and current gear) and providing methods forchanging that state, the object remains in control of how the outside world is allowed to use it. For example, ifthe bicycle only has 6 gears, a method to change gears could reject any value that is less than 1 or greater than6.Bundling code into individual software objects provides a number of benefits, including:

1. Modularity: The source code for an object can be written and maintained independently of the sourcecode for other objects. Once created, an object can be easily passed around inside the system.2. Information-hiding: By interacting only with an object's methods, the details of its internalimplementation remain hidden from the outside world.3. Code re-use: If an object already exists (perhaps written by another software developer), you can usethat object in your program. This allows specialists to implement/test/debug complex, task-specific objects,which you can then trust to run in your own code.

Page 2: Java Final Material

2 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

4. Pluggability and debugging ease: If a particular object turns out to be problematic, you can simplyremove it from your application and plug in a different object as its replacement. This is analogous to fixingmechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine.

What Is a Class?In the real world, you'll often find many individual objects all of the same kind. There may be thousands ofother bicycles in existence, all of the same make and model. Each bicycle was built from the same set ofblueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle isan instance of the class of objects known as bicycles. A class is the collection of individual objects.What Is Inheritance?Different kinds of objects often have a certain amount in common with each other. Mountain bikes,road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed,current pedal cadence, current gear). Yet each also defines additional features that make themdifferent: tandem bicycles have two seats and two sets of handlebars; road bikes have drophandlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio.

Object-oriented programming allows classes to inherit commonly used state and behaviorfrom other classes. In this example, Bicycle now becomes the superclass of MountainBike,RoadBike, and TandemBike. In the Java programming language, each class is allowed to haveone direct superclass, and each superclass has the potential for an unlimited number of subclasses:

A hierarchy of bicycle classes.

The syntax for creating a subclass is simple. At the beginning of your class declaration, usethe extends keyword, followed by the name of the class to inherit from:

class MountainBike extends Bicycle{// new fields and methods defining a mountain bike would go

here}

This gives MountainBike all the same fields and methods as Bicycle, yet allows its codeto focus exclusively on the features that make it unique. This makes code for your subclasseseasy to read. However, you must take care to properly document the state and behavior thateach superclass defines, since that code will not appear in the source file of each subclass.

What Is Data Abstraction and Encapsulation?The wrapping up of data and function into a single unit (called class) is known as encapsulation. Dataencapsulation is the most striking feature of a class. The data is not accessible to the outside world, and onlythose functions, which are wrapped in the class, can access it. These functions provide the interface betweenthe object’s data and the program. This insulation of the data from direct access by the program is called datahiding or information hiding.Abstraction refers to the act of representing essential features without including the background details orexplanations. Classes use the concept of abstraction and are defined as a list of abstract attributes such as size,weight and cost and functions to operate on these attributes. They encapsulate all the essential properties of

Page 3: Java Final Material

3 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

the objects that are to be created. The attributes are sometimes called data members because they holdinformation. The functions that operate on these data are sometimes called methods or member functions.Since the classes use the concept of data abstraction, they are known as abstract data types (ADT).What Is Polymorphism?Polymorphism is another important OOP concept. Polymorphism, a Greek term, and means the ability to takemore than one form. An operation may exhibit different behaviors in different instances. The behaviordepends upon the types of data used in the operation. For example, consider the operation of addition. For twonumbers, the operation will generate a sum. If the operands are strings, then the operation would produce athird string by concatenation. The process of making an operator to exhibit different behaviors in differentinstances is known as operator overloading.Polymorphism plays an important role in allowing objects having different internal structures to share thesame external interface. This means that a general class of operations may be accessed in the same mannereven thought specific actions associated with each operation may differ. Polymorphism is extensively used inimplementing inheritance.What Is Dynamic Binding?Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamicbinding (also known as late binding) means that the code associated with a given procedure call is not knownuntil the time of the call at run-time. It is associated with polymorphism and inheritance. A function callassociated with a polymorphic reference depends on the dynamic type of that reference.

Every object will have this procedure. Its algorithm is, however, unique to each object and so the drawprocedure will be redefined in each class that defines the object. At run-time, the code matching the objectunder current reference will be called.

What Is Message passing?An object-oriented program consists of set of objects that communicate with each other, The process ofprogramming in an object-oriented language, therefore, involves the following basic steps:

1. Creating classes that define objects and their behavior,2. Creating objects from class definitions, and3. Establishing communication among objects.

Objects communicate with one another by sending and receiving information much the same way aspeople pass messages to one another. The concept of message passing makes it easier to talk about buildingsystems that directly model or simulate their real-world counterparts.

A message for an object is a request for execution of a procedure, and therefore will invoke a function(procedure) in the receiving object that generates the desired result. Message passing involves specifying thename of the object, the name of the function (message) and the information to be sent.

Objects have a life cycle. They can be created and destroyed. Communication with an object is feasibleas long as it is alive.What Is an Interface?As you've already learned, objects define their interaction with the outside world through the methods thatthey expose. Methods form the object's interface with the outside world; the buttons on the front of yourtelevision set, for example, are the interface between you and the electrical wiring on the other side of itsplastic casing. You press the "power" button to turn the television on and off.In its most common form, an interface is a group of related methods with empty bodies. A bicycle'sbehavior, if specified as an interface, might appear as follows:

Page 4: Java Final Material

4 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

interface Bicycle {

void changeCadence(int newValue);

void changeGear(int newValue);

void speedUp(int increment);

void applyBrakes(int decrement);}To implement this interface, the name of your class would change (to ACMEBicycle, forexample), and you'd use the implements keyword in the class declaration:class ACMEBicycle implements Bicycle{

// remainder of this class implemented as before}

Implementing an interface allows a class to become more formal about the behavior it promises to provide.Interfaces form a contract between the class and the outside world, and this contract is enforced at build timeby the compiler. If your class claims to implement an interface, all methods defined by that interface mustappear in its source code before the class will successfully compile.

Note: To actually compile the ACMEBicycle class, you'll need to add the public keyword to thebeginning of the implemented interface methods. You'll learn the reasons for this later in the lessons onClasses and Objects and Interfaces and Inheritance.

What Is a Package?A package is a namespace that organizes a set of related classes and interfaces. Conceptually you can think ofpackages as being similar to different folders on your computer. You might keep HTML pages in one folder,images in another, and scripts or applications in yet another. Because software written in the Javaprogramming language can be composed of hundreds or thousands of individual classes, it makes sense tokeep things organized by placing related classes and interfaces into packages.The Java platform provides an enormous class library (a set of packages) suitable for use in your ownapplications. This library is known as the "Application Programming Interface", or "API" for short. Itspackages represent the tasks most commonly associated with general-purpose programming. For example, aString object contains state and behavior for character strings; a File object allows a programmer toeasily create, delete, inspect, compare, or modify a file on the filesystem; a Socket object allows for thecreation and use of network sockets; various GUI objects control buttons and checkboxes and anything elserelated to graphical user interfaces. There are literally thousands of classes to choose from. This allows you,the programmer, to focus on the design of your particular application, rather than the infrastructure required tomake it work.The Java Platform API Specification contains the complete listing for all packages, interfaces, classes,fields, and methods supplied by the Java Platform 6, Standard Edition. Load the page in your browser andbookmark it. As a programmer, it will become your single most important piece of referencedocumentation.

Questions and Exercises:1. A software object's state is stored in ___.2. A software object's behavior is exposed through ___.3. Hiding internal data from the outside world and accessing it only through publicly exposedmethods is known as data ___.4. A blueprint for a software object is called a ___.

Page 5: Java Final Material

5 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

5. Common behavior can be defined in a ___ and inherited into a ___ using the ___ keyword.6. A collection of methods with no implementation is called an ___.7. A namespace that organizes classes and interfaces by functionality is called a ___.8. The term API stands for ___?

Exercises:1. Create new classes for each real-world object that you observed at the beginning of this trail.Refer to the Bicycle class if you forget the required syntax.2. For each new class that you've created above, create an interface that defines its behavior, andthen require your class to implement it. Omit one or two methods and try compiling. What does theerror look like?

Lesson 2: Java EvolutionJava Features

The inventors of java wanted to design a language which could offer solutions to some of the problemsencountered in modern programming. They wanted the language to be not only reliable, portable anddistributed but also simple, compact and interactive. Sun Microsystems officially describes java with thefollowing attributes:

Java 2 features Additional features of J2SE 5.0 Compiled and interpreted Platform independent and portable Object-Oriented Robust and Secure Distributed Familiar, Simple and Small Multithreaded and Interactive High Performance Dynamic and extensible

Ease of development Scalability and performance Monitoring and Manageability Desktop Client Core XML Support Supplementary character support JDBC Row set

Although the above appears to be a list 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 thepremier language for general purpose stand- alone applications.

Complied and InterpretedUsually a computer language is either compiled or interpreted. Java combines both these approaches thusmaking java a two stage system. First, java compiler translates source code into what is known byte codeinstructions. Byte codes are not machine instructions and therefore, in the second stage, java interpretergenerates machine code that can be directly executed by the machine that is running the java program. We canthus say that java is both a compiled and an interpreted language.

Platform-Independent and PortableThe most significant contribution of java over other languages is its protability. Java programs can be easilymoved from one computer system to another, anywhere, and anytime. Chages and upgrades in operatingsystems, processors and system resources will not force any changes in java programs. This is the reason whyjava has become a popular language for programming on internet which is interconnects different kinds of

Page 6: Java Final Material

6 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

systems worldwide. We can download a java applet form a remote computer onto our local system viainternet and execute it locally. This makes the internet and extension of the user’s basic system providingpractically unlimited number of accessible applets and applications.

Java ensures portability in two ways, first, java compiler generates bytecode instructions that can beimplemented on any machine. Secondly, the size of the primitive data types are machine independent.

Object – OrientedJava is a true object oriented language. Almost everything in java is an object. All program code and datareside within objects and classes. Java comes with an extensive set of classes, arranged in packages, that wecan use in our programs by inheritance. The object model in java is simple and easy to extend.

Robust and SecureJava is a robust language. It provides many safeguards to ensure reliable code. It has strict compile time andrun time checking for data types. It is designed as garbage collected language relieving the programmersvirtually all memory management problems. Java also incorporates the concept of exception handling whichcaptures series errors and eliminates any risk of crashing the system. Security becomes an important issue fora language that is used for programming on internet. Threat of viruses and abuse of resources are everywhere.Java systems not only verify all memory access but also ensure that no viruses are communicated with anapplet. The absence of pointers in java ensures that programs cannot gain access to memory locations withoutproper authorization.

DistributedJava is designed as distributed language for creating applications on networks. It has the ability to share bothdata and programs. Java applications can open and access remote objects on internet as easily as they can doin a local system. This enables multiple programmers at multiple remote locations to collaborate and worktogether on a single project.

Simple, Small and FamiliarJava is a small and simple languae. Many features of C and C++ that are either redundant or sources ofunreliable code are not part of java for example, java does not use pointers, preprocessor header files, gotostatement and many others. It also eliminates operator overloading and multiple inheritance for more detailedcomparison of java with C and C++ , refer to sections 2.3

Familiarity is another striking features of java. To make the language look familiar to the exisitingprogrammers, it was modeled on C and C++ languages. Java uses many constructs of C and C++ andtherefore, java code “look like a C++” code. In fact, java is a simplified version of C++.Multithreaded and InteractiveMultithreaded means handling multiple tasks simultaneously.java supports multithreaded programs. Thismeans that we need not wait for the application to finish one task before beginning another, for example, wecan listen to an audio clip while scrolling a page and at the same time download and applet from a distantcomputer. This feature greatly improves the interactive performance of graphics applications.

The Java runtime comes with tools that support multiprocess synchronization and construct smoothlyrunning interactive systems.High Performance

Page 7: Java Final Material

7 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

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 reduceoverheads during runtime, further, the incorporation of multireading enhances the overall execution speed ofjava programs.

Dynamic and ExtensibleJava is a dynamic language. Java is capable of dynamically linking in new class libraries, methods, andobjects. Java can also determine the type of class through a query, making it possible to either dynamicallylink or abort the program, depending on the response.

Java programs support functions written in other languages such as C and C++. These functions are knownas native methods, This facility enables the programmers to use the efficient functions available in theselanguages. Native methods are linked dynamically at runtime.Ease of DevelopmentJava 2 standard Edition (j2se) 5.0 supports features, such as Generics, Enhanced for Loop, Autoboxing orunboxing, typesafe enums, Varargs, Static import and Annotation. These features reduce the work of theprogrammer by shifting the responsibility of creating the reusable code to the compiler. The resulting sourcecode is free bugs because the errors made by the compiler are less when compared to those made byprogrammers. Thus, each of the linguistic features is designed to develop java programs in an easier way.

Scalability and Performance

J2SE 5.0 assures a significant increase in scalability and performance by improving the startup time andreducing the amount of memory used in java 2 runtime environment. For example, the introduction of theclass, data sharing in the Hotspot java virtual Machine (JVM) improves the startup time by loading the coreclasses from the jar files into a shared archive. Memory utilization is reduced by sharing data in the sharedarchive among multiple JVM processes. In the earlier versions, the data was replicated in each JVM instance.

Monitoring and ManageabilityJava supports a number of APIs, such as JVM Monitoring and Management API, Sun Mangament platformExtension, Monitoring and Mangement interface, and Java management Extension (JMX) to monitor andmange java application. For example, java provides JVM Monitoring and Mangement API to track theinformation at the application level and JVM level when deploying a large application. Java provides tools,such as jconsole, jps, jstat, and jstatd to make use of monitoring and management facilities. For example, GUIbased tool called jconsole is used ot monitor the JVM.

Desktop Client

J2SE 5.0 provides enhanced features ot meet the requirements and challenges of the java desktop users. Itprovides an improved swing look and feel called ocean. This feature is mainly used for developing graphicsapplications that require open GL hardware acceleration.

Miscellaneous FeaturesIn addition to the above features, J2SE 5.0 supports the features such as:

Core XML Support

Page 8: Java Final Material

8 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

J2SE 5.0 adds a powerful XML feature to the java platform. Java contains some special packages forinterface, to instantiate simple API for XML (SAX) and document object model (DOM) parsers to parse andXML document, transform the content of an XML document, and validate and XML document against theschema.

Supplementary Character Support

Java adds the 32-bit supplementary character support as part of the Unicode 4.0 support. The supplementarycharacters are encoded with UTF -16 values to generate a different character called,surrogate codepoint.

JDBC RowsetJava supports JDBC rowset to send data in a tabular format between the remote components of a distributedenterprise application. JDBC Rowset contains chacherowset and webrowset objects. The cached row setobject is a JavaBeans component which acts like a container. This object contains a number of rows of data,which are retrieved from the database. The data stored in the cachedrowset can be directly accessed withoutconnecting to the database or any other data source/. The rows of data that are retrieved from the database canbe synchronized later. The webrowset object can operate without being connected to the database or datasource. The webrowset object uses XML format to read and write the rowset.

How Java Differs from C and C++

Although java was modeled after C and C++ languages, it differs from C and C++ in many ways. Java doesnot incorporate a number of features available in C and C++. For the benefit of C and C++ programmers, wepoint out here a few major differences between C/C++ and java languages.

Java and C

Java is a lot like C but the major difference between java and C is that java is an object oriented language andhas mechanism to define classes and objects. In an effort to build a simple and safe language, the java teamdid not include some of the C features in java.

Java does not include the C unique statement keywords sizeof, and typedef. Java does not contain the dat types struct and union. Java does not define the ytpe modifiers keywords auto,e extern, register, signed, and unsigned . Java does not support and explicit pointer type. Java does not have a preprocessor and therefore we cannot use # define, #include and #ifder

statements. Java requires that the functions with no arguments must be declared with empty parenthesis and not

with the void keyword as done in C. Java adds new operators such as instance of and >>>. Java adds labeled break and continue statements.

Java adds many features required for object oriented programming.

Java and C++

Page 9: Java Final Material

9 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Java is a ture object oriented language while C++ is basically C with object oriented extension, that is whatexactly the increment operator ++ indicates. C++ has maintained backward compatibility with C. it istherefore possible to write and old style C program and run it successfully under C++. Java appear to besimilar to C++ when we consider only the “extension” part of C++. However, some object oriented featuresof C++ make the C++ code exteremely difficult to follow and maintain.

Listed below are some major C++ features that were intentionally omitted from java or significant modified.

Java does not support operator overloading. Java does not have tamplate classes as in C++. Java does not support multiple inheritance of classes. This is accomplished using a new features

called “interface”. Java does not support global variables. Every variable and method is declared withing a class and

forms part of that class. Java does not use pointers. Java has replaced the destructor functions with a finalize ( ) function.

There are no header files in java.

Java also adds some new features. While C++ is a superset of C, java is neither a superset nor a subset of C orC++.

C

C++

Java

Overlapping of C, C++ and Java

Java and internet

Java is strongly associated with the internet because of the fact that the first application program written injava was HotJava, a web browser to run applets on internet. Internet users can use java to create appletprograms and run them locally using a “java-enabled browser” such as HotJava. They can also use a java-enabled browser to download an applet located on a computer anywhere in the internet and run it on his localcomputer. In fact, java applets have made the internet a true extension of the storage system of the localcomputer.Internet users can also set up their web sites containing Java applets that could be used by other remote usersof Internet. The ability of java applets to hitch a ride on the Information Superhighway has made Java aunique programming language for the Internet. In fact, due to this, Java is popularly known as InternetLanguage.

Java and World Wide Web

Page 10: Java Final Material

10 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

World Wide Web (WWW) is an open – ended information retrieval system designed to be used in theinternet’s distributed environment. This system contains what are known as web pages that provide bothinformation and controls. Unlike a menu driven system where we are guided through a particular directionusing a decision tree structure, the web system is open ended and we can navigate to a new document in anydirection as shown in figure. This is made possible with the help of a language called hypertext markuplanguage (HTML). Web pages contain HTML tags that enable us to find, retrieve, manipulate and displaydocuments worldwide.

Web structure of information search

Java was meant to be used in distributed environments such as internet. Since, both the web and java share thesame philosophy; java could be easily incorporated into the web system. Before, java, the World Wide Webwas limited to the display of still images and texts. However, the incorporation of java into WebPages hasmade it capable of unsporting animation, graphics, game, and a wide range of special effects. With thesupport of java, the web has become more interactive and dynamic. on the other hand, with the support ofweb, we can run a java program on someone else’s computer across the internet.Java communicates with a web page through a special tag called <APPLET>. Figure illustrates this process.The figure shows the following communication steps:

1. The users send a request for and HTML document to the remote computer’s web server. The webserver is a program that accepts a request, processes the request and sends the required document.

2. The HTML document is returned to the user’s browser. The document contains the APPLET tag,which identifies the applet.

3. The corresponding applet byutecode is transferred to the user’s computer. This bytecode had beenpreviously created by the java compiler using the java source code file for that applet.

4. The java enabled browser on the user’s computer interprets the bytecodes and provides output.5. The users may have further interaction with the applet but with nor further downloading form the

provider’s web server. This is because the bytecode contains all the information necessary to interpretthe applet.

Web BrowsersAs pointed out earlier, the internet is a vast sea of information represented in many formats and soared onmany computers. A large portion of the internet is organized as the World Wide Web which uses hypertext.Web browsers are used to navigate through the information found on the net. They allow su to retrieved the

Page 11: Java Final Material

11 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

information spread across the internet and display it using the hypertext markup language (HTML). Examplesof web browsers, among others, include:

Hot java Netscape navigator Internet explorer

HTML documents and <APPLET> tags are discussed in detail inch:14.

Hot JavaHot java is the web browser form sun Microsystems that enables the display of interactive content on the web,using the java language. Hot java is written entirely in java and demonstrates the capabilities of the javaprogramming language.When the java language was first developed and parted to the internet, no browsers were available that couldrun java applets. Although we can view a web page that includes java applets with a regular browser, we willnot gain any of java’s benefits. Hotjava is currently available for the SPARC/ Solaris platform as well asWindows 95, windows NT and Windows XP. So far as being a web browser goes, it is nothing special anddoes not offer anything special that most other web browsers don’t offer. Its biggest draw is that it was thefirst web browser to provide support for the java language, thus making the web more dynamic andinteractive.Netscape NavigatorNetscape navigator, form Netscape Communications Corporation, is general purpose browser that can runjava applets. With versions available for window 95,NT, Solaris and apple macintosh, Netscape navigator isone of the most widely used browsers today.Internet ExplorerInternet explorer is another popular browser developed by Microsoft for windows 95, NT and XPworkstations. Both the navigator and explorer use tool bars, icons, menus and dialog boxes for easynavigation. Explorer uses a just in time (JIT) compiler which greatly increases the speed of executions.Hardware and Software RequirementsJava is cureently supported on windows 95, Windows NT, Window XP, Sun Solaris, Machintosh, and UNIXmachines. Though the programs and examples in this book were tested under windows 95, the most popularoperating system today, they can be implemented on any of the above systems. The minimum hardware andsoftware requirements for windows 95 version of java are as follows:

IBM compatible 486 system Minimum of 8 MB memory Windows 95 software A windows compatible sound card, if necessary A hard drive A CD – Rom Drive

A micorsoft compatible mouse

Java Support Systems

Page 12: Java Final Material

12 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

it is clear from the discussion we had up to now that the operation of java and java enabled browsers on theinternet requires a variety of support systems. Table list the systems necessary to supports java for deliveringinformation on the internet.

Table Java Support Systems

Support Systems DescriptionInternet connection Local computer should be connected to the internet.Web Server A program that accepts requests for information and sends the required

documents.Web Browser A program that provides access to WWW and runs java applets.HTML A language for creating hypertext for the webAPPLET Tag For placing java applets in HTML documentJava Code Java code is used for defining java appletsBytecode Complied java code that is referred to in the APPLET tag and transferred to the

user computer

Java EnvironmentJava environment includes a large number of development tools and hundreds of classes and methods. Thedevelopment tools are part of the system known as java development kit (JDK) and the classes and methodsare part of the java Standard Library (JSL) also known as the application programming interface (API)Java DevelopmentThe java development kit comes with a collection of tools that are used for developing and running javaPrograms. They include:

applet viewer (for Viewing Java applets) Java C (java compiler) Java (Java interpreter) Java p ( java disassemble) Java h (for C header files) Java doc (for Creating HTML documents) Jdb ( Java debugger)

Table lists these tools and their descriptions.Table Java Development Tools

Tools DescriptionAppletviewer Enables us to run Java applets (without actually using a java compatible browser).Java Java interpreter, which runs applets and applications by reading and interpreating

bytecode files.Javac The java compiler which translate java sourcecode to bytecode files that the interpreter

can understand.Java doc Creates HTML format documentation from java source code filesJavah Produces header files for use with native methodsJavap Java disaaembler, which enables us to convert bytecode files into a program description.Jdb Java debugger, which helps us to find errors in our programs.

Page 13: Java Final Material

13 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

The way these tools are applied to build and run application programs is illustrated in figure. To create a Javaprogram, we need to create a source code file using a text editor. The source code is then complied using thejava Compiler Javac and executed using the java interpreter java. The java debugger jdb is used to find errors,if any, in the source code. a Compiled java program can be converted into a source code with the help of javadisassemble javap.

Text Editor

JavaSourceCode

javac

JavaClassFile

java

JavaProgramOutput

javadoc HTMLFiles

javah HeaderFiles

jdb

Process of building and running Java application programs

Page 14: Java Final Material

14 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Lesson 3 :Over view of Java Language

Introduction

Java is a general purpose, object oriented programming language. We can develop two types of javaprograms:

Stand – alone applications Web applets

They are implemented as shown in figure. Stand alone applications are programs written in java to carry outcertain tasks on a stand alone local computer. In fact, java can be used to develop programs for all kinds ofapplications, which earlier, were developed using languages like C and C++. As pointed out earlier, Hot javaitself is a java application program. Executing a stand alone java program involves two steps:

1. Compiling source code into bytecode using javac compiler.2. Executing the bytecode program using java interpreter.

Applets are small java programs developed for internet applications. An applet located on a distant computer(server) can be downloaded via internet and executed on a local computer (Client) using a java capablebrowser. We can develop applets for doing everything from simple animated graphics to complex games andutilities. Since applets are embedded in an HTML (Hypertext Markup Language) document and run inside aweb page, creating and running applets are more complex than creating and application.Stand alone programs can read and write files and perform certain operations that applets cannot do. Anapplet can only run within a Web browser.

JavaSourceCode

JavaCompiler

Java enabledWeb Browser

JavaInterpreter

Output Output

AppletType

ApplicationType

In this chapter, we shall consider some simple applications programs, which would demonstrate thegeneral structure of Java application programs. We shall also discuss here the general structure of javaapplication programs. We shall also discuss here the basic elements of java language and steps involved inexecuting a java application program. Creation of applets will be discussed later in chapter 14.

Page 15: Java Final Material

15 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Simple Java Program

The best way to learn a new language is to write a few simple example programs and executed them. Webegin with a very simple program that prints a line of text as output.class SampleOne}

Public static viod main (String args[ ]){

System.out.println (“ Java is better than C++.”);}

}Program 3.1 is perhaps the simplest of all java programs. Nevertheless, it brings out some salient features ofthe language. Let us therefore discuss the program line by line and understand the unique features thatconstitute a java program.Class Declaration

The first lineclass SampleOne

Declares a class, which is an object oriented construct. As statee earlier, java is a true object oriented languageand therefore, everything must be placed inside a class. Class is a keyword and declares that a new classdefinition follows. SampleOne is a java identifier that specifies the name of the class to be defined.

Opening Brace

Every class definition in Java begins with an opening brace “{“ and ends with a matching closing brace “}”,appearing in the last line in the example. This is similar to C++ class construct. (Note that a class definition inC++ ends with a semicolon.)

The Main Line

The third linepublic static void main (String args [ ] )

Defines a method named main. Conceptually, this is similar to the main ( ) function in C/C++. Every Javaapplication program must include the main ( ) method. This is the starting point for the interpreter to begin theexecution of the program. A Java application can have any number of classes but only one of them mustinclude a main method to initiate to initiate the execution. (Note that java applets will not use the mainmethod at all.)

The line contains a number of keywords, public, static and void.

public: The keyword Public is an access specified that declares the main method asUnprotected and therefore making it accessible to all other classes. This is similar to the C++Public modifier.

static: Next appears the keyword static. Which declares this method as one that belongs to the entireclass and not a part of any objects of the class. The main must always be declared as static

Page 16: Java Final Material

16 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

since the interpreter uses this method before any objects are created. More about staticmethods and variables will be discussed later chapter 8.

void: The type modifier void states that the main method does not return any value (but simplyprints some text to the screen.)

All parameters to a method are declared inside a pair of parentheses.here, String argsdeclares a parameter named args, which contains an arrays of objects of the class type String.

The Output Line

The only executable statement in the program isSystem. Out. println( “ Java is better than C++.”);

This is similar to the printf( ) statement of C or cout << construct of C++. Since java is a true object orientedlanguage, every method must be part of an object. The println method is a member of the out object, which isa static data member of System class. This line prints the string

Java is better than C++.To the screen. The method println always appends a new line character to the end of the string. This meansthat any sunssequent output will start on a new line. Note the semicolon at the end of the statement. Everyjava statement must end with a semicolon. ( Saving, compling, and executing a java program are discussed insection 3.8).

More of Java

Assume that we would like to compute and print the square root of a number. A java program to aaaomplishthis is shown in program. This is a slightly complex program. This program when complied and run producesthe output.

Y = 2.23607Program 3.2 A Java program with multiple statements

/ **More Java statements* This code comptes square root*/

Import java.lang.Math:class SquareRoot{

public static void main (String args [ ]){

double x = 5 ; // Declaration and initializationdouble y : // Simple declarationY = Math. Sqrt (x) ;System.out.println ( “ y = “ + y );

}}

Page 17: Java Final Material

17 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

The structure of the program is similar to the previous one except that it has more number of statements. Thestatement

double x = 5;Declares a variable x and initializes it to the value 5 and the statement

double y;Merely declares a variable y. note that both of them have been declared as double type variables. (double is adata type used to represent a floating point number. Data type are discussed in the next chatper.)The statement

Y = Math.sqrt (x) ;Invokes the method sqrt of the Math class, computes square root of x and then assigns the result to thevariable y. the output statement

System.out.println( “y =” + y);Displays the result on the screen as

Y = 2.23607Note the use of + symbol, here, the + acts as the concatenation operator of two strings. The value of y isconverted into a string representation before concatenation.

Use of Math FunctionsNote that the first statement in the program is

Import java.lang.Math:The purpose of this statement is to instruct the interpreter to load the Math class from the pacakage lang.

(This statement is similar to # include statement in C.) Remember, Math clas contains the sqrt methodrequired in the program.

CommentsJava permits both the single – line comments and multi line comments available in C++. The single linecomments begin with // and end at the end of the line as shown on the lines declaring x and y. For longercomments, we can create long multi line comments by starting with a/* and ending with a */ as shows at thebeginning of the program.

An Application with Two Classes

Both the examples discussed above use only one class that contains the main method. A real life applicationwill generally require multiple classes. Program illustrates a java application with two classes.

class Room{

float length;float breadth;

void getdata (float a. float b){

Page 18: Java Final Material

18 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

length = a;breadth = b;

}}class RoomArea{

public static void main (String args [ ]){

float area ;room room1 = new Room ( ); // Creates an object room1room1.getdata (14.10); // Assigns values to length and breadtharea = room1.length * room1. Breadth;system.out.println (“Area =” + area);

}}Program defines two classes Room and RoomArea. The Room class defines two variables and one methodto assign values to these variables. The class RoomArea contains the main method that initiates theexecution.

The main method declares a local variable area and a Room type object room1 and then assigns values tothe data members of Room class by using the getdata method. Finally, it calculates the area and prints theresults. Note the use of dot operator to accesss the variables and methods of Room class. Classes and methodsare discussed in chapter 8. The use of the keyword new is explained later in this chatper.

Java Program Structure

As we have seen in the previous examples, a java program many contain many classes of which only oneclass defines a main method. Classes contain data members and methods that operate on the data members ofthe class. Methods may contain data type declarations and executable statements. To write a java program, wefirst define classes and then put them together. A java program may contain one or more sections as shown in

Page 19: Java Final Material

19 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Documentation Section

Package Statement

Import Statements

Interface Statements

Class Definitions

Main Method Class{ Main Method Definition}

Suggested

Optional

Optional

Optional

Optional

Essential

Documentation Section

The documentation section comprises asset of comment lines giving the name of the program, the author andother details, which the programmer would like to refer to at a later stage. Comments must explain why andwhat of classes and how of algorithms. This would greatly help in maintain the program. In addition to thetwo styles of comments discussed earlier, java also uses a third style of comment /** …..*/ known asdocumentation comment. This form of comment is used for generation documentation automatically.

Package Statement

The first statement allowed in a java file is a package statement. This statement declares a package name andinforms 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 aboutpackages will be discussed later on.

Import Statements

The next thing after a package statement (but before any class definitions) may be number of importstatements. This is similar to the #include statement in C. Example:

import student. Test;This statement instructs the interpreter to load the test class contained in the package student using importstatements; we can have access to classes that are part of other named packages. More on import statementslater on.

Page 20: Java Final Material

20 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Interface StatementAn interface is like a class but includes a group of method declarations. This is also an optional section and isused only when we wish to implement the multiple inheritance feature in the program. Interface is a newconcept in java and is discussed in detail later on.

Class DefinitionsA java program may contain multiple class definitions. Classes are the primary and essential elements of javaprogram. These classes are used to map the objects of real world problems. The number of classes useddepends on the complexity of the problem.

Main Method ClassSince every java stand alone program requires a main method as its starting point, this class is the essentialpart of a java program. A simple java program may contain only this part. The main method creates objects ofvarious classes and establishes communications between them. On reaching the end of main, the programterminates and the control passes back to the operating system.

Java TokenA Java program is basically a collection of classes. A class is defined by a set of declaration statements andmethods containing executable statements (see figure). Most statements contain expressions, which describethe actions carried out on data. Smallest individual units in a program are known tokens. The compilerrecognizes them for building up expressions and statements.

In simple terms, a java program is a collection of tokens, comments and white spaces. Java languageincludes five types of tokens. They are:

Reserved Keywords Identifiers Literals Operators Separators

Java Character SetThe smallest units of java language are the characters used to write java tokens. These characters are definedby the Unicode character set, an emerging standard that tires to create characters for a large number of scriptsworldwide.

The Unicode, is a 16-bit character coding system and currently supports more than 34000 defined charactersderived from 24 languages from America, Europe, Middle East, Africa and Asia (including India). However,most of us use only the basic ASCII characters, which include letters, digits and punctuation marks,used innormal English. We, therefore, have used only ASCII character set (a subset of UNICODE character set) indeveloping the programs in this book.

KeywordsKeywords are an essential part of a language definition. They implement specific features of the language.Java language has reserved 50 words as keywords. Table 3.1 lists these keywords. These keywords, combinedwith operators and separators according to a syntax, form definition of the java language. Understanding themeaning of all these words is important for java programmers.

Page 21: Java Final Material

21 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Since keywords have specific meaning in Java, we cannot use them as names of variables,classes,methods and so on. All keywords are to be written in lower case letters. Since java is case sensitive one canuse these words as identifiers by changing one or more letters to upper case. However, it is a bad practice andshould be avoided.

Java Keywords

abstract assert Boolean breakbyte case catch charclass const continue defaultdo double else enumExtendsfinal finally floatfor goto if implementsimport instance of int interfacelong native new packageprivate protected public returnshort static strctfp superswitch synchronized this throwthrows transient try voidvolatile while

Note: We should also not attempt to use the Boolean values true and false or null as names in our programs.

Identifilers

Identifiers are programmer-designed tokens. They are used for naming classes, methods, variables, objects,labels, packages and interfaces in a program. Java identifiers follow the following rules:

1. They can have alphabets, digits, and the underscore and dollar sign characters.2. They must not begin with a digit.3. Uppercase and lowercase letters are distinct.4. They can be of any length.

Identifier must be meaningful, short enough to be quickly and easily typed and long enough to be descriptiveand easily read. Java developers have followed some naming converntions.

Names of all public methods and instance variables start with a leading lowercase letter.Examples:

averagesum

When more than one words are used in a name,the second and subsequent words are marked with aleading uppercase letters. Examples:

dayTemperaturefirstDayOfMonthtotalMarks

All private and local variables use only lowercase letters combined with underscores. Examples:lengthbatch_strength

Page 22: Java Final Material

22 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

All classes and interfaces start with a leading uppercase letter (and each subsequent wordStudentHelloJavaVehiclemotoCycle

Variables that represent constant values use all uppercase letters and underscores between words,Examples:

TOTALF_MAXPRINCIPAL_AMOUNT

They are like symbolic constants in C.It should be remembered that all these are conventions and not rules. We may follow our own conventions aslong as we do not break the basic rules of naming identifiers.LiteralsLiterals in java are a sequence of characters (digits, letters, and other characters) that represent constant valuesto be stored in variables. Java language specifies five major types of literals. They are:

Interger literals Floating_Point literals Character literals String literals Boolean literals

Each of them has a type associated with it. The type describes how the values behave and how they arestored. We will discuss these in detail when we deal with data types and constants.

OperatorsAn operator is a symbol that takes one or more arguments and operates on them to produce a result.operatorsare of many types and are considered in detail in chapter5.SeparatorsSeparators are symbols used to indicate where groups of code are divided and arranged. They basically definethe shape and function of our code. Table 3.2 lists separators and their functions.

Table 3.2 Java SeparatorsName What it is used for

parentheses( ) Used to enclose parameters in method definition and invocation, also used for definingprecedence in expressions, containing expressions for flow control, and surroundingcast types.

braces { } Used to contain the values of automatically initialized arrays and to define a block ofcode for classes, methods and local scopes

brackets [ ] Used to declare array types and for dereferencing array valuessemicolon; Used to separate statementscomma, Used to separate consecutive identifiers in a variable declaration, also used to chain

statement together inside a ‘for’ statementperiod. Used to separate package names from sub-packages and classes; also used to separate a

variable or method from a reference variable.

Page 23: Java Final Material

23 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Compiling the ProgramThe compile the program, we must run the java Compiler javac, with the name of the source file on thecommand line as shown below:

javac Test.javaIf everything is OK, the javac compiler creates a file called Test.class containing the bytecodes of theprogram. note that the compiler automatically names he bytecode file as

<classname> .class

Source Code

Java Compiler

Byte Code

WindowsInterpreter

MachineCode

MachineCode

MachineCode

WindowComputer

ABCInterpreter

ABCComputer

MacintoshInterpreter

MacintoshComputer

Implementation of Java ProgramRunning the programWe need to use the java interpreter to run a stand alone program. At the command prompt, type

java TestNow, the interpreter looks for the main method in the program and begins execution form there. Whenexecuted, our program displays the following:

Hello!Welcome to the world of Java.Let us learn Java.

Note that we simply type “Test” at the command line and not “Test.class” or “Test.java”

Machine NeturalThe compiler converts the source code files into bytecode files. These codes are machine- independent andtherefore can be run on any machine. That is, a program compiled on an IBM machine will run on aMachintosh machine.

Java interpreter reads the bytecode files and translates them into machine code for the specifiedmachine on which the java program is running. The interpreter is therefore specially written for each type ofmachine. Figure illustrates this concept.

Page 24: Java Final Material

24 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Java Virtual MachineAll language compilers translate source code into machine code for a specific computer. Java compiler alsodoes the same thing. Then, how does java achieve architecture neutrality? The answer is that the javacompiler produces and intermedia code known as bytecode for a machine that does not exist. This machine iscalled the java Virtual Machine and it exists only inside the computer memory. It is a simulated computerwithin the computer and does all major functions of a real computer. Figure illustrates the process ofcompiling a java program into bytecode which is also referred to as virtual machine code.

JavaProgram

JavaCompiler

VirtualMachine

Process of compilationThe virtual machine code is not machine specific. The machine specific code (known as machine code) isgenerated by the java interpreter by acting as an intermediary between the virtual machine and the realmachine as show fig.3.7 .Remember that the interpreter is different for different machines.

Bytecode JavaInterpreter

Machine Code

Process of converting bytecode into machine codeFigure illustrates how java works on a typical computer. The java object framework (JavaAPI) acts as theintermediary between the user programs and the virtual machine which in turn acts as the intermediarybetween the operating system and the java object framework.

Command Line ArgumentsThere may be occasions when we may like our program to act in a particular way depending on the inputprovided at the time of execution. This is achieved in java programs by using what are known as commandline arguments. Command line arguments are parameters that are supplied to the application program at thetime of invoking it for execution. It may be recalled that program 3.4 was invoked for execution of thecommand line as follows:

java TestHere, we have not supplied any command line arguments. Even if we supply arguments, the program does notknown what to do with them.

We can write Java programs that can receive and use the arguments provided in the command line. Recallthe signature of the main( ) method used in our earlier example programs:

Public static void main (String args[ ])As pointed out earlier, args is declared as an array of strings (known as string objects). Any arguents

provided in the command line (at the time of execution) are passed to the array args as its elements. We cansimply access the array elements and use them in the program as we wish. For example, consider thecommand line

java Test BASIC FORTRAN C++ javaThis command line contains four arguments. These are assigned to the array args as follows:

BASIC args [0]

Page 25: Java Final Material

25 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

FORTRAN args [1]C++ args [2]JAVA args [3]

The individual elements of an array are accessed by using an index or subscript like args[i]. The value of Idenotes the position of the elements inside the array. For example, args[2] denotes the third element andrepresents C++. Note that Java subscripts begin with 0 and not 1.

Use of command line arguments

/**this program uses command line* arguments as input .*/

class ComLineTest{

public static void main (string args [ ]){

int count. i =0;String string;count = args.length;System.out.println (“Number of arguments = “ + count );while (i < count){

String = args[ i ];i= i + 1;System.out.println(i+ “ : “ + “Java is “ + string+ “!”);

}}

}

Program illustrates the use of command line arguments. Compile and run the program with the command lineas follows:

java ComLineTest Simple Object_Oriented Distributed RobustSecure Portable Multithreaded Dynamic

Upon execution, the command line arguments simple, object_Oriented, etc. are passed to the program throughthe array args as discussed earlier. That is the element args[0] contains simple, args[1] containsObject_Oriented, and so on. These elements are accessed using the loop variable i as and index like

name = args[i]The index i is incremented using a while loop until all the arguments are accessed. The number of argumentsis obtained by statement

count = args.length ;The output of the program would be as follows:Number of arguents =8

1 : Java is simple!2 : Java is Object_Oriented!

Page 26: Java Final Material

26 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

3 : Java is Distributed!4 : Java is Robust!5 : Java is Secure!6 : Java is Portable!7 : Java is Multithreaded!8 : Java is Dynamic!

Note how the output statement concatenates the strings while printing.

Programming StyleJava is a freeform language. We need not have to indent any lines to make the program work properly. Javasystem does not care where on the line e begin typing. While this may be a license for bad programming. Weshould try to use this fact to our advantage for producing readable programs. Although several alternate stylesare possible, we should select one and try to use it with total consistency.

For example, the statementSystem.out.println (“Java is Wonderful!”)

Can be written asSystem.out.println(“Java is Wonderful!”);

Or, even asSystem.out.println(“Java is Wonderful!”);

Page 27: Java Final Material

27 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Lesson 4: Language Basics

VariablesA variable is an identifier that denotes a storage location used to store a data value. Unlike constants thatremain unchanged during the execution of a program, a variable may take different values at different timesduring the execution of the program.The Java programming language defines the following kinds of variables:

Instance Variables (Non-Static Fields) Technically speaking, objects store their individual states in"non-static fields", that is, fields declared without the static keyword. Non-static fields are alsoknown as instance variables because their values are unique to each instance of a class (to eachobject, in other words); the currentSpeed of one bicycle is independent from thecurrentSpeed of another.

Class Variables (Static Fields) A class variable is any field declared with the static modifier;this tells the compiler that there is exactly one copy of this variable in existence, regardless of howmany times the class has been instantiated. A field defining the number of gears for a particular kindof bicycle could be marked as static since conceptually the same number of gears will apply to allinstances. The code static int numGears = 6; would create such a static field.Additionally, the keyword final could be added to indicate that the number of gears will neverchange.

Local Variables Similar to how an object stores its state in fields, a method will often store itstemporary state in local variables. The syntax for declaring a local variable is similar to declaring afield (for example, int count = 0;). There is no special keyword designating a variable as local;that determination comes entirely from the location in which the variable is declared — which isbetween the opening and closing braces of a method. As such, local variables are only visible to themethods in which they are declared; they are not accessible from the rest of the class.

Parameters You've already seen examples of parameters, both in the Bicycle class and in themain method of the "Hello World!" application. Recall that the signature for the main method ispublic static void main(String[] args). Here, the args variable is the parameter tothis method. The important thing to remember is that parameters are always classified as "variables"not "fields".

Having said that, the remainder of this tutorial uses the following general guidelines when discussing fieldsand variables. If we are talking about "fields in general" (excluding local variables and parameters), we maysimply say "fields". If the discussion applies to "all of the above", we may simply say "variables". If thecontext calls for a distinction, we will use specific terms (static field, local variables, etc.) as appropriate.You may also occasionally see the term "member" used as well. A type's fields, methods, and nested typesare collectively called its members.

NamingEvery programming language has its own set of rules and conventions for the kinds of names that you'reallowed to use, and the Java programming language is no different. The rules and conventions for namingyour variables can be summarized as follows:

Variable names are case-sensitive. A variable's name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign "$", or theunderscore character "_". The convention, however, is to always begin your variable names with aletter, not "$" or "_". Additionally, the dollar sign character, by convention, is never used at all. Youmay find some situations where auto-generated names will contain the dollar sign, but your variablenames should always avoid using it. A similar convention exists for the underscore character; whileit's technically legal to begin your variable's name with "_", this practice is discouraged. White spaceis not permitted.

Page 28: Java Final Material

28 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Subsequent characters may be letters, digits, dollar signs, or underscore characters. Conventions (andcommon sense) apply to this rule as well. When choosing a name for your variables, use full wordsinstead of cryptic abbreviations. Doing so will make your code easier to read and understand. In manycases it will also make your code self-documenting; fields named cadence, speed, and gear, forexample, are much more intuitive than abbreviated versions, such as s, c, and g. Also keep in mindthat the name you choose must not be a keyword or reserved word.

If the name you choose consists of only one word, spell that word in all lowercase letters. If it consistsof more than one word, capitalize the first letter of each subsequent word. The names gearRatioand currentGear are prime examples of this convention. If your variable stores a constant value,such as static final int NUM_GEARS = 6, the convention changes slightly, capitalizingevery letter and separating subsequent words with the underscore character. By convention, theunderscore character is never used elsewhere.

Primitive Data TypesThe Java programming language is staticaly-typed, which means that all variables must first be declaredbefore they can be used. This involves stating the variable's type and name, as you've already seen:int gear = 1;Doing so tells your program that a field named "gear" exists, holds numerical data, and has an initial value of"1". A variable's data type determines the values it may contain, plus the operations that may be performed onit. In addition to int, the Java programming language supports seven other primitive data types. A primitivetype is predefined by the language and is named by a reserved keyword. Primitive values do not share statewith other primitive values. The eight primitive data types supported by the Java programming language are:

byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memoryin large arrays, where the memory savings actually matters. They can also be used in place of intwhere their limits help to clarify your code; the fact that a variable's range is limited can serve as aform of documentation.

short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: youcan use a short to save memory in large arrays, in situations where the memory savings actuallymatters.

int: The int data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). For integral values, this data typeis generally the default choice unless there is a reason (like the above) to choose something else. Thisdata type will most likely be large enough for the numbers your program will use, but if you need awider range of values, use long instead.

long: The long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use thisdata type when you need a range of values wider than those provided by int.

float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values isbeyond the scope of this discussion. As with the recommendations for byte and short, use afloat (instead of double) if you need to save memory in large arrays of floating point numbers

double: The double data type is a double-precision 64-bit IEEE 754 floating point. For decimalvalues, this data type is generally the default choice. As mentioned above, this data type should neverbe used for precise values, such as currency.

boolean: The boolean data type has only two possible values: true and false. Use this datatype for simple flags that track true/false conditions. This data type represents one bit of information,but its "size" isn't something that's precisely defined.

char: The char data type is a single 16-bit Unicode character.

Page 29: Java Final Material

29 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

In addition to the eight primitive data types listed above, the Java programming language also providesspecial support for character strings via the java.lang.String class. Enclosing your character string withindouble quotes will automatically create a new String object; for example, String s = "this is astring";. String objects are immutable, which means that once created, their values cannot be changed.The String class is not technically a primitive data type, but considering the special support given to it bythe language, you'll probably tend to think of it as such. You'll learn more about the String class later on.

Default ValuesIt's not always necessary to assign a value when a field is declared. Fields that are declared but not initializedwill be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null,depending on the data type. Relying on such default values, however, is generally considered badprogramming style.The following chart summarizes the default values for the above data types.

Data Type Default Value (for fields)

byte 0

short 0

int 0

long 0L

float 0.0f

double 0.0d

char '\u0000'

String (or any object) null

boolean false

Local variables are slightly different; the compiler never assigns a default value to an uninitialized localvariable. If you cannot initialize your local variable where it is declared, make sure to assign it a value beforeyou attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.

Declaration of Variables:After designing suitable variable names, we must declare them to the compiler. Declaration does three things:

1. It tells the compiler what the variable name is.2. It specifies what type of data the variable will hold.3. The place of declaration decides the scope of the variable.

A variable must be declared before it is used in the program. The declaration statement defines the type ofvariable. The general form of declaration of a variable is:

type variable1, variable2, ………. variable;Variables are separated by commas. A declaration statement must end with a semicolon. Some validdeclarations are:

int count;float x , y;

Giving values to variables:A variable must be given a valid after it has been declared but before it is used in an expression. This can beachieved in two ways:

1. By using an assignment statement2. By using a read statement

Page 30: Java Final Material

30 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

A simple method of giving value to a variable is through the assignment statement as follows:VariableName = value;

For example:initialValue = 0;yes = ‘x’;x = y = z = 0;

It is also possible to assign a value to a variable at the time of its declaration. This takes the form:type variableName = value;

For example,int finalvalue = 100;char yes=’x’;

LiteralsYou may have noticed that the new keyword isn't used when initializing a variable of a primitive type.Primitive types are special data types built into the language; they are not objects created from a class. Aliteral is the source code representation of a fixed value; literals are represented directly in your code withoutrequiring computation. As shown below, it's possible to assign a literal to a variable of a primitive type:

boolean result = true;char capitalC = 'C';byte b = 100;short s = 10000;int i = 100000;

The integral types (byte, short, int, and long) can be expressed using decimal, octal, or hexadecimalnumber systems. Decimal is the number system you already use every day; it's based on 10 digits, numbered 0through 9. The octal number system is base 8, consisting of the digits 0 through 7. The hexadecimal system isbase 16, whose digits are the numbers 0 through 9 and the letters A through F. For general-purposeprogramming, the decimal system is likely to be the only number system you'll ever use. However, if youneed octal or hexadecimal, the following example shows the correct syntax. The prefix 0 indicates octal,whereas 0x indicates hexadecimal.

int decVal = 26; // The number 26, in decimalint octVal = 032; // The number 26, in octalint hexVal = 0x1a; // The number 26, in hexadecimal

The floating point types (float and double) can also be expressed using E or e (for scientific notation), For f (32-bit float literal) and D or d (64-bit double literal; this is the default and by convention is omitted).

double d1 = 123.4;double d2 = 1.234e2; // same value as d1, but in scientific notationfloat f1 = 123.4f;

Literals of types char and String may contain any Unicode (UTF-16) characters. If your editor and filesystem allow it, you can use such characters directly in your code. If not, you can use a "Unicode escape"such as '\u0108' (capital C with circumflex), or "S\u00ED se\u00F1or" (Sí Señor in Spanish).Always use 'single quotes' for char literals and "double quotes" for String literals. Unicode escapesequences may be used elsewhere in a program (such as in field names, for example), not just in char orString literals.The Java programming language also supports a few special escape sequences for char and String literals:\b (backspace), \t (tab), \n (line feed), \f (form feed), \r (carriage return), \" (double quote), \' (singlequote), and \\ (backslash).There's also a special null literal that can be used as a value for any reference type. null may be assignedto any variable, except variables of primitive types. There's little you can do with a null value beyond

Page 31: Java Final Material

31 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

testing for its presence. Therefore, null is often used in programs as a marker to indicate that some object isunavailable.Finally, there's also a special kind of literal called a class literal, formed by taking a type name and appending".class"; for example, String.class. This refers to the object (of type Class) that represents the typeitself.

ArraysAn array is a container object that holds a fixed number of values of a single type. The length of an array isestablished when the array is created. After creation, its length is fixed. You've seen an example of arraysalready, in the main method of the "Hello World!" application. This section discusses arrays in greater detail.

An array of tenelements

Each item in an array is called an element, and each element is accessed by its numerical index. As shown inthe above illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed atindex 8.The following program, ArrayDemo, creates an array of integers, puts some values in it, and prints eachvalue to standard output.

class ArrayDemo {public static void main(String[] args) {

int[] anArray; // declares an array of integers

anArray = new int[10]; // allocates memory for 10 integers

anArray[0] = 100; // initialize first elementanArray[1] = 200; // initialize second elementanArray[2] = 300; // etc.anArray[3] = 400;anArray[4] = 500;anArray[5] = 600;anArray[6] = 700;anArray[7] = 800;anArray[8] = 900;anArray[9] = 1000;

System.out.println("Element at index 0: " + anArray[0]);System.out.println("Element at index 1: " + anArray[1]);System.out.println("Element at index 2: " + anArray[2]);System.out.println("Element at index 3: " + anArray[3]);System.out.println("Element at index 4: " + anArray[4]);System.out.println("Element at index 5: " + anArray[5]);System.out.println("Element at index 6: " + anArray[6]);

Page 32: Java Final Material

32 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

System.out.println("Element at index 7: " + anArray[7]);System.out.println("Element at index 8: " + anArray[8]);System.out.println("Element at index 9: " + anArray[9]);

}}The output from this program is:Element at index 0: 100Element at index 1: 200Element at index 2: 300Element at index 3: 400Element at index 4: 500Element at index 5: 600Element at index 6: 700Element at index 7: 800Element at index 8: 900Element at index 9: 1000In a real-world programming situation, you'd probably use one of the supported looping constructs to iteratethrough each element of the array, rather than write each line individually as shown above. However, thisexample clearly illustrates the array syntax. You'll learn about the various looping constructs (for, while,and do-while) in the Control Flow section.

Declaring a Variable to Refer to an ArrayThe above program declares an Array with the following line of code:

int[] anArray; // declares an array of integersor

int anArray[];Like declarations for variables of other types, an array declaration has two components: the array's type andthe array's name. An array's type is written as type[], where type is the data type of the containedelements; the square brackets are special symbols indicating that this variable holds an array. The size of thearray is not part of its type (which is why the brackets are empty). An array's name can be anything you want,provided that it follows the rules and conventions as previously discussed in the naming section. As withvariables of other types, the declaration does not actually create an array — it simply tells the compiler thatthis variable will hold an array of the specified type.Similarly, you can declare arrays of other types:byte[] anArrayOfBytes;short[] anArrayOfShorts;long[] anArrayOfLongs;float[] anArrayOfFloats;double[] anArrayOfDoubles;boolean[] anArrayOfBooleans;char[] anArrayOfChars;String[] anArrayOfStrings;

You can also place the square brackets after the array's name:float anArrayOfFloats[]; // this form is discouragedHowever, convention discourages this form; the brackets identify the array type and should appear with thetype designation.

Creating, Initializing, and Accessing an Array

Page 33: Java Final Material

33 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

One way to create an array is with the new operator. The next statement in the ArrayDemo programallocates an array with enough memory for ten integer elements and assigns the array to the anArrayvariable.anArray = new int[10]; // create an array of integersIf this statement were missing, the compiler would print an error like the following, and compilation wouldfail:ArrayDemo.java:4: Variable anArray may not have been initialized.The next few lines assign values to each element of the array:anArray[0] = 100; // initialize first elementanArray[1] = 200; // initialize second elementanArray[2] = 300; // etc.Each array element is accessed by its numerical index:System.out.println("Element 1 at index 0: " + anArray[0]);System.out.println("Element 2 at index 1: " + anArray[1]);System.out.println("Element 3 at index 2: " + anArray[2]);Alternatively, you can use the shortcut syntax to create and initialize an array:int[] anArray = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000};Here the length of the array is determined by the number of values provided between { and }.You can also declare an array of arrays (also known as a multidimensional array) by using two or more sets ofsquare brackets, such as String[][] names. Each element, therefore, must be accessed by acorresponding number of index values.In the Java programming language, a multidimensional array is simply an array whose components arethemselves arrays. This is unlike arrays in C or Fortran. A consequence of this is that the rows are allowed tovary in length, as shown in the following MultiDimArrayDemo program:class MultiDimArrayDemo {

public static void main(String[] args) {String[][] names = {{"Mr. ", "Mrs. ", "Ms. "},

{"Smith", "Jones"}};System.out.println(names[0][0] + names[1][0]); //Mr. SmithSystem.out.println(names[0][2] + names[1][1]); //Ms. Jones

}}The output from this program is:

Mr. SmithMs. Jones

Finally, you can use the built-in length property to determine the size of any array. The codeSystem.out.println(anArray.length);

will print the array's size to standard output.

Copying ArraysThe System class has an arraycopy method that you can use to efficiently copy data from one array intoanother:public static void arraycopy(Object src,

int srcPos,Object dest,int destPos,int length)

The two Object arguments specify the array to copy from and the array to copy to. The three intarguments specify the starting position in the source array, the starting position in the destination array, andthe number of array elements to copy.

Page 34: Java Final Material

34 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

The following program, ArrayCopyDemo, declares an array of char elements, spelling the word"decaffeinated". It uses arraycopy to copy a subsequence of array components into a second array:

class ArrayCopyDemo {public static void main(String[] args) {

char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e','i', 'n', 'a', 't', 'e', 'd' };

char[] copyTo = new char[7];

System.arraycopy(copyFrom, 2, copyTo, 0, 7);System.out.println(new String(copyTo));

}}The output from this program is:CaffeineQuestions

1. The term "instance variable" is another name for ___.2. The term "class variable" is another name for ___.3. A local variable stores temporary state; it is declared inside a ___.4. A variable declared within the opening and closing parenthesis of a method signature is called a ____.5. What are the eight primitive data types supported by the Java programming language?6. Character strings are represented by the class ___.7. An ___ is a container object that holds a fixed number of values of a single type.

Exercises1. Create a small program that defines some fields. Try creating some illegal field names and see what

kind of error the compiler produces. Use the naming rules and conventions as a guide.2. In the program you created in Exercise 1, try leaving the fields uninitialized and print out their values.

Try the same with a local variable and see what kind of compiler errors you can produce. Becomingfamiliar with common compiler errors will make it easier to recognize bugs in your code.

Lesson 5: Operators

Now that you've learned how to declare and initialize variables, you probably want to know how to dosomething with them. Learning the operators of the Java programming language is a good place to start.Operators are special symbols that perform specific operations on one, two, or three operands, and thenreturn a result.As we explore the operators of the Java programming language, it may be helpful for you to know ahead oftime which operators have the highest precedence. The operators in the following table are listed accordingto precedence order. The closer to the top of the table an operator appears, the higher its precedence.Operators with higher precedence are evaluated before operators with relatively lower precedence.Operators on the same line have equal precedence. When operators of equal precedence appear in the sameexpression, a rule must govern which is evaluated first. All binary operators except for the assignmentoperators are evaluated from left to right; assignment operators are evaluated right to left.

Operator Precedence

Operators Precedence

postfix expr++ expr--

unary ++expr --expr +expr -expr ~ !

Page 35: Java Final Material

35 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

multiplicative * / %

additive + -

shift << >> >>>

relational < > <= >= instanceof

equality == !=

bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

logical AND &&

logical OR ||

ternary ? :

assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

In general-purpose programming, certain operators tend to appear more frequently than others; for example,the assignment operator "=" is far more common than the unsigned right shift operator ">>>". With that inmind, the following discussion focuses first on the operators that you're most likely to use on a regularbasis, and ends focusing on those that are less common. Each discussion is accompanied by sample codethat you can compile and run. Studying its output will help reinforce what you've just learned.

Types of Operators

1. The Assignment OperatorOne of the most common operators that you'll encounter is the simple assignment operator "=".You saw this operator in the Bicycle class; it assigns the value on its right to the operand on its left:int cadence = 0;int speed = 0;int gear = 1;

2. The Arithmetic OperatorsThe Java programming language provides operators that perform addition, subtraction,multiplication, and division. There's a good chance you'll recognize them by their counterparts inbasic mathematics. The only symbol that might look new to you is "%", which divides one operandby another and returns the remainder as its result.+ addition operator (also used for String concatenation)- subtraction operator* multiplication operator/ division operator% remainder operatorThe following program, ArithmeticDemo, tests the arithmetic operators.

Page 36: Java Final Material

36 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

class ArithmeticDemo{

public static void main (String[] args){int result = 1 + 2; // result is now 3System.out.println(result);

result = result - 1; // result is now 2System.out.println(result);

result = result * 2; // result is now 4System.out.println(result);

result = result / 2; // result is now 2System.out.println(result);

result = result + 8; // result is now 10result = result % 7; // result is now 3System.out.println(result);

}}

You can also combine the arithmetic operators with the simple assignment operator to createcompound assignments. For example, x+=1; and x=x+1; both increment the value of x by 1.The + operator can also be used for concatenating (joining) two strings together, as shown in thefollowing ConcatDemo program:

class ConcatDemo {public static void main(String[] args){

String firstString = "This is";String secondString = " a concatenated

string.";String thirdString = firstString+secondString;System.out.println(thirdString);

}}

By the end of this program, the variable thirdString contains "This is a concatenated string.",which gets printed to standard output.

3. The Unary OperatorsThe unary operators require only one operand; they perform various operations such asincrementing/decrementing a value by one, negating an expression, or inverting the value of aboolean.+ Unary plus operator; indicates positive value (numbers arepositive without this, however)- Unary minus operator; negates an expression++ Increment operator; increments a value by 1-- Decrement operator; decrements a value by 1! Logical complement operator; inverts the valueof a booleanThe following program, UnaryDemo, tests the unary operators:

class UnaryDemo

Page 37: Java Final Material

37 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

{public static void main(String[] args){

int result = +1; // result is now 1System.out.println(result);result--; // result is now 0System.out.println(result);result++; // result is now 1System.out.println(result);result = -result; // result is now -1System.out.println(result);boolean success = false;System.out.println(success); // falseSystem.out.println(!success); // true

}}

The increment/decrement operators can be applied before (prefix) or after (postfix) the operand.The code result++; and ++result; will both end in result being incremented by one.The only difference is that the prefix version (++result) evaluates to the incremented value,whereas the postfix version (result++) evaluates to the original value. If you are justperforming a simple increment/decrement, it doesn't really matter which version you choose. Butif you use this operator in part of a larger expression, the one that you choose may make asignificant difference.The following program, PrePostDemo, illustrates the prefix/postfix unary increment operator:

class PrePostDemo {public static void main(String[] args){int i = 3;i++;System.out.println(i); // "4"++i;System.out.println(i); // "5"System.out.println(++i); // "6"System.out.println(i++); // "6"System.out.println(i); // "7"}

}

4. The Relational OperatorsThe equality and relational operators determine if one operand is greater than, less than, equal to,or not equal to another operand. The majority of these operators will probably look familiar to youas well. Keep in mind that you must use "==", not "=", when testing if two primitive values areequal.

== equal to!= not equal to> greater than>= greater than or equal to< less than<= less than or equal to

Page 38: Java Final Material

38 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

The following program, ComparisonDemo, tests the comparison operators:

class ComparisonDemo{public static void main(String[] args){int value1 = 1;int value2 = 2;if(value1 == value2) System.out.println("value1 ==

value2");if(value1 != value2) System.out.println("value1 !=

value2");if(value1 > value2) System.out.println("value1 > value2");if(value1 < value2) System.out.println("value1 < value2");if(value1 <= value2) System.out.println("value1 <=

value2");}

}Output:value1 != value2value1 < value2value1 <= value2

5. The Logical OperatorsThe && and || operators perform Logical-AND and Logical-OR operations on two booleanexpressions. These operators exhibit "short-circuiting" behavior, which means that the secondoperand is evaluated only if needed.

&& AND|| OR! NOT

The following program, ConditionalDemo1, tests these operators:

class ConditionalDemo1{public static void main(String args[]){int value1 = 1;int value2 = 2;if((value1 == 1) && (value2 == 2))System.out.println("value1 is 1 AND value2 is 2");if((value1 == 1) || (value2 == 1))System.out.println("value1 is 1 OR value2 is 1");}}

6. The Conditional OperatorThe conditional operator is ?:, which can be thought of as shorthand for an if-then-elsestatement (discussed in the Control Flow Statements section). This operator is also known as theternary operator because it uses three operands. In the following example, this operator should beread as: "If some Condition is true, assign the value of value1 to result. Otherwise,assign the value of value2 to result."Syntax:

Page 39: Java Final Material

39 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Exp1 ? exp2 : exp3;If the Exp1 is true then it evaluates exp2 otherwise exp3.

The following program, ConditionalDemo2, tests the ?: operator:class ConditionalDemo2{

public static void main(String[] args){int value1 = 1;int value2 = 2;int result;boolean someCondition = true;result = someCondition ? value1 : value2;System.out.println(result);

}}

Because someCondition is true, this program prints "1" to the screen. Use the ?: operatorinstead of an if-then-else statement if it makes your code more readable; for example, whenthe expressions are compact and without side-effects.

7. The Type Comparison Operator instanceofThe instanceof operator compares an object to a specified type. You can use it to test if anobject is an instance of a class, an instance of a subclass, or an instance of a class that implementsa particular interface.The following program, InstanceofDemo, defines a parent class (named Parent), a simpleinterface (named MyInterface), and a child class (named Child) that inherits from the parentand implements the interface.

class InstanceofDemo{public static void main(String[] args){Parent obj1 = new Parent();Parent obj2 = new Child();System.out.println("obj1 instanceof Parent: " + (obj1instanceof Parent));System.out.println("obj1 instanceof Child: " + (obj1instanceof Child));System.out.println("obj1 instanceof MyInterface: " + (obj1instanceof MyInterface));System.out.println("obj2 instanceof Parent: " + (obj2instanceof Parent));System.out.println("obj2 instanceof Child: " + (obj2instanceof Child));System.out.println("obj2 instanceof MyInterface: " + (obj2instanceof MyInterface));}

}

class Parent{}class Child extends Parent implements MyInterface{}

Page 40: Java Final Material

40 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

interface MyInterface{}Output:obj1 instanceof Parent: trueobj1 instanceof Child: falseobj1 instanceof MyInterface: falseobj2 instanceof Parent: trueobj2 instanceof Child: trueobj2 instanceof MyInterface: true

When using the instanceof operator, keep in mind that null is not an instance of anything.

8. Bitwise and Bit Shift OperatorsThe Java programming language also provides operators that perform bitwise and bit shiftoperations on integral types. The operators discussed in this section are less commonly used.Therefore, their coverage is brief; the intent is to simply make you aware that these operators exist.The unary bitwise complement operator "~" inverts a bit pattern; it can be applied to any of theintegral types, making every "0" a "1" and every "1" a "0". For example, a byte contains 8 bits;applying this operator to a value whose bit pattern is "00000000" would change its pattern to"11111111".The signed left shift operator "<<" shifts a bit pattern to the left, and the signed right shift operator">>" shifts a bit pattern to the right. The bit pattern is given by the left-hand operand, and thenumber of positions to shift by the right-hand operand. The unsigned right shift operator ">>>"shifts a zero into the leftmost position, while the leftmost position after ">>" depends on signextension.The bitwise & operator performs a bitwise AND operation.The bitwise ^ operator performs a bitwise exclusive OR operation.The bitwise | operator performs a bitwise inclusive OR operation.The following program, BitDemo, uses the bitwise AND operator to print the number "2" tostandard output.

class BitDemo{

public static void main(String[] args){int bitmask = 0x000F;int val = 0x2222;System.out.println(val & bitmask); // prints "2"

Summary of OperatorsThe following quick reference summarizes the operators supported by the Java programminglanguage.

Simple Assignment Operator= Simple assignment operatorArithmetic Operators+ Addition operator (also used for String concatenation)- Subtraction operator* Multiplication operator/ Division operator% Remainder operator

Page 41: Java Final Material

41 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Unary Operators+ Unary plus operator; indicates positive value (numbers arepositive without this, however)- Unary minus operator; negates an expression++ Increment operator; increments a value by 1-- Decrement operator; decrements a value by 1! Logical compliment operator; inverts the value of a booleanEquality and Relational Operators== Equal to!= Not equal to> Greater than>= Greater than or equal to< Less than<= Less than or equal toConditional Operators?: Ternary (shorthand for if-then-else statement)Logical Operators&& AND|| OR! NOTType Comparison Operatorinstanceof Compares an object to a specified typeBitwise and Bit Shift Operators~ Unary bitwise complement<< Signed left shift>> Signed right shift>>> Unsigned right shift& Bitwise AND^ Bitwise exclusive OR| Bitwise inclusive OR

Questions and ExercisesQuestions1. Consider the following code snippet.

arrayOfInts[j] > arrayOfInts[j+1]Which operators does the code contain?

2. Consider the following code snippet.int i = 10;int n = i++%5;a. What are the values of i and n after the code is executed?b. What are the final values of i and n if instead of using the postfix increment operator (i++), youuse the prefix version (++i))?

3. To invert the value of a boolean, which operator would you use?4. Which operator is used to compare two values, = or == ?5. Explain the following code sample: result = someCondition ? value1 : value2;Exercises

Change the following program to use compound assignments:class ArithmeticDemo{public static void main (String[] args){

Page 42: Java Final Material

42 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

int result = 1 + 2; // result is now 3System.out.println(result);result = result - 1; // result is now 2System.out.println(result);result = result * 2; // result is now 4System.out.println(result);result = result / 2; // result is now 2System.out.println(result);result = result + 8; // result is now 10result = result % 7; // result is now 3System.out.println(result);

}}

In the following program, explain why the value "6" is printed twice in a row:class PrePostDemo {

public static void main(String[] args){int i = 3;

i++;System.out.println(i); // "4"++i;System.out.println(i); // "5"System.out.println(++i); // "6"System.out.println(i++); // "6"System.out.println(i); // "7"

}}

Expressions, Statements, and Blocks

Now that you understand variables and operators, it's time to learn about expressions, statements, and blocks.Operators may be used in building expressions, which compute values; expressions are the core componentsof statements; statements may be grouped into blocks.ExpressionsAn expression is a construct made up of variables, operators, and method invocations, which are constructedaccording to the syntax of the language, that evaluates to a single value. You've already seen examples ofexpressions, illustrated in bold below:

int cadence = 0;anArray[0] = 100;System.out.println("Element 1 at index 0: " + anArray[0]);int result = 1 + 2; // result is now 3if(value1 == value2) System.out.println("value1 == value2");

The data type of the value returned by an expression depends on the elements used in the expression. Theexpression cadence = 0 returns an int because the assignment operator returns a value of the same datatype as its left-hand operand; in this case, cadence is an int. As you can see from the other expressions, anexpression can return other types of values as well, such as boolean or String.The Java programming language allows you to construct compound expressions from various smallerexpressions as long as the data type required by one part of the expression matches the data type of the other.Here's an example of a compound expression:1 * 2 * 3

Page 43: Java Final Material

43 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

In this particular example, the order in which the expression is evaluated is unimportant because the result ofmultiplication is independent of order; the outcome is always the same, no matter in which order you applythe multiplications. However, this is not true of all expressions. For example, the following expression givesdifferent results, depending on whether you perform the addition or the division operation first:x + y / 100 // ambiguousYou can specify exactly how an expression will be evaluated using balanced parenthesis: ( and ). Forexample, to make the previous expression unambiguous, you could write the following:(x + y) / 100 // unambiguous, recommendedIf you don't explicitly indicate the order for the operations to be performed, the order is determined by theprecedence assigned to the operators in use within the expression. Operators that have a higher precedence getevaluated first. For example, the division operator has a higher precedence than does the addition operator.Therefore, the following two statements are equivalent:x + y / 100

x + (y / 100) // unambiguous, recommendedWhen writing compound expressions, be explicit and indicate with parentheses which operators should beevaluated first. This practice makes code easier to read and to maintain.StatementsStatements are roughly equivalent to sentences in natural languages. A statement forms a complete unit ofexecution. The following types of expressions can be made into a statement by terminating the expressionwith a semicolon (;).

Assignment expressions Any use of ++ or -- Method invocations Object creation expressions

Such statements are called expression statements. Here are some examples of expression statements.aValue = 8933.234; // assignment statementaValue++; // increment statementSystem.out.println("Hello World!"); // method invocation statementBicycle myBike = new Bicycle(); // object creation statementIn addition to expression statements, there are two other kinds of statements: declaration statements andcontrol flow statements. A declaration statement declares a variable. You've seen many examples ofdeclaration statements already:double aValue = 8933.234; //declaration statementFinally, control flow statements regulate the order in which statements get executed. You'll learn aboutcontrol flow statements in the next section, Control Flow StatementsBlocksA block is a group of zero or more statements between balanced braces and can be used anywhere a singlestatement is allowed. The following example, BlockDemo, illustrates the use of blocks:class BlockDemo {

public static void main(String[] args) {boolean condition = true;if (condition) { // begin block 1

System.out.println("Condition is true.");} // end block oneelse { // begin block 2

System.out.println("Condition is false.");} // end block 2

}}

Page 44: Java Final Material

44 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Questions and Exercises: Expressions, Statements, and BlocksQuestions

1. Operators may be used in building ___, which compute values.2. Expressions are the core components of ___.3. Statements may be grouped into ___.4. The following code snippet is an example of a ___ expression.5. 1 * 2 * 36. Statements are roughly equivalent to sentences in natural languages, but instead of ending with a

period, a statement ends with a ___.7. A block is a group of zero or more statements between balanced ___ and can be used anywhere a

single statement is allowed.

Page 45: Java Final Material

45 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Lesson 6: Control Flow Statements

The statements inside your source files are generally executed from top to bottom, in the order that theyappear. Control flow statements, however, break up the flow of execution by employing decision making,looping, and branching, enabling your program to conditionally execute particular blocks of code. Thissection describes the decision-making statements (if-then, if-then-else, switch), the loopingstatements (for, while, do-while), and the branching statements (break, continue, return)supported by the Java programming language.

The if-then and if-then-else StatementsThe if-then Statement

The if-then statement is the most basic of all the control flow statements. It tells your program toexecute a certain section of code only if a particular test condition evaluates to true. The syntax is:if (expression){

statement(s);}

The if-then-else Statement

The if-then-else statement provides a secondary path of execution when an "if" clause evaluates tofalse. You could use an if-then-else statement in the applyBrakes method to take some actionif the brakes are applied when the bicycle is not in motion. In this case, the action is to simply print an errormessage stating that the bicycle has already stopped.void applyBrakes(){

if (isMoving) {currentSpeed--;

} else {System.err.println("The bicycle has already stopped!");

}}The following program, IfElseDemo, assigns a grade based on the value of a test score: an A for a scoreof 90% or above, a B for a score of 80% or above, and so on.class IfElseDemo{

public static void main(String[] args){

int testscore = 76;char grade;if (testscore >= 90) {

grade = 'A';} else if (testscore >= 80) {

grade = 'B';} else if (testscore >= 70) {

grade = 'C';} else if (testscore >= 60) {

grade = 'D';} else {

grade = 'F';

Page 46: Java Final Material

46 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

}System.out.println("Grade = " + grade);

}}The output from the program is:

Grade = CYou may have noticed that the value of testscore can satisfy more than one expression in the compoundstatement: 76 >= 70 and 76 >= 60. However, once a condition is satisfied, the appropriate statementsare executed (grade = 'C';) and the remaining conditions are not evaluated.

The switch Statement

Unlike if-then and if-then-else, the switch statement allows for any number of possibleexecution paths. A switch works with the byte, short, char, and int primitive data types. It alsoworks with enumerated types (discussed in Classes and Inheritance) and a few special classes that "wrap"certain primitive types: Character, Byte, Short, and Integer (discussed in Simple Data Objects ).The following program, SwitchDemo, declares an int named month whose value represents a monthout of the year. The program displays the name of the month, based on the value of month, using theswitch statement.

class SwitchDemo{

public static void main(String[] args){

int month = 8;switch (month) {

case 1: System.out.println("January"); break;case 2: System.out.println("February");break;

case 3: System.out.println("March"); break;case 4: System.out.println("April"); break;case 5: System.out.println("May"); break;case 6: System.out.println("June"); break;case 7: System.out.println("July"); break;case 8: System.out.println("August"); break;

case 9: System.out.println("September"); break;case 10: System.out.println("October"); break;case 11: System.out.println("November"); break;case 12: System.out.println("December"); break;default: System.out.println("Invalid month.");

}}

}In this case, "August" is printed to standard output.The body of a switch statement is known as a switch block. Any statement immediately contained by theswitch block may be labeled with one or more case or default labels. The switch statementevaluates its expression and executes the appropriate case.Of course, you could also implement the same thing with if-then-else statements:

int month = 8;if (month == 1) {

System.out.println("January");

Page 47: Java Final Material

47 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

} else if (month == 2) {System.out.println("February");

}. . . // and so on

Deciding whether to use if-then-else statements or a switch statement is sometimes a judgmentcall. You can decide which one to use based on readability and other factors. An if-then-elsestatement can be used to make decisions based on ranges of values or conditions, whereas a switchstatement can make decisions based only on a single integer or enumerated value.Another point of interest is the break statement after each case. Each break statement terminates theenclosing switch statement. Control flow continues with the first statement following the switch block.The break statements are necessary because without them, case statements fall through; that is, withoutan explicit break, control will flow sequentially through subsequent case statements. The followingprogram, SwitchDemo2, illustrates why it might be useful to have case statements fall through:class SwitchDemo2 {

public static void main(String[] args){int month = 2;int year = 2000;int numDays = 0;switch (month) {

case 1:case 3:case 5:case 7:case 8:case 10:case 12:

numDays = 31;break;

case 4:case 6:case 9:case 11:

numDays = 30;break;

case 2:if(((year % 4 == 0)&& !(year % 100 == 0))||(year%400 ==

0))numDays = 29;

elsenumDays = 28;

break;default:

System.out.println("Invalid month.");break;

}System.out.println("Number of Days = " + numDays);

}}This is the output from the program.

Page 48: Java Final Material

48 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Number of Days = 29echnically, the final break is not required because flow would fall out of the gswitch statement anyway.However, we recommend using a break so that modifying the code is easier and less error-prone. Thedefault section handles all values that aren't explicitly handled by one of the case sections.

The while LoopThe while statement continually executes a block of statements while a particular condition is true. Itssyntax can be expressed as:while (expression){

statement(s);}The while statement evaluates expression, which must return a boolean value. If the expressionevaluates to true, the while statement executes the statement(s) in the while block. The whilestatement continues testing the expression and executing its block until the expression evaluates to false.Using the while statement to print the values from 1 through 10 can be accomplished as in the followingWhileDemo program:class WhileDemo{

public static void main(String[] args){

int count = 1;while (count < 11)

{System.out.println("Count is: " + count);count++;

}}

}You can implement an infinite loop using the while statement as follows:while (true){

// your code goes here}The do while Loop

The Java programming language also provides a do-while statement, which can be expressed as follows:do{

statement(s);} while (expression);

The difference between do-while and while is that do-while evaluates its expression at the bottomof the loop instead of the top. Therefore, the statements within the do block are always executed at leastonce, as shown in the following DoWhileDemo program:class DoWhileDemo{

public static void main(String[] args){

int count = 1;do{

Page 49: Java Final Material

49 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

System.out.println("Count is: " + count);count++;

} while (count <= 11);}

}

The for LoopThe for loop provides a compact way to iterate over a range of values. Programmers often refer to it as the"for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The generalform of the for statement can be expressed as follows:

for (initialization; termination; increment){

statement(s);}

When using this version of the for statement, keep in mind that: The initialization expression initializes the loop; it's executed once, as the loop begins. When the termination expression evaluates to false, the loop terminates. The increment expression is invoked after each iteration through the loop; it is perfectly acceptable

for this expression to increment or decrement a value.The following program, ForDemo, uses the general form of the for statement to print the numbers 1through 10 to standard output:class ForDemo{

public static void main(String[] args){

for(int i=1; i<11; i++){

System.out.println("Count is: " + i);}

}}The output of this program is:Count is: 1Count is: 2Count is: 3Count is: 4Count is: 5Count is: 6Count is: 7Count is: 8Count is: 9Count is: 10Notice how the code declares a variable within the initialization expression. The scope of this variable extendsfrom its declaration to the end of the block governed by the for statement, so it can be used in thetermination and increment expressions as well. If the variable that controls a for statement is not neededoutside of the loop, it's best to declare the variable in the initialization expression. The names i, j, and k areoften used to control for loops; declaring them within the initialization expression limits their life span andreduces errors.The three expressions of the for loop are optional; an infinite loop can be created as follows:

for ( ; ; ) { // infinite loop

Page 50: Java Final Material

50 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

// your code goes here}

The for statement also has another form designed for iteration through Collections and arrays This form issometimes referred to as the enhanced for statement, and can be used to make your loops more compact andeasy to read. To demonstrate, consider the following array, which holds the numbers 1 through 10:int[] numbers = {1,2,3,4,5,6,7,8,9,10};The following program, EnhancedForDemo, uses the enhanced for to loop through the array:class EnhancedForDemo{

public static void main(String[] args){

int[] numbers = {1,2,3,4,5,6,7,8,9,10};for (int item : numbers)

{System.out.println("Count is: " + item);

}}

}In this example, the variable item holds the current value from the numbers array. The output from thisprogram is the same as before:Count is: 1Count is: 2Count is: 3Count is: 4Count is: 5Count is: 6Count is: 7Count is: 8Count is: 9Count is: 10We recommend using this form of the for statement instead of the general form whenever possible.

Branching Statements

The break StatementThe break statement has two forms: labeled and unlabeled. You saw the unlabeled form in the previousdiscussion of the switch statement. You can also use an unlabeled break to terminate a for, while, ordo-while loop, as shown in the following BreakDemo program:class BreakDemo{

public static void main(String[] args){int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076,2000, 8, 622, 127

};int searchfor = 12;int i;boolean foundIt = false;for (i = 0; i < arrayOfInts.length; i++)

{if (arrayOfInts[i] == searchfor)

Page 51: Java Final Material

51 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

{foundIt = true;break;

}}if (foundIt)

{System.out.println("Found " + searchfor + " at index " + i);

}else{

System.out.println(searchfor + " not in the array");}

}}This program searches for the number 12 in an array. The break statement, shown in boldface, terminatesthe for loop when that value is found. Control flow then transfers to the print statement at the end of theprogram. This program's output is:

Found 12 at index 4An unlabeled break statement terminates the inner most switch, for, while, or do-while statement,but a labeled break terminates an outer statement. The following program, BreakWithLabelDemo, issimilar to the previous program, but uses nested for loops to search for a value in a two-dimensional array.When the value is found, a labeled break terminates the outer for loop (labeled "search"):

class BreakWithLabelDemo{

public static void main(String[] args){int[][] arrayOfInts = { { 32, 87, 3, 589 },

{ 12, 1076, 2000, 8 },{ 622, 127, 77, 955 }

};int searchfor = 12;int i;int j = 0;boolean foundIt = false;

search:for (i = 0; i < arrayOfInts.length; i++) {

for (j = 0; j < arrayOfInts[i].length; j++) {if (arrayOfInts[i][j] == searchfor) {

foundIt = true;break search;

}}

}

if (foundIt){

System.out.println("Found " + searchfor +" at " + i + ", " +j);

Page 52: Java Final Material

52 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

}else{

System.out.println(searchfor+ " not in the array");}

}}This is the output of the program.

Found 12 at 1, 0The break statement terminates the labeled statement; it does not transfer the flow of control to the label.Control flow is transferred to the statement immediately following the labeled (terminated) statement.

The continue Statement

The continue statement skips the current iteration of a for, while , or do-while loop. The unlabeledform skips to the end of the innermost loop's body and evaluates the boolean expression that controls theloop. The following program, ContinueDemo , steps through a String, counting the occurences of theletter "p". If the current character is not a p, the continue statement skips the rest of the loop and proceedsto the next character. If it is a "p", the program increments the letter count.

class ContinueDemo{

public static void main(String[] args){String searchMe = "peter piper picked a peck of pickled peppers";int max = searchMe.length();int numPs = 0;for (int i = 0; i < max; i++)

{//interested only in p'sif (searchMe.charAt(i) != 'p')

continue;//process p'snumPs++;

}System.out.println("Found " + numPs + " p's in the string.");

}}Here is the output of this program:Found 9 p's in the string.To see this effect more clearly, try removing the continue statement and recompiling. When you run theprogram again, the count will be wrong, saying that it found 35 p's instead of 9.A labeled continue statement skips the current iteration of an outer loop marked with the given label. Thefollowing example program, ContinueWithLabelDemo, uses nested loops to search for a substringwithin another string. Two nested loops are required: one to iterate over the substring and one to iterate overthe string being searched. The following program, ContinueWithLabelDemo, uses the labeled form ofcontinue to skip an iteration in the outer loop.

class ContinueWithLabelDemo{

Page 53: Java Final Material

53 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

public static void main(String[] args){String searchMe = "Look for a substring in me";String substring = "sub";boolean foundIt = false;int max = searchMe.length() - substring.length();

test:for (int i = 0; i <= max; i++)

{int n = substring.length();int j = i;int k = 0;while (n-- != 0)

{if (searchMe.charAt(j++)!= substring.charAt(k++))

{continue test;

}}foundIt = true;break test;

}System.out.println(foundIt ? "Found it" : "Didn't find it");

}}Here is the output from this program.

Found it

Labelled Loops

In Java, we can give a label to a block of statements. A label is any valid Java variable name. To give a labelto a loop, place it before the loop with a colon at the end. Example:

Loop1: for(…………..){

…………..…………..

}A block of statements can be labeled as shown below:

Block1:{…………..…………..

Block2: {………….………….

}}

We have seen that a simple break statement causes the control to jump outside the nearest loop and a simplecontinue statement restarts the current loop. If we want to jump outside a nested loops or to continue a loopthat is outside the current one, then we may have to use the labeled break and labeled continue statements.Example:

outer: for ( int m = 1; m <11; m++)

Page 54: Java Final Material

54 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

{for( int n = 1; n<11; n++){

System.out.print(“ “ + m*n);if (n == m)

continue outer;

}}

Here, the continue statement terminates the inner loop when n = m and continues with the next iteration of theouter loop.Following program illustrates the use of break and continue statements.class ContinueBreak{

public static void main(String args[]){

LOOP1 : for(int i = 1; i<100; i++){

System.out.println(“ “);if( i>=10); break;for( int j = 1; j<100 ; j++){

System.out.print(“ * “);if( j == i)

continue LOOP1;}

}System.out.println(“termination by break”);

}}Output :** ** * ** * * ** * * * ** * * * * ** * * * * * ** * * * * * * ** * * * * * * * *

The return Statement

The last of the branching statements is the return statement. The return statement exits from the currentmethod, and control flow returns to where the method was invoked. The return statement has two forms:one that returns a value, and one that doesn't. To return a value, simply put the value (or an expression thatcalculates the value) after the return keyword.

return ++count;The data type of the returned value must match the type of the method's declared return value. When amethod is declared void, use the form of return that doesn't return a value.

Page 55: Java Final Material

55 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

return;The Classes and Objects lesson will cover everything you need to know about writing methods.

Questions and Exercises: Control Flow StatementsQuestions

1. The most basic control flow statement supported by the Java programming language is the ___statement.

2. The ___ statement allows for any number of possible execution paths.3. The ___ statement is similar to the while statement, but evaluates its expression at the ___ of the

loop.4. How do you write an infinite loop using the for statement?5. How do you write an infinite loop using the while statement?

ExercisesConsider the following code snippet.

if (aNumber >= 0)if (aNumber == 0) System.out.println("first string");else System.out.println("second string");System.out.println("third string");

a. What output do you think the code will produce if aNumber is 3?b. Write a test program containing the previous code snippet; make aNumber 3. What is the output of

the program? Is it what you predicted? Explain why the output is what it is; in other words, what isthe control flow for the code snippet?

c. Using only spaces and line breaks, reformat the code snippet to make the control flow easier tounderstand.

d. Use braces, { and }, to further clarify the code.

Page 56: Java Final Material

56 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Lesson 7: Classes and Objects

ClassThe introduction to object-oriented concepts in the lesson titled Object-oriented ProgrammingConcepts used a bicycle class as an example, with racing bikes, mountain bikes, and tandem bikesas subclasses. Here is sample code for a possible implementation of a Bicycle class, to giveyou an overview of a class declaration. Subsequent sections of this lesson will back up andexplain class declarations step by step. For the moment, don't concern yourself with the details.public class Bicycle{

// the Bicycle class has three fieldspublic int cadence;public int gear;public int speed;

// the Bicycle class has one constructorpublic Bicycle(int startCadence, int startSpeed, int startGear)

{gear = startGear;cadence = startCadence;speed = startSpeed;

}// the Bicycle class has four methodspublic void setCadence(int newValue)

{cadence = newValue;

}public void setGear(int newValue) {

gear = newValue;}

public void applyBrake(int decrement) {speed -= decrement;

}public void speedUp(int increment) {

speed += increment;}}

A class declaration for a MountainBike class that is a subclass of Bicycle might look likethis:public class MountainBike extends Bicycle {

// the MountainBike subclass has one fieldpublic int seatHeight;

// the MountainBike subclass has one constructorpublic MountainBike(int startHeight, int startCadence,

int startSpeed, int startGear) {super(startCadence, startSpeed, startGear);seatHeight = startHeight;

}

Page 57: Java Final Material

57 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

// the MountainBike subclass has one methodpublic void setHeight(int newValue) {

seatHeight = newValue;}

}MountainBike inherits all the fields and methods of Bicycle and adds the fieldseatHeight and a method to set it (mountain bikes have seats that can be moved up and downas the terrain demands).

Declaring a ClassYou've seen classes defined in the following way:class classname{

//field and method declarations}This is a class declaration. The class body (the area between the braces) contains all the code that providesfor the life cycle of the objects created from the class: constructors for initializing new objects, declarationsfor the fields that provide the state of the class and its objects, and methods to implement the behavior of theclass and its objects.The preceding class declaration is a minimal one—it contains only those components of a class declarationthat are required. You can provide more information about the class, such as the name of its superclass,whether it implements any interfaces, and so on, at the start of the class declaration. For example,class MyClass extends MySuperClass implements YourInterface{

//field, constructor, and method declarations}means that MyClass is a subclass of MySuperClass and that it implements the YourInterfaceinterface.You can also add modifiers like public or private at the very beginning—so you can see that the opening lineof a class declaration can become quite complicated. The modifiers public and private, which determine whatother classes can access MyClass, are discussed later in this lesson. The lesson on interfaces and inheritancewill explain how and why you would use the extends and implements keywords in a class declaration. For themoment you do not need to worry about these extra complications.In general, class declarations can include these components, in order:

1. Modifiers such as public, private, and a number of others that you will encounter later.2. The class name, with the initial letter capitalized by convention.3. The name of the class's parent (superclass), if any, preceded by the keyword extends. A class can

only extend (subclass) one parent.4. A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword

implements. A class can implement more than one interface.5. The class body, surrounded by braces, {}.

Declaring Member VariablesThere are several kinds of variables:

Member variables in a class—these are called fields. Variables in a method or block of code—these are called local variables. Variables in method declarations—these are called parameters.

The Bicycle class uses the following lines of code to define its fields:public int cadence;public int gear;

Page 58: Java Final Material

58 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

public int speed;Field declarations are composed of three components, in order:

1. Zero or more modifiers, such as public or private.2. The field's type.3. The field's name.

The fields of Bicycle are named cadence, gear, and speed and are all of data type integer (int). Thepublic keyword identifies these fields as public members, accessible by any object that can access the class.Example:class rectangle{

int length;int width;

}

Access ModifiersThe first (left-most) modifier used lets you control what other classes have access to a member field. For themoment, consider only public and private. Other access modifiers will be discussed later.

public modifier—the field is accessible from all classes. private modifier—the field is accessible only within its own class.

In the spirit of encapsulation, it is common to make fields private. This means that they can only be directlyaccessed from the Bicycle class. We still need access to these values, however. This can be done indirectly byadding public methods that obtain the field values for us:public class Bicycle {

private int cadence;private int gear;private int speed;public Bicycle(int startCadence, int startSpeed, int startGear){

gear = startGear;cadence = startCadence;speed = startSpeed;

}public int getCadence(){

return cadence;}public void setCadence(int newValue){

cadence = newValue;}public int getGear(){

return gear;}public void setGear(int newValue){

gear = newValue;}public int getSpeed()

Page 59: Java Final Material

59 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

{return speed;

}

public void applyBrake(int decrement){

speed -= decrement;}public void speedUp(int increment){

speed += increment;}

}TypesAll variables must have a type. You can use primitive types such as int, float, boolean, etc. Or you canuse reference types, such as strings, arrays, or objects.Variable NamesAll variables, whether they are fields, local variables, or parameters, follow the same naming rules andconventions that were covered in the Language Basics lesson, Variables—Naming .In this lesson, be aware that the same naming rules and conventions are used for method and class names,except that

the first letter of a class name should be capitalized, and the first (or only) word in a method name should be a verb.

Defining MethodsMethods are declared inside the body of the class but immediately after the declaration of instance variable.The general form of a method declaration ismodifier Return-type MethodName (parameter-list){

Method-body;}Here is an example of a typical method declaration:public double calculateAnswer(double wingSpan, int numberOfEngines,double length, double grossTons){

//do the calculation here}The only required elements of a method declaration are the method's return type, name, a pair of parentheses,(), and a body between braces, {}.More generally, method declarations have 5 components, in order:

1. Modifiers—such as public, private, and others you will learn about later.2. The return type—the data type of the value returned by the method, or void if the method does not

return a value.3. The method name—the rules for field names apply to method names as well, but the convention is a

little different.4. The parameter list in parenthesis—a comma-delimited list of input parameters, preceded by their data

types, enclosed by parentheses, (). If there are no parameters, you must use empty parentheses.5. The method body, enclosed between braces—the method's code, including the declaration of local

variables, goes here.Modifiers, return types, and parameters will be discussed later in this lesson.

Page 60: Java Final Material

60 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Method OverloadingThe Java programming language supports overloading methods, and Java can distinguish between methodswith different method parameters. This means that methods within a class can have the same name if theyhave different parameter lists.Suppose that you have a class that can use calligraphy to draw various types of data (strings, integers, and soon) and that contains a method for drawing each data type. It is cumbersome to use a new name for eachmethod—for example, drawString, drawInteger, drawFloat, and so on. In the Java programminglanguage, you can use the same name for all the drawing methods but pass a different argument list to eachmethod. Thus, the data drawing class might declare four methods named draw, each of which has a differentparameter list.public class DataArtist {

...public void draw(String s) {

...}public void draw(int i) {

...}public void draw(double f) {

...}public void draw(int i, double f) {

...}

}Overloaded methods are differentiated by the number and the type of the arguments passed into the method.In the code sample, draw(String s) and draw(int i) are distinct and unique methods because theyrequire different argument types.You cannot declare more than one method with the same name and the same number and type of arguments,because the compiler cannot tell them apart.The compiler does not consider return type when differentiating methods, so you cannot declare two methodswith the same signature even if they have a different return type.

ObjectsA typical Java program creates many objects, which as you know, interact by invoking methods. Throughthese object interactions, a program can carry out various tasks, such as implementing a GUI, running ananimation, or sending and receiving information over a network. Once an object has completed the work forwhich it was created, its resources are recycled for use by other objects.

Creating ObjectsAs you know, an object in Java is essentially a block of memory that contains space to store all the instancevariables. Creating an object is also referred to as instantiating an object.Objects in java are created using the new operator. The new operator creates an object of the specified classand returns a reference to that object. Here is an example of creating an object of class Rectangle.

Rectangle rectOne //Declare the objectrectOne = new Rectangle(); //instantiate the object

The first line declares a variable to hold the object reference and the second line actually assigns the objectreference to the of the variable. The rectone is now an object of the Rectangle class.

Page 61: Java Final Material

61 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Both statements can be combined into one as shown below:Rectangle rectone= new Rectangle();

Instantiating a ClassThe new operator instantiates a class by allocating memory for a new object and returning a reference to thatmemory. The new operator also invokes the object constructor.

Note: The phrase "instantiating a class" means the same thing as "creating an object." When you create anobject, you are creating an "instance" of a class, therefore "instantiating" a class.

The new operator requires a single, postfix argument: a call to a constructor. The name of the constructorprovides the name of the class to instantiate.The new operator returns a reference to the object it created. This reference is usually assigned to a variableof the appropriate type, like:Point originOne = new Point(23, 94);The reference returned by the new operator does not have to be assigned to a variable. It can also be useddirectly in an expression. For example:int height = new Rectangle().height;

Accessing Class MembersOnce you've created an object, you probably want to use it for something. You may need to use the value ofone of its fields, change one of its fields, or call one of its methods to perform an action.Accessing an Class variableClass variables are accessed by their name. You may use a simple name for a variable within its own class.For example, we can add a statement within the Rectangle class that prints the width and height:System.out.println("Width and height are: " + width + ", " + height);In this case, width and height are simple names.Code that is outside the object's class must use an object reference or expression, followed by the dot (.)operator, followed by a simple field name, as in:

ObjectName.variableNameFor example, the code in the CreateObjectDemo class is outside the code for the Rectangle class. Soto refer to the origin, width, and height fields within the Rectangle object named rectOne, theCreateObjectDemo class must use the names rectOne.origin, rectOne.width, andrectOne.height, respectively. The program uses two of these names to display the width and theheight of rectOne:System.out.println("Width of rectOne: " + rectOne.width);System.out.println("Height of rectOne: " + rectOne.height);Attempting to use the simple names width and height from the code in the CreateObjectDemo classdoesn't make sense — those fields exist only within an object — and results in a compiler error.Recall that the new operator returns a reference to an object. So you could use the value returned from new toaccess a new object's fields:

int height = new Rectangle().height;This statement creates a new Rectangle object and immediately gets its height. In essence, the statementcalculates the default height of a Rectangle. Note that after this statement has been executed, the programno longer has a reference to the created Rectangle, because the program never stored the referenceanywhere. The object is unreferenced, and its resources are free to be recycled by the Java Virtual Machine.The instance variable of the Rectangle class may be accessed and assigned values as follow:

Page 62: Java Final Material

62 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

rectone.width = 10;rectone.height = 15;

Calling an class MethodsYou also use an object reference to invoke an object's method. You append the method's simple name to theobject reference, with an intervening dot operator (.). Also, you provide, within enclosing parentheses, anyarguments to the method. If the method does not require any arguments, use empty parentheses.

objectName.methodName(argumentList);or

objectName.methodName();The Rectangle class has two methods: getArea() to compute the rectangle's area and move() tochange the rectangle's origin. Here's the CreateObjectDemo code that invokes these two methods:System.out.println("Area of rectOne: " + rectOne.getArea());...rectTwo.getData(40, 72);The first statement invokes rectOne's getArea() method and displays the results. The second lineinvokes getData() method and then passes values 40 and 72 for the x and y parameters. This method thenassigns value to length and width variables respectively. The method is shown below:

void getData(int x,int y){

length = x;width = y;

}

As with instance fields, objectName must be a name of an object. You can use a variable name, but you alsocan use any expression that returns an object reference. The new operator returns an object reference, so youcan use the value returned from new to invoke a new object's methods:

new Rectangle(100, 50).getArea()The expression new Rectangle(100, 50) returns an object reference that refers to a Rectangleobject. As shown, you can use the dot notation to invoke the new Rectangle's getArea() method tocompute the area of the new rectangle.Application of class and object:class Rectangle{

int length,width;void getData(int x, int y){

length = x;width = y;

}int rectArea(){

int area = length * width;return(area);

}}class rectArea{public static void main(String args[]){

Page 63: Java Final Material

63 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

int area1,area2;Rectangle rect1 = new Rectangle();Rectangle rect2 = new Rectangle();rect1.length = 15;rect1.width = 10;area1 = rect1.length * rect1.width;rect2.getData(20,12);area2 = rect2.rectArea();System.out.println(“Area1 = “ + area1);System.out.println(“Area2 = “ + area2);

}}Output would be:

Area1 = 150Area2 = 240

ConstructorWe know that all the objects that are created must be given initial values. We have done this earlier using twoapproaches. The first approach uses the dot operator to access the instance variables and then assigns valuesto them individually. The second approach takes the help of a method like getData to initialize each objectindividually using statements like,

rect1.getData(15,10);it would be simpler and more concise to initialize an object when it is first created. Java supports a specialtype of method, called constructor, that enables an object to initialize itself when it is created.Constructors have the same name as the class itself. Secondly, they do not specify a return type, not evenvoid.

Initializing an ObjectHere's the code for the Point class:class Point {

int x = 0;int y = 0;Point(int a, int b) //constructor{

x = a;y = b;

}}This class contains a single constructor. You can recognize a constructor because its declaration uses the samename as the class and it has no return type. The constructor in the Point class takes two integer arguments,as declared by the code (int a, int b). The following statement provides 23 and 94 as values for thosearguments:Point originOne = new Point(23, 94);The result of executing this statement can be illustrated in the next figure:

Page 64: Java Final Material

64 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Here's the code for the Rectangle class, which contains one constructor:class Rectangle{

int width = 0;int height = 0;Rectangle(int x, int y){

width = y;length = x;

}// a method to calculate the are of rectangleint rectArea(){

return(length * width);}

}class RectangleArea{Public static void main(string args[]){

Rectangle rect1 = new Rectangle(15,10); // calling constructorint area1 = rect1.rectArea();System.out.println(“Area1 = “ + area1);

}}Output will be :

Area1 = 150

The Garbage CollectorSome object-oriented languages require that you keep track of all the objects you create and that youexplicitly destroy them when they are no longer needed. Managing memory explicitly is tedious and error-prone. The Java platform allows you to create as many objects as you want, and you don't have to worry aboutdestroying them. The Java runtime environment deletes objects when it determines that they are no longerbeing used. This process is called garbage collection.An object is eligible for garbage collection when there are no more references to that object. References thatare held in a variable are usually dropped when the variable goes out of scope. Or, you can explicitly drop anobject reference by setting the variable to the special value null. Remember that a program can havemultiple references to the same object; all references to an object must be dropped before the object is eligiblefor garbage collection.

Page 65: Java Final Material

65 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

The Java runtime environment has a garbage collector that periodically frees the memory used by objects thatare no longer referenced. The garbage collector does its job automatically when it determines that the time isright.

the this KeywordWithin an instance method or a constructor, this is a reference to the current object — the object whosemethod or constructor is being called. You can refer to any member of the current object from within aninstance method or a constructor by using this.Using this with a FieldThe most common reason for using the this keyword is because a field is shadowed by a method orconstructor parameter.For example, the Point class was written like thisclass Point {

public int x = 0;public int y = 0;//constructorPoint(int a, int b) {

x = a;y = b;

}}but it could have been written like this:class Point {

public int x = 0;public int y = 0;//constructorPoint(int x, int y) {

this.x = x;this.y = y;

}}Each argument to the constructor shadows one of the object's fields — inside the constructor x is a local copyof the constructor's first argument. To refer to the Point field x, the constructor must use this.x.

Controlling Access to Members of a ClassAccess level modifiers determine whether other classes can use a particular field or invoke a particularmethod. There are two levels of access control:

At the top level—public, or package-private (no explicit modifier). At the member level—public, private, protected, or package-private (no explicit

modifier).A class may be declared with the modifier public, in which case that class is visible to all classeseverywhere. If a class has no modifier (the default, also known as package-private), it is visible only withinits own package (packages are named groups of related classes—you will learn about them in a later lesson.)At the member level, you can also use the public modifier or no modifier (package-private) just as withtop-level classes, and with the same meaning. For members, there are two additional access modifiers:private and protected. The private modifier specifies that the member can only be accessed in itsown class. The protected modifier specifies that the member can only be accessed within its own package(as with package-private) and, in addition, by a subclass of its class in another package.The following table shows the access to members permitted by each modifier.

Page 66: Java Final Material

66 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Access Levels

Modifier Class Package Subclass World

public Y Y Y Y

protected Y Y Y N

no modifier Y Y N N

private Y N N N

The first data column indicates whether the class itself has access to the member defined by the access level.As you can see, a class always has access to its own members. The second column indicates whether classesin the same package as the class (regardless of their parentage) have access to the member. The third columnindicates whether subclasses of the class — declared outside this package — have access to the member. Thefourth column indicates whether all classes have access to the member.Access levels affect you in two ways. First, when you use classes that come from another source, such as theclasses in the Java platform, access levels determine which members of those classes your own classes canuse. Second, when you write a class, you need to decide what access level every member variable and everymethod in your class should have.Let's look at a collection of classes and see how access levels affect visibility. The following figure shows thefour classes in this example and how they are related.

Understanding Instance and Class MembersIn this section, we discuss the use of the static keyword to create fields and methods that belong to theclass, rather than to an instance of the class.Static VariablesWhen a number of objects are created from the same class blueprint, they each have their own distinct copiesof instance variables. In the case of the Bicycle class, the instance variables are cadence, gear, andspeed. Each Bicycle object has its own values for these variables, stored in different memory locations.Sometimes, you want to have variables that are common to all objects. This is accomplished with thestatic modifier. Fields that have the static modifier in their declaration are called static fields or classvariables. They are associated with the class, rather than with any object. Every instance of the class shares aclass variable, which is in one fixed location in memory. Any object can change the value of a class variable,but class variables can also be manipulated without creating an instance of the class. Such members can bedefined as follows:

static int count;For example, suppose you want to create a number of Bicycle objects and assign each a serial number,beginning with 1 for the first object. This ID number is unique to each object and is therefore an instancevariable. At the same time, you need a field to keep track of how many Bicycle objects have been createdso that you know what ID to assign to the next one. Such a field is not related to any individual object, but tothe class as a whole. For this you need a class variable, numberOfBicycles, as follows:public class Bicycle{

private int cadence;private int gear;private int speed;// add an instance variable for the object IDprivate int id;// add a class variable for the number of Bicycle objects

instantiatedprivate static int numberOfBicycles = 0;

}

Page 67: Java Final Material

67 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Class variables are referenced by the class name itself, as inBicycle.numberOfBicycles

This makes it clear that they are class variables.

Note: You can also refer to static fields with an object reference likemyBike.numberOfBicycles

but this is discouraged because it does not make it clear that they are class variables.

Static MethodsThe Java programming language supports static methods as well as static variables. Static methods, whichhave the static modifier in their declarations, should be invoked with the class name, without the need forcreating an instance of the class, as in

ClassName.methodName(args)

Note: You can also refer to static methods with an object reference likeinstanceName.methodName(args)

but this is discouraged because it does not make it clear that they are class methods.

A common use for static methods is to access static fields. For example, we could add a static method to theBicycle class to access the numberOfBicycles static field:static int getNumberOfBicycles() {

return numberOfBicycles;}We can define our own static methods as shown below:class MathOperation{

static float mul(float x, float y){

return(x*y);}static float divide (float x, float y){

return(x/y);}

}class MathApplication{

public static void main(String args[]){

float a = Mathoperation.mul(4.0,5.0);float b = Mathoperation.divide(a,2.0);System.out.println(“b = “ + b);

}}Output will be:

B = 10.0Not all combinations of instance and class variables and methods are allowed:

Instance methods can access instance variables and instance methods directly. Instance methods can access class variables and class methods directly. Class methods can access class variables and class methods directly.

Page 68: Java Final Material

68 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Class methods cannot access instance variables or instance methods directly—they must use anobject reference. Also, class methods cannot use the this keyword as there is no instance forthis to refer to.

Final variablesThe static modifier, in combination with the final modifier, is also used to define constants. Thefinal modifier indicates that the value of this field cannot change.For example, the following variable declaration defines a constant named PI,static final double PI = 3.141592653589793;Constants defined in this way cannot be reassigned, and it is a compile-time error if your program tries to doso. By convention, the names of constant values are spelled in uppercase letters. If the name is composed ofmore than one word, the words are separated by an underscore (_).

Page 69: Java Final Material

69 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Lesson 8: Inheritance and Interface

InheritanceIn the preceding lessons, you have seen inheritance mentioned several times. In the Java language, classes canbe derived from other classes, thereby inheriting fields and methods from those classes.

Definitions:A class that is derived from another class is called a subclass (also a derived class, extended class, or childclass). The class from which the subclass is derived is called a superclass (also a base class or a parent class).Excepting Object, which has no superclass, every class has one and only one direct superclass (singleinheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of Object.Classes can be derived from classes that are derived from classes that are derived from classes, and so on, andultimately derived from the topmost class, Object. Such a class is said to be descended from all the classesin the inheritance chain stretching back to Object.

The idea of inheritance is simple but powerful: When you want to create a new class and there is already aclass that includes some of the code that you want, you can derive your new class from the existing class. Indoing this, you can reuse the fields and methods of the existing class without having to write them yourself.A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors arenot members, so they are not inherited by subclasses, but the constructor of the superclass can be invokedfrom the subclass.

What You Can Do in a SubclassA subclass inherits all of the public and protected members of its parent, no matter what package the subclassis in. If the subclass is in the same package as its parent, it also inherits the package-private members of theparent. You can use the inherited members as is, replace them, hide them, or supplement them with newmembers:

The inherited fields can be used directly, just like any other fields. You can declare a field in the subclass with the same name as the one in the superclass, thus

hiding it (not recommended). You can declare new fields in the subclass that are not in the superclass. The inherited methods can be used directly as they are. You can write a new instance method in the subclass that has the same signature as the one in

the superclass, thus overriding it. You can write a new static method in the subclass that has the same signature as the one in the

superclass, thus hiding it. You can declare new methods in the subclass that are not in the superclass. You can write a subclass constructor that invokes the constructor of the superclass, either

implicitly or by using the keyword super.The following sections in this lesson will expand on these topics.

Private Members in a SuperclassA subclass does not inherit the private members of its parent class. However, if the superclass has publicor protected methods for accessing its private fields, these can also be used by the subclass.A nested class has access to all the private members of its enclosing class—both fields and methods.Therefore, a public or protected nested class inherited by a subclass has indirect access to all of the privatemembers of the superclass.The inheritance may take different forms:

Single inheritance(only one super class) Multiple inheritance(several super classes)

Page 70: Java Final Material

70 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Hierarchical inheritance(one super class, many subclasses) Multilevel inheritance(derived from derived class)

These forms are shown below:

A

B

A

B

C

B D

A

C

A B

C

(a) Single Inheritance (b) Hierarchical Inheritance

(c) Multilevel inheritance (d) Multiple inheritance

Defining a subclassA subclass is defined as follows:

class subclasname entends superclassname{

Variable declaration;Method declaration;

}The keyword extends signifies that the properties of the superclassname are extends to the subclassname.The subclass will now contain its own variables and methods as well those of the super class. Application ofsingle inheritance:class Room{

int length;int breadth;Room(int x, int y)l

Length = x;breadth = y;

}int area(){

return( length * breadth);}

}class Bedroom extends Room

Page 71: Java Final Material

71 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

{int height;Bedroom(int x, int y, int z){

super(x,y); // pass values to superclassheight = z;

}int volume(){

return(length * breadth * height);}

}class InherTest{

public static void main(string args[]){

Bedroom room1 = new Bedroom(14,12,10);int area1 = room1.area(); // superclass methodint volume1 = room1.volume(); //baseclass methodSystem.out.println(“Area1 = “+ area1);System.out.println(“Volume = “+ volume);

}}The output of program is:

Area1 = 168Volume = 1680

The program defines a class Room and extends it to another class BedRoom. Note that the class BedRoomdefines its own data members and methods. The subclass BedRoom now includes three instance variables,namely length, breadth and height and two methods, area and volume.The constructor in the derived class uses the super keyword to pass values that are required by the vaseconstructor. The statement

BedRoom room1 = new BedRoom(14,12,10);Calls first the BedRoom constructor method, which in turn class the Room constructor method by using thesuper keyword.Finally, the object room1 of the subclass BedRoom calls the method area defined in the super class as wellas the method volume defined in the subclass itself.

Multilevel InheritanceA common requirement in object-oriented programming is the use of a derived class as a super class. Javasupports this concept and uses it intensively in building its class library. This concept allows us to build achian of classes as shown in figure.

Page 72: Java Final Material

72 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

A

B

C

Grandfather

Father

Child

Superclass

Intermediate superclass

Subclass

The clas A serves as a base class for the derived class B which in turn serves as a base class for the derivedclass C. the chain ABC is known as inheritance path.A derived class with multilevel base classes is declared as follows.

class A{

………….………….

}class B extends A // First level{

………….………….

}class c extends B // Second level{

………….………….

}This process may be extended to any number of levels. The class C can inherit the members of both A and Bas shown in figure.

class B members

class A members

class C members

C contains B which contains A

Page 73: Java Final Material

73 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Hierarchical InheritanceAnother interesting application of inheritance is to use it as a support to the hierarchical design of a program.Many programming problems can be cast into a hierarchy where certain features of one level are shared bymany others below the level. As and example, figure shows a hierarchical classification of accounts in acommercial bank. This is possible because all the accounts possess certain common features.

Account

Saving Fixed-deposit Current

Short Medium Long

Hierarchical classification of bank accounts

Overriding and Hiding MethodsInstance MethodsAn instance method in a subclass with the same signature (name, plus the number and the type of itsparameters) and return type as an instance method in the superclass overrides the superclass's method.The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is"close enough" and then to modify behavior as needed. The overriding method has the same name, numberand type of parameters, and return type as the method it overrides. An overriding method can also return asubtype of the type returned by the overridden method. This is called a covariant return type.

Class MethodsIf a subclass defines a class method with the same signature as a class method in the superclass, the method inthe subclass hides the one in the superclass.The distinction between hiding and overriding has important implications. The version of the overriddenmethod that gets invoked is the one in the subclass. The version of the hidden method that gets invokeddepends on whether it is invoked from the superclass or the subclass. Let's look at an example that containstwo classes. The first is Animal, which contains one instance method and one class method:public class Animal{

public static void testClassMethod(){

System.out.println("The class method in Animal.");}public void testInstanceMethod(){

System.out.println("The instance method in Animal.");}

}

Page 74: Java Final Material

74 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

The second class, a subclass of Animal, is called Cat:public class Cat extends Animal{

public static void testClassMethod(){

System.out.println("The class method in Cat.");}public void testInstanceMethod(){

System.out.println("The instance method in Cat.");}public static void main(String[] args){

Cat myCat = new Cat();Animal myAnimal = myCat;Animal.testClassMethod();myAnimal.testInstanceMethod();

}}The Cat class overrides the instance method in Animal and hides the class method in Animal. The mainmethod in this class creates an instance of Cat and calls testClassMethod() on the class andtestInstanceMethod() on the instance.The output from this program is as follows:The class method in Animal.The instance method in Cat.As promised, the version of the hidden method that gets invoked is the one in the superclass, and the versionof the overridden method that gets invoked is the one in the subclass.class Alpha{

int x;Alpha(int x){

this.x = x;}void display() //method defined{

System.out.println(“Alpha x = “ + x);}

}class Beta extends Alpha{

int y;Beta(int x,int y){

super(x);this.y = y;

}void display() //method defined again{

System.out.println(“Alpha x = “ + x);

Page 75: Java Final Material

75 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

System.out.println(“Beta y = “ + y);}

}class OverrideTest{

public static void main(string args[]){

Beta b1 = new Beta(100,200);b1.dispaly();

}}Output:

Alpha x = 100Beta y = 200

Note: the method display() defined in the subclass is invoked.

The finalize() MethodThe Object class provides a callback method, finalize(), that may be invoked on an object when itbecomes garbage. Object's implementation of finalize() does nothing - you can overridefinalize() to do cleanup, such as freeing resources.The finalize() method may be called automatically by the system, but when it is called, or even if it iscalled, is uncertain. Therefore, you should not rely on this method to do your cleanup for you. For example, ifyou don't close file descriptors in your code after performing I/O and you expect finalize() to close themfor you, you may run out of file descriptors.

Final Classes and MethodsYou can declare some or all of a class's methods final. All methods and variables can be overridden by defaultin subclass.You use the final keyword in a method declaration to indicate that the method cannot beoverridden by subclasses. The Object class does this - a number of its methods are final. Example:

final int SIZE = 100;final void showstatus() { ………..}

You might wish to make a method final if it has an implementation that should not be changed. For example,you might want to make the getFirstPlayer method in this ChessAlgorithm class final:

class ChessAlgorithm {final ChessPlayer getFirstPlayer() {return ChessPlayer.WHITE;

}}

Methods called from constructors should generally be declared final. If a constructor calls a non-final method,a subclass may redefine that method with surprising or undesirable results.Note that you can also declare an entire class final — this prevents the class from being subclassed. This isparticularly useful, for example, when creating an immutable class like the String class.Sometimes we may like to prevent a class being further subclasses for security reasons. A class that cannot besubclassed is called final class. This is achieved by

final class AClass {……}final class BClass extends AClass {………}

Abstract Methods and Classes

Page 76: Java Final Material

76 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Using making final we ensure that the method is not redefined in a subclass. That is, the method can never besubclassed. Java allows us to do something that is exactly opposite to this. That is, we can indicate that amethod must always be redefined in a subclass, thus making overriding compulsory.An abstract class is a class that is declared abstract—it may or may not include abstract methods.Abstract classes cannot be instantiated, but they can be subclassed.An abstract method is a method that is declared without an implementation (without braces, and followed bya semicolon), like this:abstract void moveTo(double deltaX, double deltaY);If a class includes abstract methods, the class itself must be declared abstract, as in:

abstract class GraphicObject{

abstract void draw();}

When an abstract class is subclassed, the subclass usually provides implementations for all of the abstractmethods in its parent class. However, if it does not, the subclass must also be declared abstract.

Note: All of the methods in an interface are implicitly abstract, so the abstract modifier is not used withinterface methods (it could be—it's just not necessary).

Abstract Classes versus InterfacesUnlike interfaces, abstract classes can contain fields that are not static and final, and they can containimplemented methods. Such abstract classes are similar to interfaces, except that they provide a partialimplementation, leaving it to subclasses to complete the implementation. If an abstract class contains onlyabstract method declarations, it should be declared as an interface instead.Questions1. Consider the following two classes:public class ClassA {

public void methodOne(int i) {}public void methodTwo(int i) {}public static void methodThree(int i) {}public static void methodFour(int i) {}

}

public class ClassB extends ClassA {public static void methodOne(int i) {}public void methodTwo(int i) {}public void methodThree(int i) {}public static void methodFour(int i) {}

}a. Which method overrides a method in the superclass?b. Which method hides a method in the superclass?c. What do the other methods do?

Page 77: Java Final Material

77 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

InterfaceThere are a number of situations in software engineering when it is important for disparate groups ofprogrammers to agree to a "contract" that spells out how their software interacts. Each group should be able towrite their code without any knowledge of how the other group's code is written. Generally speaking,interfaces are such contracts.For example, imagine a futuristic society where computer-controlled robotic cars transport passengers throughcity streets without a human operator. Automobile manufacturers write software (Java, of course) thatoperates the automobile—stop, start, accelerate, turn left, and so forth. Another industrial group, electronicguidance instrument manufacturers, make computer systems that receive GPS (Global Positioning System)position data and wireless transmission of traffic conditions and use that information to drive the car.The auto manufacturers must publish an industry-standard interface that spells out in detail what methods canbe invoked to make the car move (any car, from any manufacturer). The guidance manufacturers can thenwrite software that invokes the methods described in the interface to command the car. Neither industrialgroup needs to know how the other group's software is implemented. In fact, each group considers itssoftware highly proprietary and reserves the right to modify it at any time, as long as it continues to adhere tothe published interface.

Interfaces in Java

Java does not support multiple inheritance. That is classes in java cannot have more than one superclass . forinstance, a definition like

class A extends B extends C{………………………………..}

It is not permitted in java. Since C++ like implementation of multiple inheritances proves difficult and addscomplexity to the language, java provides an alternate approach known as interfaces to support the concept ofmultiple inheritances. Although a java class cannot be a subclass of more than one superclass, it canimplement more than one interface, thereby enabling us to create classes that build upon other classes withoutthe problems created by multiple inheritances.Defining interfacesAn interface is basically a kind of class. Like classes, interfaces contain methods and variables but with amajor difference. The difference is that interfaces define only abstract methods and final fields. This meansthat interfaces do not specify any code to implement these methods and data fields. Contains only constants.Therefore it is the responsibility of the class that’s implements an interface to define the code forimplementation of these methods.The syntax of interface defination:

interface InterfaceName{variables declaration;methods declaration;}

Here, interface is the keyword and InterfaceName is any valid variable. Variables are declared as follows:static final type VariableName = value;

Note that all variables are declared as constants.

Page 78: Java Final Material

78 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

In the Java programming language, an interface is a reference type, similar to a class, that can contain onlyconstants, method declaration, and nested types. There are no method bodies. Interfaces cannot beinstantiated—they can only be implemented by classes or extended by other interfaces.Here is the example of an interface definition that contains two variables and one method:

interface Item{

static final int code = 1001;static final String name = “Fan”;void display();

}

Note that the method declarations have no braces and are terminated with a semicolon.To use an interface, you write a class that implements the interface. When an instantiable class implements aninterface, it provides a method body for each of the methods declared in the interfaceExtending InterfacesAn interface can extend other interfaces, just as a class can extend or subclass another class. However,whereas a class can extend only one other class, an interface can extend any number of interfaces. Theinterface declaration includes a comma-separated list of all the interfaces that it extends.

interface name2 extends name1,name3{

Body of name2}

For example, we can put all constant in one interface and the methods in the other. This will enables us to usethe constants in classes where the methods are not required.interface ItemConstants{

int code = 1001;string name = “Fan”;

}interface Item extends itemConstants{

void display();}The interface Item would inherit both the constants code and name into it. Note that the variables name andcode are declared like simple variables. It is allowed because all the variables in an interface are treated asconstants although the keyword final and static are not present.

The interface body contains method declarations for all the methods included in the interface. A methoddeclaration within an interface is followed by a semicolon, but no braces, because an interface does notprovide implementations for the methods declared within it. All methods declared in an interface areimplicitly public, so the public modifier can be omitted.An interface can contain constant declarations in addition to method declarations. All constant values definedin an interface are implicitly public, static, and final. Once again, these modifiers can be omitted.Implementing an InterfaceTo declare a class that implements an interface, you include an implements clause in the class declaration.Your class can implement more than one interface, so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class.By convention, the implements clause follows the extends clause, if there is one.class classname implements interfacename{

Page 79: Java Final Material

79 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Body of classname}Here the class classname “implements” the interface interfacename. A more general form of implementationmay look like this:class classname extends superclass implements interface1, interface2{

Body of classname}This shows class can extend another class while implementing interfaces. Implementation of interfaces asclass types is illustrated by following program. In this program, first we create an interface Area andimplements the same in two different classes, Rectangle and Circle. We create an instance of each classusing the new operator. Then we declare an object of type Area, the interface class. Now, we assign thereference to the Rectangle object rect to area. When we call the compute method of area, the Rectangleclass is invoked. We repeat the same thing with the Circle object.// InterfaceTest.javainterface Area // interface defined{

final static float pi = 3.14;float compute (float x, float y);

}class Rectangle implements Area{

public float compute(float x, float y){return(x*y);}

}class Circle implements Area{

public float compute(float x, float y){

return(pi*x*y);}

}class InterfaceTest{

public static void main(String args[]){

Rectangle rect = new Rectangle();Circle cir = new Circle();Area area;area = react;System.out.println(“area of Rectangle = “ + area.compute(10,20));area = cir;System.out.println(“area of Circle = “ + area.compute(10,0));

}}The output is as follows:

area of Rectangle = 200area of Circle = 314

Page 80: Java Final Material

80 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

program: Implementing multiple inheritanceclass Student{

int rollnumber;void gerNumber(int n){

rollNumber = n;}void putNumber(){

System.out.println(“Roll No : “ + rollNumber);}

}class Test extends Student{

float part1,part2;void getMarks(float m1,float m2){

part1 = m1;part2 = m2;

}void putMarks(){

System.out.println(“ Marks obtained ”);System.out.println(““ part1 = ” + part1”);System.out.println(“ part2 = ” + part2);

}}interface Sports{

float sportWt = 6.0F;void putWt();

}class Results extends Test implements Sports{

float total;public void putWt(){

System.out.println(“Sports Wt = “ + sportWt);}void display(){

total = part1 + part2 + sportWt;putNumber();putMarks();putWt();System.out.println(“Total score = “ + total);

}}

Page 81: Java Final Material

81 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

class Hybrid{

public static void main(String args[]){

Results student1 = new Results();student1.getNumber(1234);student1.getMarks(27.5F,33.0F);student1.display();

}}output:

Roll No = 1234Marks obtainedpart1 = 27.5part2 = 33Sports Wt = 6Total score = 66.5

Lesson 9: Numbers and StringsNumbersThis section begins with a discussion of the Number class (in the java.lang package) and its subclasses.In particular, this section talks about the situations where you would use instantiations of these classes ratherthan the primitive data types. Additionally, this section talks about other classes you might need to work withnumbers, such as formatting or using mathematical functions to complement the operators built into thelanguage.StringsStrings, which are widely used in Java programming, are a sequence of characters. In the Java programminglanguage, strings are objects. This section describes using the String class to create and manipulate strings.It also compares the String and StringBuilder classes.NumbersThis section begins with a discussion of the Number class in the java.lang package, its subclasses, andthe situations where you would use instantiations of these classes rather than the primitive number types.Finally, the Math class in java.lang is discussed. It contains mathematical functions to complement theoperators built into the language. This class has methods for the trigonometric functions, exponentialfunctions, and so forth.The Numbers ClassesWhen working with numbers, most of the time you use the primitive types in your code. For example:int i = 500;float gpa = 3.65f;byte mask = 0xff;There are, however, reasons to use objects in place of primitives, and the Java platform provides wrapperclasses for each of the primitive data types. These classes "wrap" the primitive in an object. Often, thewrapping is done by the compiler—if you use a primitive where an object is expected, the compiler boxes theprimitive in its wrapper class for you. Similarly, if you use a number object when a primitive is expected, thecompiler unboxes the object for you.Here is an example of boxing and unboxing:Integer x, y;x = 12;y = 15;System.out.println(x+y);

Page 82: Java Final Material

82 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

When x and y are assigned integer values, the compiler boxes the integers because x and y are integerobjects. In the println() statement, x and y are unboxed so that they can be added as integers.All of the numeric wrapper classes are subclasses of the abstract class Number:

There are three reasons that you might use a Number object rather than a primitive:1. As an argument of a method that expects an object (often used when manipulating collections of

numbers).2. To use constants defined by the class, such as MIN_VALUE and MAX_VALUE, that provide the upper

and lower bounds of the data type.3. To use class methods for converting values to and from other primitive types, for converting to and

from strings, and for converting between number systems (decimal, octal, hexadecimal, binary).As pointed out earlier, vectors cannot handle primitive data types like int, float, long, char, and double.Primitive data types may be converted into object types by using the wrapper classes contained in thejava.lang package.

Wrapper classes for converting simple types

Simple type wrapper class

boolean Boolean

char Character

double Double

float Float

int Integer

long Long

The wrapper classes have a number of unique methods for handling primitive data types and objects.

Converting primitive numbers to object numbers using constructor methods

Constructor calling conversion action

Integer IntVal=new Integer(i); primitive integer to Integer object

Float FloatVal=new Float(f); primitive float to Float object

Double DoubleVal=new Double(d); primitive double to Double object

Long LongVal=new Long(l); primitive long to Long object

Converting object numbers to primitive numbers using typeValue() method

Method calling conversion action

int j = IntVal.intValue(); object to primitive integer

float f=FloatVal.floatValue(); object to primitive float

Page 83: Java Final Material

83 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

long l=LongVal.longValue(); object to primitive long

double d= DoubleVal.doubleValue(); object to primitive double

Converting numbers to strings using to string() method

Method calling conversion action

str= Integer.toString(i); primitive integer to string

str=Float.toString(f); primitive float to string

str=Double.toString(d); primitive double to string

str=Long.toString(l); primitive long to string

Converting string objects to numeric objects using the static method valueof()

method calling conversion action

DoubleVal=Double.valueOf(str); converts string to Double object

FloatVal=Float.valueOf(str); converts string to Float object

IntVal=Integer.valueOf(str); Converts string to Integer object

LongVal=Long.valueOf(str); converts string to Long object

Converting numeric strings to primitive numbers using parsing methods

Method calling conversion action

int i = Integer.parseInt(str); converts string to primitive integer

long i = Long.parseLong(str); converts string to primitive long

Mathematical functions and constantsThe Math class includes two constants:

Math.E, which is the base of natural logarithms, and Math.PI, which is the ratio of the circumference of a circle to its diameter.

The Math class also includes more than 40 static methods. The following table lists a number of the basicmethods.

Math Methods

Method Description

abs(x) Returns the absolute value of the argument.

ceil(x) Returns the smallest integer that is greater than or equal to the argument. Returnedas a double.

floor(x) Returns the largest integer that is less than or equal to the argument. Returned as adouble.

rint(d) Returns the integer that is closest in value to the argument. Returned as a double.

round(d) Returns the closest long or int, as indicated by the method's return type, to theargument.

min(arg1, arg2) Returns the smaller of the two arguments.

Page 84: Java Final Material

84 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

max(arg1, arg2) Returns the larger of the two arguments.

exp(d) Returns the base of the natural logarithms, e, to the power of the argument.

log(d) Returns the natural logarithm of the argument.

pow(base,exponent) Returns the value of the first argument raised to the power of the second argument.

sqrt(d) Returns the square root of the argument.

sin(d) Returns the sine of the specified double value.

cos(d) Returns the cosine of the specified double value.

tan(d) Returns the tangent of the specified double value.

asin(d) Returns the arcsine of the specified double value.

acos(d) Returns the arccosine of the specified double value.

atan(d) Returns the arctangent of the specified double value.

atan2(y, x)Converts rectangular coordinates (x, y) to polar coordinate (r, theta) andreturns theta.

Random NumbersThe random() method returns a randomly selected number between 0.0 and 1.0. The range includes 0.0 butnot 1.0. To get a number in a different range, you can perform arithmetic on the value returned by the randommethod. For example, to generate an integer between 0 and 9, you would write:int number = (int)(Math.random() * 10);By multiplying the value by 10, the range of possible values becomes 0.0 <= number < 10.0.Using Math.random works well when you need to generate a single random number. If you need togenerate a series of random numbers, you should create an instance of java.util.Random and invokemethods on that object to generate numbers.

ArrayArray is the most important thing in any programming language. By definition, array is the static memory

allocation. It allocates the memory for the same data type in sequence. It contains multiple values of sametypes. It also stores the values in memory at the fixed size. Multiple types of arrays are used in anyprogramming language such as: one - dimensional, two - dimensional or can say multi - dimensional.Declaration of an array

int num[];or

int num = new int[2];Sometimes user declares an array and its size simultaneously. You may or may not be define the size in thedeclaration time. Such as:

int num[] = {50,20,45,82,25,63};In this program we will see how to declare and implementation. This program illustrates that the arrayworking way. This program takes the numbers present in the num[] array in unordered list and prints numbersin ascending order. In this program the sort() function of the java.util.*; package is using to sort all the

Page 85: Java Final Material

85 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

numbers present in the num[] array. The Arrays.sort() automatically sorts the list of number in ascendingorder by default. This function held the argument which is the array name num.Here is the code of the program to arrange the numbers in ascending order.import java.util.*;class array{

public static void main(String[] args){

int num[] = {50,20,45,82,25,63};int i = num.length;int i,j,t;System.out.print("Given number : ");for (i = 0;i < l;i++ ){

System.out.print(" " + num[i]);}System.out.println("\n");System.out.print("Accending order number : ");Arrays.sort(num);for(i = 0;i < l;i++){

System.out.print(" " + num[i]);}

}}Output of the program:C:\ jdk\bin >javac array.java

C:\ jdk\bin >java arrayGiven number : 50 20 45 82 25 63

Ascending order number : 20 25 45 50 63 82

Java Copy Array ExampleIn this tutorial, you will learn how to copy data from one array to another. Here, providing you an examplewith code and its explanation to given below.This is a program that follows one dimensional array. In this program, firstly we have to define a class"CopyArray". Now, we take two integer type array like: array1[] and array2[]. The array1[] contains someinteger type values (2,3,4,5,8,9) and another is blank. After initializing this, now we get number of rows andcolumns by using the array1.length. We use the 'for' loop statement for displaying and copying (array1[j] =array2[j] ) the array.Here is the code of this program:class CopyArray{

public static void main(String[] args){

int array1[]= {2,3,4,5,8,9};int array2[] = new int[6];System.out.println("array:");System.out.print("[");

Page 86: Java Final Material

86 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

for (int i=0; i<array1.length; i++){

System.out.print(" "+array1[i]);}System.out.print("]");System.out.println("\narray1:");System.out.print("[");for(int j=0; j<array1.length; j++){

array2[j] = array1[j];System.out.print(" "+ array2[j]);

}System.out.print("]");

}}charAt() MethodIn this section, you will get the detailed explanation about the charAt() method of String class. We are goingfor using charAt() method. You can see how to use the method by syntax. There is a section provided forunderstanding the usage of the method practically.Description of program:Here, you will understand about the procedure of the charAt() method through the following java program.This program reads a string as input through the keyboard. And first this shows the length of the string thenfind the character at the 4th (mentioned as a parameter of the method) position of the string that is retrievedby using charAt() method. This method takes a parameter that is the position of the string. The charAt()method returns a character value for the character at the given position of the string.Here is the code of this program:import java.io.*;class CharAt{

public static void main(String[] args){

try{BufferedReader object=new BufferedReader(new InputStreamReader(System.in));System.out.println("Enter the String");String s=object.readLine();int len=s.length();System.out.println(len);char char1=s.charAt(4);System.out.println(char1);}catch(Exception e){}

}}Output this program:C:\ jdk\bin >java CharAtEnter the Stringroseindia9i

Page 87: Java Final Material

87 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

length() MethodIn this section, you will learn how to use length() method of the String class. We are going to using length()method. These method are illustration as follow here:Description of program:Here, we will know that how many character of length in String. First of all, we have to define class named"StringLength". Inside of class we have to define method of class in main class. After that we create onemethod which returns the integer type values. So we are using to length() method of the String class for thepurpose.length() method : This method return the length of this string as an integer value.Here is the the code of this program:import java.io.*;class StringLength{

public static void main(String[] args).{

try{

BufferedReader object=new BufferedReader (new InputStreamReader(System.in));System.out.println("Eneter string value:");String s=object.readLine();int len=s.length();System.out.println(len);

}catch(Exception e){}

}}Output this program:C:\ jdk\bin >javac StringLength.java

C:\ jdk\bin >java StringLengthEneter string value:amar4

toUpperCase() MethodIn this section, you will learn how to use toUpperCase() method of the String class. We are going for usingtoUpperCase() method. This method is explained as follows:Description of program:Here, you will see the procedure of converting letters of the string in uppercase letter. So, we are usingtoUpperCase() method of the String class for the purpose.The following program convert the string "india" into "INDIA" by using toUpperCase() method.toUpperCase(): This method returns a string value.Here is the code of this program:class ConvertInUpperCase{

public static void main(String args[]){

String roseindia = "india";

Page 88: Java Final Material

88 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

System.out.println("String is : " + roseindia);String upper = roseindia.toUpperCase();System.out.println("String in uppercase letter: " + upper);

}}Output of program:

C:\ jdk\bin >javac ConvertInUpperCase.java

C:\ jdk\bin >java ConvertInUpperCaseString is : indiaString in uppercase letter: INDIA

String ArrayIn this section, you will learn how to use string array in Java. Here, you will see how to declare a string arrayand the syntax for using in the program. This section provides you a simple java program which illustratesabout the string array in very efficient manner.Program Description:Following code of the program declares a string array and store some strings like "chandan", "tapan", "Amar","santosh", and "deepak" to it. And in the main method these string are displayed one by one by retrievingfrom the specified string array named roseindia. In this program all the string values are stored in theroseindia string array at the declaration time.Here is the code of this program:class StringCharacter{

static String[] roseindia={"chanan","tapan","Amar","santosh","deepak"};public static void main(String args[]){for(int i=0;i<5;i++)

. {System.out.println(roseindia[i]);

}}

}Output of program:C:\ jdk\bin >javac StringCharacter.javaC:\ jdk\bin >java StringCharacterchanantapanAmarsantoshdeepak

Average of ArrayIn this section, we will learn how to get an average of array. For this, first of all we have to define a classname "ArrayAverage" that has double type array to contain some values. Now we take a double type datathat calculates the average of array (result/nums.length). And finally it will display the result on thecommand prompt with message by using the System.out.println().

Here is the code of this programclass ArrayAverage

Page 89: Java Final Material

89 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

{public static void main(String[] args){

double nums[]={1.0,2.3,3.4,4.5,40.5};double result=0.0;int i=0;for(i=0; i < nums.length; i++).{

result=result + nums[i];}System.out.println("Average is =" + result/nums.length);

}}

MatrixA matrix is a collection of data in rows and columns format.

Description of program:In this program we are going to implement a matrix. To make a program over the two dimensional array,first of all we have to declare class named as MatrixExample that has one static method outputArray()which takes integer type array and represents it. For displaying the matrix we need to its rows and columnby using the array.length method. Now, we use the for loop to print all the values stored in the array. Atlast use the main() method inside which we are going to declare the values of the multidimensional arraywhich we are going to use. Call the outputArray() method inside the main method. The output will bedisplayed to the user by println() method.Here is the code of this Example:

class MatrixExample{

public static void main(String[] args){int array[][]= {{1,3,5},{2,4,6}};System.out.println("Row size= " + array.length);System.out.println("Column size = " + array[1].length);outputArray(array);

}

public static void outputArray(int[][] array){

int rowSize = array.length;int columnSize = array[0].length;for(int i = 0; i <= 1; i++){

System.out.print("[");for(int j = 0; j <= 2; j++){

System.out.print(" " + array[i][j]);}

System.out.println(" ]");}System.out.println();

}

Page 90: Java Final Material

90 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

}

Sum of two MatrixIn this section, we are going to calculate the sum of two matrix and containing its rows and columns. Seebelow for better understanding to this.In this program we are going to calculate the sum of two matrix. To make this program, we need to declaretwo dimensional array of type integer. Firstly it calculates the length of the both the arrays. Now we needto make a matrix out of it. To make the matrix we will use the for loop. By making use of the for loop therows and column will get divide. This process will be performed again for creating the second matrix.After getting both the matrix with us, we need to sum both the matrix. The both matrix will be added byusing the for loop with array[i][j]+array1[i][j]. The output will be displayed by using the println() method.Here is the code of this program:

class MatrixSum{

public static void main(String[] args){int array[][]= {{4,5,6},{6,8,9}};int array1[][]= {{5,4,6},{5,6,7}};System.out.println("Number of Row= " + array.length);System.out.println("Number of Column= " + array[1].length);int l= array.length;System.out.println("Matrix 1 : ");for(int i = 0; i < l; i++)

. {for(int j = 0; j <= l; j++){

System.out.print(" "+ array[i][j]);}

System.out.println();}

int m= array1.length;System.out.println("Matrix 2 : ");for(int i = 0; i < m; i++)

. {for(int j = 0; j <= m; j++){

System.out.print(" "+array1[i][j]);}

System.out.println();}

System.out.println("Addition of both matrix : ");for(int i = 0; i < m; i++){for(int j = 0; j <= m; j++){

System.out.print(" "+(array[i][j]+array1[i][j]));}

System.out.println();}

}

Page 91: Java Final Material

91 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

}Output of program:

C:\ jdk\bin >javac MatrixSum.java

C:\ jdk\bin >java MatrixSumNumber of Row= 2Number of Column= 3Matrix 1 :4 5 66 8 9Matrix 2 :5 4 65 6 7Addition of both matrix :9 9 1211 14 16

Multiplication of two MatrixThis is a simple java program that teaches you for multiplying two matrix to each other. Here providingyou Java source code with understanding the Java developing application program. We are going to make asimple program that will multiply two matrix. Two dimensional array represents the matrix.Now, make this program, you have to declare two multidimensional array of type integer. Program usestwo for loops to get number of rows and columns by using the array1.length. After getting both matrixthen multiply to it. Both matrix will be multiplied to each other by using 'for' loop. So the output will bedisplayed on the screen command prompt by using the println() method.

Here is the code of this program:class MatrixMultiply{

public static void main(String[] args) {int array[][] = {{5,6,7},{4,8,9}};int array1[][] = {{6,4},{5,7},{1,1}};int array2[][] = new int[3][3];int x= array.length;System.out.println("Matrix 1 : ");for(int i = 0; i < x; i++) {for(int j = 0; j <= x; j++) {

System.out.print(" "+ array[i][j]);}

System.out.println();}int y= array1.length;System.out.println("Matrix 2 : ");for(int i = 0; i < y; i++) {for(int j = 0; j < y-1; j++) {

System.out.print(" "+array1[i][j]);}

System.out.println();}

Page 92: Java Final Material

92 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

for(int i = 0; i < x; i++) {for(int j = 0; j < y-1; j++) {

for(int k = 0; k < y; k++){

array2[i][j] += array[i][k]*array1[k][j];}

}}

System.out.println("Multiply of both matrix : ");for(int i = 0; i < x; i++) {

for(int j = 0; j < y-1; j++) {System.out.print(" "+array2[i][j]);

}System.out.println();}

}}Square Elements of Two Dimensional Array

This is a simple java program for implementing the two dimensional array program and its square. Thissession provide you the best explanation with mathematical operation.Description of progarm:We are going to display the square of two matrix. Firstly, we have to define a class "SquareMatrix". Thenwe take an integer type array that contains integer type values. After this, we use two 'for' loop thatdenotes rows and columns of a matrix. After getting both the matrix with us we need to square both matrix.When we go to square this array then we use "square[i][j] =square[i][j] * square[i][j]". So, the outputwill be displayed on the screen command prompt by using the println() method.Here is the code of this program

public class SquareMatrix{

public static void main(String[] args){int square[][]= {{1,3,5},{2,4,6}};System.out.println("Your Original Matrix: ");for(int i = 0; i < 2; i++){for(int j = 0; j < 3; j++){

System.out.print(square[i][j] + " ");}System.out.println();

}for(int i = 0; i <= 1; i++){for(int j = 0; j <= 2; j++){

square[i][j] = square[i][j] * square[i][j];}

}System.out.println("Matrix after changes: ");for(int i = 0; i < 2; i++)

Page 93: Java Final Material

93 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

{for(int j = 0; j < 3; j++){

System.out.print(square[i][j] + " ");}System.out.println();

}}

}

CharactersMost of the time, if you are using a single character value, you will use the primitive char type. Forexample:char ch = 'a';char[] charArray ={ 'a', 'b', 'c', 'd', 'e' }; // an array of charsThere are times, however, when you need to use a char as an object—for example, as a method argumentwhere an object is expected. The Java programming language provides a wrapper class that "wraps" thechar in a Character object for this purpose. An object of type Character contains a single field, whosetype is char. This Character class also offers a number of useful class (i.e., static) methods formanipulating characters.You can create a Character object with the Character constructor:Character ch = new Character('a');The Java compiler will also create a Character object for you under some circumstances. For example, ifyou pass a primitive char into a method that expects an object, the compiler automatically converts thechar to a Character for you. This feature is called autoboxing—or unboxing, if the conversion goes theother way.Here is an example of boxing,Character ch = 'a'; // the primitive char 'a' is boxed into the Characterobject chand here is an example of both boxing and unboxing,Character test(Character c) {...} // method parameter and return type =Character object

char c = test('x'); // primitive 'x' is boxed for method test, return isunboxed to char 'c'

The following table lists some of the most useful methods in the Character class, but is not exhaustive. Fora complete listing of all methods in this class (there are more than 50), refer to thejava.lang.Character API specification.

Useful Methods in the Character Class

Method Description

isLetter(char ch)isDigit(char ch)

Determines whether the specified char value is a letter or a digit,respectively.

isWhitespace(charch) Determines whether the specified char value is white space.

isUpperCase(char ch) Determines whether the specified char value is uppercase or lowercase,

Page 94: Java Final Material

94 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

isLowerCase(char ch) respectively.

toUpperCase(char ch)toLowerCase(char ch) Returns the uppercase or lowercase form of the specified char value.

toString(char ch) Returns a String object representing the specified character value—that is,a one-character string.

Escape SequencesA character preceded by a backslash (\) is an escape sequence and has special meaning to the compiler. Thefollowing table shows the Java escape sequences:

Escape Sequences

EscapeSequence Description

\t Insert a tab in the text at this point.

\b Insert a backspace in the text at this point.

\n Insert a newline in the text at this point.

\r Insert a carriage return in the text at this point.

\f Insert a formfeed in the text at this point.

\' Insert a single quote character in the text at this point.

\" Insert a double quote character in the text at this point.

\\ Insert a backslash character in the text at this point.

When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. Forexample, if you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes.To print the sentenceShe said "Hello!" to me.you would writeSystem.out.println("She said \"Hello!\" to me.");

StringsStrings, which are widely used in Java programming, are a sequence of characters. In the Java programminglanguage, strings are objects.The Java platform provides the String class to create and manipulate strings.

Creating StringsString manipulation is the most common part of many Java program. Strings represent a sequence ofcharacters. The easiest way to represent a sequence of characters to Java is by using a character array.Example:

char charArray[] = new char[4];charArray[0] = ‘J’;charArray[1] = ‘a’;

Page 95: Java Final Material

95 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

charArray[2] = ‘v’;charArray[3] = ‘a’;

Although character arrays have the advantage of being able to query their length, they themselves are notgood enough to support the range of operations we may like to perform on strings. For example, copying onecharacter array into another might require a lot of book keeping effort. Fortunately, Java is equipped to handlethese situations more efficiently.

In Java, strings are class objects and implemented using two classes, namely, string and stringBuffer. Ajava string is an instantiated object of the String class.Java string as compared to ‘C strings, are more reliableand predictable. This is basically due to C’s lack of bounds – checking. A Java string is not a character arrayand is not NULL terminated. strings may be declared and created as follows:

Example:String firstName;

firstName = new String (“Anil”) ;These two statement may be combined as follows:

String firstName = new String (“Anil”) ;Like arrays, it is possible to get the length of string using the length method of the String class.

int m = firstName.length ( ) ;Note the use of parentheses here. Java strings can be concatenated using the + operator. Examples:

String fullName = name1 + name2;String city1 = “New” + “Delhi” ;

where name1 and name2 are Java strings containing string constants. Another example is:System.out.print1n(firstName +”Kumar ) ;

String ArraysWe can also create and use arrays that contain strings. The statement

String itemArray [ ] = new String [3] ;will create an itemArray of size 3 to hold three string constants. We can assign the strings to the itemArrayelement by element using three different statements or more efficiently using a for loop.String MethodsThe string class defines a number of methods that allow us to accomplish a variety of string manipulationtasks. Hear lists some of the most commonly used string methods, and their tasks.

s2=s1.toLowerCase; converts the string s1 to all lowercases2=s1.toUpperCase; converts the string s1 to all Uppercases2=s1.replace(‘x’,’y’); Replace all appearances of x with ys2=s1.trim(); remove white spaces at the beginning and end of the string

s1s1.equals(s2) returns ‘true’ if s1 is equal to s2s1.equalsIgnoreCase(s2) returns ‘true’ if s1=s2,ignoring the case of characterss1.length() gives the length of s1s1.CharAt(n) gives nth character of s1s1.compareTo(s2) returns negative if s1<s2,positive if s1>s2, and zero if s1 is

equal s2s1.concat(s2) concatenates s1 and s2s1.substring(n) gives substring starting from nth characters1.substring(n,m) gives substring starting from nth character up to mth (not

ncluding mth)

String stringName:StringName = new String (“string”);

Page 96: Java Final Material

96 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

String.ValueOf(p) creates a string object of the parameter p (simple type ofobject)

p.toString() creates a string representation of the object ps1.indexOf(‘x’) gives the position of the first occurrence of ‘x’ in the string s1s1.indexOf(‘x’,n) gives the position of ‘x’ that occurs after nth position in the

string s1String.VauldeOf(Variable) converts the parameter value to string representation

String LengthMethods used to obtain information about an object are known as accessor methods. One accessor methodthat you can use with strings is the length() method, which returns the number of characters contained inthe string object. After the following two lines of code have been executed, len equals 17:

String palindrome = "Dot saw I was Tod";int len = palindrome.length();

A palindrome is a word or sentence that is symmetric—it is spelled the same forward and backward, ignoringcase and punctuation. Here is a short and inefficient program to reverse a palindrome string. It invokes theString method charAt(i), which returns the ith character in the string, counting from 0.

public class StringDemo {public static void main(String[] args) {

String palindrome = "Dot saw I was Tod";int len = palindrome.length();char[] tempCharArray = new char[len];char[] charArray = new char[len];// put original string in an array of charsfor (int i = 0; i < len; i++)

{tempCharArray[i] = palindrome.charAt(i);

}// reverse array of charsfor (int j = 0; j < len; j++)

{charArray[j] = tempCharArray[len - 1 - j];

}String revPalindrome = new String(charArray);System.out.println(revPalindrome);

}}Running the program produces this output:doT saw I was toD

Concatenating StringsThe String class includes a method for concatenating two strings:string1.concat(string2);This returns a new string that is string1 with string2 added to it at the end.You can also use the concat() method with string literals, as in:"My name is ".concat("Rumplestiltskin");Strings are more commonly concatenated with the + operator, as in"Hello," + " world" + "!"which results in

Page 97: Java Final Material

97 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

"Hello, world!"The + operator is widely used in print statements. For example:String string1 = "saw I was ";System.out.println("Dot " + string1 + "Tod");which printsDot saw I was TodSuch a concatenation can be a mixture of any objects. For each object that is not a String, itstoString() method is called to convert it to a String.

Note: The Java programming language does not permit literal strings to span lines in source files, so you mustuse the + concatenation operator at the end of each line in a multi-line string. For example,String quote = "Now is the time for all good " +

"men to come to the aid of their country.";Breaking strings between lines using the + concatenation operator is, once again, very common in printstatements.

Converting Between Numbers and StringsConverting Strings to NumbersFrequently, a program ends up with numeric data in a string object—a value entered by the user, for example.The Number subclasses that wrap primitive numeric types ( Byte, Integer, Double, Float, Long, andShort) each provide a class method named valueOf that converts a string to an object of that type. Here isan example, ValueOfDemo , that gets two strings from the command line, converts them to numbers, andperforms arithmetic operations on the values:public class ValueOfDemo {

public static void main(String[] args) {//this program requires two arguments on the command line

if (args.length == 2) {//convert strings to numbers using wrapper class

float a = (Float.valueOf(args[0]) ).floatValue();float b = (Float.valueOf(args[1]) ).floatValue();

//do some arithmeticSystem.out.println("a + b = " + (a + b) );System.out.println("a - b = " + (a - b) );System.out.println("a * b = " + (a * b) );System.out.println("a / b = " + (a / b) );System.out.println("a % b = " + (a % b) );

} else {System.out.println("This program requires two command-line

arguments.");}

}}The following is the output from the program when you use 4.5 and 87.2 for the command-line arguments:a + b = 91.7a - b = -82.7a * b = 392.4a / b = 0.0516055a % b = 4.5Converting Numbers to Strings

Page 98: Java Final Material

98 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Sometimes you need to convert a number to a string because you need to operate on the value in its stringform. There are several easy ways to convert a number to a string:int i;String s1 = "" + i; //Concatenate "i" with an empty string;

//conversion is handled for you.or

String s2 = String.valueOf(i); //The valueOf class method.Each of the Number subclasses includes a class method, toString(), that will convert its primitive typeto a string. For example:int i;double d;String s3 = Integer.toString(i);String s4 = Double.toString(d);The ToStringDemo example uses the toString method to convert a number to a string. The programthen uses some string methods to compute the number of digits before and after the decimal point:public class ToStringDemo{public static void main(String[] args){double d = 858.48;String s = Double.toString(d);int dot = s.indexOf('.');System.out.println(dot + " digits before decimal point.");System.out.println( (s.length() - dot - 1)+" digits after decimal

point.");}}The output of this program is:3 digits before decimal point.2 digits after decimal point.Manipulating Characters in a StringThe String class has a number of methods for examining the contents of strings, finding characters orsubstrings within a string, changing case, and other tasks.

Other Methods for Manipulating StringsHere are several other String methods for manipulating strings:

Other Methods in the String Class for Manipulating Strings

Method Description

split(String regex)split(String regex, int limit)

Searches for a match as specified by the string argument(which contains a regular expression) and splits this stringinto an array of strings accordingly. The optional integerargument specifies the maximum size of the returned array.Regular expressions are covered in the lesson titled"Regular Expressions."

String trim() Returns a copy of this string with leading and trailing whitespace removed.

Page 99: Java Final Material

99 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

String toLowerCase()String toUpperCase()

Returns a copy of this string converted to lowercase oruppercase. If no conversions are necessary, these methodsreturn the original string.

An ExampleThe following class, Filename, illustrates the use of lastIndexOf() and substring() to isolatedifferent parts of a file name.

Note: The methods in the following Filename class don't do any error checking and assume that theirargument contains a full directory path and a filename with an extension. If these methods were productioncode, they would verify that their arguments were properly constructed.

class Filename{

String fullPath;char pathSeparator, extensionSeparator;

Filename(String str, char sep, char ext){

fullPath = str;pathSeparator = sep;extensionSeparator = ext;

}String extension(){

int dot = fullPath.lastIndexOf(extensionSeparator);return fullPath.substring(dot + 1);

}String filename() // gets filename without extension{

int dot = fullPath.lastIndexOf(extensionSeparator);int sep = fullPath.lastIndexOf(pathSeparator);return fullPath.substring(sep + 1, dot);

}String path(){

int sep = fullPath.lastIndexOf(pathSeparator);return fullPath.substring(0, sep);

}}class FilenameDemo{

public static void main(String[] args){

final String FPATH = "/home/mem/index.html";Filename myHomePage = new Filename(FPATH,'/', '.');System.out.println("Extension = " + myHomePage.extension());System.out.println("Filename = " + myHomePage.filename());System.out.println("Path = " + myHomePage.path());

}}

Page 100: Java Final Material

100 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

And here's the output from the program:Extension = htmlFilename = indexPath = /home/memAs shown in the following figure, our extension method uses lastIndexOf to locate the lastoccurrence of the period (.) in the file name. Then substring uses the return value of lastIndexOf toextract the file name extension — that is, the substring from the period to the end of the string. This codeassumes that the file name has a period in it; if the file name does not have a period, lastIndexOf returns -1, and the substring method throws a StringIndexOutOfBoundsException.

Also, notice that the extension method uses dot + 1 as the argument to substring. If the periodcharacter (.) is the last character of the string, dot + 1 is equal to the length of the string, which is onelarger than the largest index into the string (because indices start at 0). This is a legal argument tosubstring because that method accepts an index equal to, but not greater than, the length of the string andinterprets it to mean "the end of the string."StringBuffer ClassStringBuffer is a peer class of String. While string creates strings of fixed_length, stringBuffer Creates stringsof flexible length that can be modified in terms of both length and content. We can insert characters andsubstrings in the middle of a string, or append another string to the end.

Method Tasks1.setChartAt(n,’x’) modifies the nth character to xs1.append(s2) appends the string s2 to s1 at the ends1.insert(n,s2) inserts the string s2 at the position n of the string s1s1.serLength(n) sets the length of the string s1 to n. if n<s1.length() s1 is truncated.if

n>s1.length() zeros are added to s1Program illustrates the use of these methods:class StringManipulation{public static void main(String args[]){

StringBuffer str = new StringBuffer(“Object language”);System.out.println(“Original String :” + str);// obtaining sring lengthSystem.out.println(“Length of string :” + str.length());//Accessing characters in a stringfor(int I=0; i<str.length(); i++){

int p = I + 1;System.out.println(“Character at position : “ + p + “ is “ + str.charAt(i));

Page 101: Java Final Material

101 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

}//inserting a string in the middleString aString new String(str.toString());int pos = aString.indexOf( “ language”);str.insert(pos,” Oriented “);System.out.println(“Modified string : “ + str);// modified charactersstr.setCharAr(6, ‘-‘);System.out.println(“String now : “ + str);//Appending a string at the endstr.append(“ improves security.”);System.out.println(“Appended string : “ + str);

}}Output:

Original string : Object languageLength of string : 15Character at position : 1 is OCharacter at position : 2 is bCharacter at position : 3 is jCharacter at position : 4 is eCharacter at position : 5 is cCharacter at position : 6 is tCharacter at position : 7 isCharacter at position : 8 is lCharacter at position : 9 is aCharacter at position : 10 is nCharacter at position : 11 is gCharacter at position : 12 is uCharacter at position : 13 is aCharacter at position : 14 is gCharacter at position : 15 is eModified string : Object Oriented languageString now : Object-Oriented languageAppended string : Object-Oriented language improves security.

Vectorswe have seen that J2SE 5.0 version supports the concept of variable arguments to methods. This feature canalso be achieved in java through the use of the vector class contained in the java.util package. This class canbe used to create a generic dynamic array known as vector that can hold objects of any type and anynumber. The objects do not have to be homogeneous. Array can be easily implemented as vectors. Vectorsare created like arrays as follows:

Page 102: Java Final Material

102 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Vector intVect=new Vector(); //declaring without sizeVector list=new Vector(3); //declaring with size

Note that a vector can be declared without specifying any size explicitly. A vector without size canaccommodate an unknown number of items. Even, when a size is specified , this can be overlooked and adifferent number of items may be put into the vector. Remember, in contrast, an array must always have itssize specified.Vectors possess a number of advantages over arrays.

1. It is convenient to use vectors to store objects.2. A vector can be used to store a list of objects that may vary in size.3. We can add and delete objects from the list as and when required.

A major constraint in using vectors is that we cannot directly store simple data type in a vector; we can onlystore objects. Therefore, we need to convert simple types to objects. This can be done using the wrapperclasses discussed in the next; section. The vector class supports a number of methods that can be used tomanipulate the vectors created.

Method call task performedlist.addElement(item) adds the item specified to the list at the endlist.elementAt(10) gives the name of the 10th objectlist.size() gives the number of objects presentlist.removeElement(item) removes the specified item from the listlist.removeElementAt(n) removes the item stored in the nth position of the listlist.removeAllElements() removes all the elements in the listlist.copyInto(array) copies all items from list to arraylist.insertElementAt(item,n) inserts the item at nth positionprogram illustrates the use of array, string and vector.import java.util.*;class LanguageVector{public static void main(String args[]){

Vector list = new Vector();int length = args.length;for(int i = 0; i < length; i++){

list.addElement(args[i]);}list.insertElementAt(“COBOL”,2);int size = list.size();String listArray[] = new String[size];list.copyInto(listArrary);System.out.println(“List of languages :”);for(int i = 0; i <size; i++){

System.out.println(listAray[i]);

Page 103: Java Final Material

103 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

}}}command line input and output are:C:\jdk\bin> java LanguageVector Ada BASIC C++ FORTRAN JavaList of languagesAdaBASICC++FORTRANJava

Page 104: Java Final Material

104 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Lesson 10: Packages

Packages are Java’s way of grouping a variety of classes and interfaces together. The grouping usually doneaccording to functionality. In fact, packages act as “containers” for classes. Package is a concept similar to“class libraries” in other languages.By organizing our classes into packages we achieve the following benefits:1. The classes contained in the packages of other programs can be easily reused.2. In packages, classes can be unique compared with classes in other packages. That is, two classes in twodifferent packages can have the same name. They may be referred by their fully qualified name, comprisingthe package name and the class name.3. Packages provide a way to “hide” classes thus preventing other programs or packages from accessingclasses that are meant for internal use only.4. Packages also provide a way for separating “design” from “coding”. First we can design classes and decidetheir relationships, and then we can implement the Java code needed for the methods. It is possible to changethe implementation of any method without affecting the rest of the design.Package categories in Java

Java supports two types of packages as shown below in the hierarchy structure:

Build-In Packages( Java API Packages):Java packages can be categorized in the hierarchy structure shown as:

Packages in the Java language begin with "java" as we can found in both hierarchy structure shownabove. Note that, the package "java" also has subpackages in which the package "awt" is further has asubpackage called "event" that is imported to access classes and interfaces to handle the events fired onthe awt-component in a program. Thus the the expression to import the package is shown as"

import awt.event.*;

Page 105: Java Final Material

105 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Lets understand these java packages shown in the table, from which you can access interfaces and classes.

Package Name Description

java.lang

It contains essential classes that represent primitive data types (such as int & char) aswell as more complex classes, including numerics, strings, objects, compiler, runtime,security, and threads. This is the only package that is automatically imported into everyJava program.

java.io This package provides classes to manage input and output streams to read datafrom and write data to files, strings, and other sources.

java.utilIt contains miscellaneous utility classes, including generic data structures, bit sets,time, date, string manipulation, random number generation, system properties,notification, and enumeration of data structures.

java.awtIt provides an integrated set of classes to manage user interface components suchas windows, dialog boxes, buttons, checkboxes, lists, menus, scrollbars, and textfields.

java.netIt provides classes for network support, including URLs, TCP sockets, UDP sockets, IPaddresses, and a binary-to-text converter.

java.appletIt enables the programmer to create applets through the Applet class. It alsoprovides several interfaces that connect an applet to its document and to resources forplaying audio.

Using system packagesThere are two ways of accessing the classes stored In a package. The first approach is to use the fullyqualified class name of the class that we want to use. This is done by; using the package name containing theclass and then appending the class name to it using the dot operator. For example, if we want to refer to theclass color In the awt package, then we may do so as follows:

Java.awt.colorNotice that awt is a package within the package java and the hierarchy is represented by separating the levelswith dots. This approach is perhaps the best and easiest one if we need to access the class only once or whenwe need not have to access any other classes of the package.But, in many situations, we might want to use a class in a number of places in the program or we may; like touse many of the class contained in a package. We may achieve this easily as follows:

import packagename.classname;Orimport packagename.*;

these are known as Import statements and must appear at the top of the file, before any class declarations,import is a keyword.The first statement allows the specified class in the specified package to be imported. For example, the

statementImport java.awt.color;

Imports the class colour and therefore the class name can now be directly used in the program. There is noneed to use the package name to qualify the class.The second statement imports every class contained in the specified package. For example, the statement

Page 106: Java Final Material

106 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

import java.awt.*;will bring all classes of java.awt package.

Create Your Own PackageThe package to which the source file belongs is specified with the keyword package at the top left of thesource file, before the code that defines the real classes in the package.Suppose we have a source file called "HelloWorld.java" and we want to put this file in a package"mypackage" then the following code is written as shown in the given example:

package mypackage;class HelloWorld{

public static void main (String args[]){

System.out.println("Hello World!");}

}

Before running this program make sure to do the following things:

1. Create a directory "mypackage" .2. Save the source file as "HelloWorld.java" in the created directory.3. Set the class path as set CLASSPATH = .;C:\;4. Go to the "mypackage" directory and compile the program as

C:\mypackage>javacHelloWorld.java

5. Run the program.

If you try to run this program, you will get the following exceptions (or error):

C:\mypackage>java HelloWorldException in thread "main" java.lang.NoClassDefFoundError: HelloWorld (wrong name:mypackage/HelloWorld)at java.lang.ClassLoader.defineClass1(Native Method)at java.lang.ClassLoader.defineClass(Unknown Source)at java.security.SecureClassLoader.defineClass(Unknown Source)at java.net.URLClassLoader.defineClass(Unknown Source)at java.net.URLClassLoader.access$000(Unknown Source)

This is, because the class "HelloWorld" belongs to the package "mypackage". So If we want to run it, wehave to tell the JVM about its fully-qualified class name as (mypackage.HelloWorld) instead of its plainclass name (HelloWorld). Fully-qualified class name is the name of the java class that includes itspackage name.Now run the program as shown:

C:\mypackage>javamypackage.HelloWorldHello World!

Page 107: Java Final Material

107 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

The ways to Compile the Package:

Compile in the same directory: If you have a hierarchy of packages to compilation then you can compilethe package without going to the subdirectories and specifying the complete directory path with the class .Suppose, you have a hierarchy of packages as "india.mycompany.mainpackage.mypackage" includingthe class "HelloWorld" then type the following command shown as:

C:\javacC:\india\mycompany\mainpackage\mypackage\HelloWord.java

This command will reach to the last subdirectory and compile the class "HelloWorld".

Compile into the Different Directory: On the other hand, if you want to compile the same packageavailable in the hierarchy manner to another directory (location) then syntax is shown as:

C:\javac -d <target_directory><complete_directorypath>

Suppose, you want to save the compiled package to the location "D:\myfolder" then type the followingcommand shown as:

C:\javac -d D:\myfolder C:\india\mycompany\mainpackage\mypackage\HelloWord.java

This command puts the folder "india" along with its subfolders and the class file "HelloWorld.class" tothe new location as D:\myfolder.

How to import a packageThere are two ways so that you can use the public classes stored in package.

Declaring the fully-qualified class name. For example,mypackage.HelloWorld helloworld = new mypackage.HelloWorld();

Using an "import" keyword: For example,import world.*; // we can call any public classes inside the mypackage package

Lets see an example importing the created package into the another program file.package importpackage;

public class HelloWorld{

public void show(){

System.out.println("This is the function of the class HelloWorld!!");}

}

In this program the package "importpackage" is created under the "c:\nisha" directory that will beimported into another program file to call the function of the class "HelloWorld".Now make a program file named "CallPackage" under the "c:\nisha" directory importing the package"importpackage".

import importpackage.*;

class CallPackage{public static void main(String[] args){HelloWorld h2=new HelloWorld();

h2.show();}

Page 108: Java Final Material

108 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

}

Out of the program:

C:\nisha\importpackage>javac *.javaC:\nisha\importpackage>cd..C:\nisha>javac CallPackage.javaC:\nisha>java CallPackage

This is the function of the class HelloWorld!!Make sure to the directory structure for this program shown as:

Using PackageThe listing below shows a package named package1 containing a single class ClassA.package package1;public class ClassA{

public void displayA(){

System.out.println(“Clas A”):}

}This source file should be named ClassA.java and stored in the subdirectory package1.Now compile this java file. The resultant ClassA.class will be stored in the same subdirectory.

Let us consider another package package2 containing again a single class as shown below:package package2;public class ClassB{

protected int m = 10;public void dispalyB(){

System.out.println(“Class B”);}

}As usual, the source file and the compiled file of this package are located in the subdirectory package2.Program shown below uses classes contained in both the packages.import pacakge1.ClassA;import pacakge2.*;class PackageTest2{

public static void main(String args[]){

ClassA objA = new ClassA();

Page 109: Java Final Material

109 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

ClassB objB = new ClassB();objA.displayA();objB.displayB();

}}This program will be saved as PackageTest.java, compiled and run to obtain the result:

Class AClass Bm = 10

Lesson 11: Thread

Overview of ThreadsA process is an instance of a computer program that is executed sequentially. It is a collection ofinstructions which are executed simultaneously at the rum time. Thus several processes may be associatedwith the same program. For example, to check the spelling is a single process in the Word Processorprogram and you can also use other processes like printing, formatting, drawing, etc. associated with thisprogram.

ThreadA thread is a lightweight process which exists within a program and executed to perform a special task.Several threads of execution may be associated with a single process. Thus a process that has only onethread is referred to as a single-threaded process, while a process with multiple threads is referred to as amulti-threaded process.In Java Programming language, thread is a sequential path of code execution within a program. Eachthread has its own local variables, program counter and lifetime. In single threaded runtime environment,operations are executes sequentially i.e. next operation can execute only when the previous one iscomplete. It exists in a common memory space and can share both data and code of a program. Threadingconcept is very important in Java through which we can increase the speed of any application. You can seediagram shown below in which a thread is executed along with its several operations within a singleprocess.

Main ThreadWhen any standalone application is running, it firstly execute the main() method runs in a one thread,called the main thread. If no other threads are created by the main thread, then program terminates whenthe main() method complete its execution. The main thread creates some other threads called child threads.The main() method execution can finish, but the program will keep running until the all threads havecomplete its execution.

Multithreading in Java

Page 110: Java Final Material

110 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

So far you have learned about a single thread. Lets us know about the concept of multithreading and learnthe implementation of it. But before that, lets be aware from the multitasking.Multitasking :Multitasking allow to execute more than one tasks at the same time, a task being a program. Inmultitasking only one CPU is involved but it can switches from one program to another program so quicklythat's why it gives the appearance of executing all of the programs at the same time. Multitasking allowprocesses (i.e. programs) to run concurrently on the program. For Example running the spreadsheetprogram and you are working with word processor also. Multitasking is running heavyweight processes bya single OS.Multithreading :Multithreading is a technique that allows a program or a process to execute many tasks concurrently (at thesame time and parallel). It allows a process to run its tasks in parallel mode on a single processor system.In the multithreading concept, several multiple lightweight processes are run in a single process/task orprogram by a single processor. For Example, When you use a word processor you perform a manydifferent tasks such as printing, spell checking and so on. Multithreaded software treats each process as aseparate program.In Java, the Java Virtual Machine (JVM) allows an application to have multiple threads of executionrunning concurrently. It allows a program to be more responsible to the user. When a program containsmultiple threads then the CPU can switch between the two threads to execute them at the same time.For example, look at the diagram shown as:

In this diagram, two threads are being executed having more than one task. The task of each thread isswitched to the task of another thread.

It is important to remember that ‘threads running in parallel’ does not really mean that they actually run atthe same time. Since all the threads are running on a single processor, the flow of execution is shared betweenthe threads. The java interpreter handles the switching of control between the threads in such a way that itappears they are running concurrently.Multithreading is a powerful programming tool that makes java distinctly different from its fellowprogramming languages. Multithreading is useful in a number of ways. It enables programmers to do multiplethings at one time. They can divide a long program into threads and execute them in parallel. For example, wecan send tasks such as printing into the background and continue to perform some other task in theforeground.

Advantages of multithreading over multitasking : Reduces the computation time. Improves performance of an application. Threads share the same address space so it saves the memory. Context switching between threads is usually less expensive than between processes. Cost of communication between threads is relatively low.

Page 111: Java Final Material

111 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Life Cycle of A ThreadWhen you are programming with threads, understanding the life cycle of thread is very valuable. While athread is alive, it is in one of several states. By invoking start() method, it doesn’t mean that the thread hasaccess to CPU and start executing straight away. Several factors determine how it will proceed.

Different states of a thread are:

1. New state – After the creations of Thread instance the thread is in this state but before the start()method invocation. At this point, the thread is considered not alive.

2. Runnable (Ready-to-run) state – A thread start its life from Runnable state. A thread first entersrunnable state after the invoking of start() method but a thread can return to this state after eitherrunning, waiting, sleeping or coming back from blocked state also. On this state a thread is waitingfor a turn on the processor.

3. Running state – A thread is in running state that means the thread is currently executing. There areseveral ways to enter in Runnable state but there is only one way to enter in Running state: thescheduler select a thread from runnable pool.

4. Dead state – A thread can be considered dead when its run() method completes. If any thread comeson this state that means it cannot ever run again.

5. Blocked - A thread can enter in this state because of waiting the resources that are hold by anotherthread.

Different states implementing Multiple-Threads are:

Page 112: Java Final Material

112 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

As we have seen different states that may be occur with the single thread. A running thread can enter to anynon-runnable state, depending on the circumstances. A thread cannot enter directly to the running state fromnon-runnable state; firstly it goes to runnable state. Now lets understand the some non-runnable states whichmay be occur handling the multithreads.

Sleeping – On this state, the thread is still alive but it is not runnable, it might be return to runnablestate later, if a particular event occurs. On this state a thread sleeps for a specified amount of time.You can use the method sleep( ) to stop the running state of a thread.

static void sleep(long millisecond) throws InterruptedException

Waiting for Notification – A thread waits for notification from another thread. The thread sendsback to runnable state after sending notification from another thread.

final void wait(long timeout) throws InterruptedExceptionfinal void wait(long timeout, int nanos) throws InterruptedExceptionfinal void wait() throws InterruptedException

Blocked on I/O – The thread waits for completion of blocking operation. A thread can enter on thisstate because of waiting I/O resource. In that case the thread sends back to runnable state afteravailability of resources.

Blocked for joint completion – The thread can come on this state because of waiting the completionof another thread.

Blocked for lock acquisition – The thread can come on this state because of waiting to acquire thelock of an object.

Methods that can be applied on a Thread:

Some Important Methods defined in java.lang.Thread are shown in the table:

Method ReturnType Description

start( ) void Start the thread by calling its run method.

run( ) voidThis method is the entry point to execute thread, like the main method for

applications.sleep( ) void Suspends a thread for a specified amount of time (in milliseconds).

activeCount( ) intThis method returns the number of active threads in a particular thread

group and all its subgroups.interrupt( ) void The method interrupt the threads on which it is invoked.

yield( ) voidBy invoking this method the current thread pause its execution temporarily

and allow other threads to execute.

Page 113: Java Final Material

113 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Thread CreationIn Java, an object of the Thread class can represent a thread. Thread can be implemented through any oneof two ways:

Extending the java.lang.Thread Class Implementing the java.lang.Runnable Interface

I. Extending the java.lang.Thread ClassFor creating a thread a class have to extend the Thread Class. For creating a thread by this procedure youhave to follow these steps:

1. Extend the java.lang.Thread Class. The Thread class can be extended as follows:class Mythread extends Thread{

………………

}2. Override the run( ) method in the subclass from the Thread class to define the code executed by the

thread. The basic implementation of run() method look like:public void run(){

……….//thread code here……….

}3. Create an instance of this subclass. This subclass may call a Thread class constructor by subclass

constructor.MyThread obj = new MyThread();

4. Invoke the start( ) method on the instance of the class to make the thread eligible for running. Toactually run an instance of our thread class, we must write the following:

obj,start();note : the 3rd and 4th step can be combines as follow:

new MyThread().start();

The following program demonstrates a single thread creation extending the "Thread" Class:class MyThread extends Thread{

String s=null;MyThread(String s1){

s=s1;start();

Page 114: Java Final Material

114 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

}public void run(){

System.out.println(s);}

}public class RunThread{

public static void main(String args[]){

MyThread m1=new MyThread("Thread started....");}

}

Output of the Program is :C:\j2se6\thread>javac RunThread.javaC:\j2se6\thread>java RunThreadThread started....

An example of multithreaded programming:class A extends thread{public void run(){

for(int i = 1; i <=5 ; i++){

System.out.println(“\tFrom ThreadA : i = “ + i);}System.out.println(“Exit from A”);

}}class B extends thread{public void run(){

for(int j = 1; j <=5 ; j++){

System.out.println(“\tFrom ThreadA : j = “ + j);}System.out.println(“Exit from B”);

}}class C extends thread{public void run(){

for(int k = 1; k <=5 ; k++){

System.out.println(“\tFrom ThreadA : k = “ + k);}

Page 115: Java Final Material

115 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

System.out.println(“Exit from C”);}}class TreadTest {public static void main(String args[]){

new A().start();new B().start();new C().start();

}}output :

First Run… Second Run…From Thread A : i = 1From Thread A : i = 2From Thread B : j = 1From Thread B : j = 2From Thread C : k = 1From Thread C : k = 2From Thread A : i = 3From Thread A : i = 4From Thread B : j = 3From Thread B : j = 4From Thread C : k = 3From Thread C : k = 4From Thread A : i = 5Exit from AFrom Thread B : j = 5Exit from BFrom Thread C : k = 5Exit from C

From Thread A : i = 1From Thread A : i = 2From Thread C : k = 1From Thread C : k = 2From Thread A : i = 3From Thread A : i = 4From Thread B : j = 1From Thread B : j = 2From Thread C : k = 3From Thread C : k = 4From Thread A : i = 5Exit from AFrom Thread B : j = 3From Thread B : j = 4From Thread C : k = 5Exit from CFrom Thread B : j = 5Exit from B

II. Implementing the java.lang.Runnable InterfaceThe procedure for creating threads by implementing the Runnable Interface is as follows:

1. A Class implements the Runnable Interface, override the run() method to define the code executedby thread. An object of this class is Runnable Object.

2. Create an object of Thread Class by passing a Runnable object as argument.3. Invoke the start( ) method on the instance of the Thread class.

The following program demonstrates the thread creation implenting the Runnable interface:class MyThread1 implements Runnable{

Thread t;String s=null;

MyThread1(String s1){

s=s1;t=new Thread(this);t.start();

}public void run()

Page 116: Java Final Material

116 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

{System.out.println(s);

}}public class RunableThread{

public static void main(String args[]){MyThread1 m1=new MyThread1("Thread started....");}

}However, this program returns the output same as of the output generated through the previous program.Output of the Program is:

C:\j2se6\thread>javac RunableThread.javaC:\j2se6\thread>java RunableThreadThread started....

Example:class X implements Runnable{

public void run(){

for(int i=1 ; i<=5 ; i++){

System.out.println(“\t ThreadX : “ + i);}

}}class RunnableTest{

public static void main(String args[]){

X objrun = new X();Thread threadX = new Thread(objrun);thread.start();System.out.println(“End of main Thread.”);

}}output:End of main Thread

ThreadX : 1ThreadX : 2ThreadX : 3ThreadX : 4ThreadX : 5

End of ThreadX

There are two reasons for implementing a Runnable interface preferable to extending the Thread Class:1. If you extend the Thread Class, that means that subclass cannot extend any other Class, but if you

implement Runnable interface then you can do this.

Page 117: Java Final Material

117 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

2. The class implementing the Runnable interface can avoid the full overhead of Thread class whichcan be excessive.

Thread PrioritiesIn Java, thread scheduler can use the thread priorities in the form of integer value to each of its thread todetermine the execution schedule of threads. Thread gets the ready-to-run state according to their priorities.The thread scheduler provides the CPU time to thread of highest priority during ready-to-run state.Priorities are integer values from 1 (lowest priority given by the constant Thread.MIN_PRIORITY) to 10(highest priority given by the constant Thread.MAX_PRIORITY). The default priority is5(Thread.NORM_PRIORITY).

Constant Description

Thread.MAX_PRIORITY The maximum priority of any thread (an int value of 10)

Thread.MIN_PRIORITY The minimum priority of any thread (an int value of 1)

Thread.NORM_PRIORITY The normal priority of any thread (an int value of 5)

The methods that are used to set the priority of thread shown as:Method Description

setPriority() This is method is used to set the priority of thread.getPriority() This method is used to get the priority of thread.

When a Java thread is created, it inherits its priority from the thread that created it. At any given time, whenmultiple threads are ready to be executed, the runtime system chooses the runnable thread with the highestpriority for execution. In Java runtime system, preemptive scheduling algorithm is applied. If at theexecution time a thread with a higher priority and all other threads are runnable then the runtime systemchooses the new higher priority thread for execution. On the other hand, if two threads of the same priorityare waiting to be executed by the CPU then the round-robin algorithm is applied in which the schedulerchooses one of them to run according to their round of time-slice.

Thread SchedulerIn the implementation of threading scheduler usually applies one of the two following strategies:

Preemptive scheduling – If the new thread has a higher priority than current running thread leavesthe runnable state and higher priority thread enter to the runnable state.

Time-Sliced (Round-Robin) Scheduling – A running thread is allowed to be execute for the fixedtime, after completion the time, current thread indicates to the another thread to enter it in therunnable state.

You can also set a thread's priority at any time after its creation using the setPriority method. Let’s see, howto set and get the priority of a thread.

class MyThread1 extends Thread{

MyThread1(String s){

super(s);start();

}public void run()

Page 118: Java Final Material

118 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

{for(int i=0;i<3;i++)

{Thread cur=Thread.currentThread();cur.setPriority(Thread.MIN_PRIORITY);int p=cur.getPriority();System.out.println("Thread Name :"+Thread.currentThread().getName());System.out.println("Thread Priority :"+cur);}

}}

class MyThread2 extends Thread{

MyThread2(String s){

super(s);start();

}

public void run(){

for(int i=0;i<3;i++){

Thread cur=Thread.currentThread();cur.setPriority(Thread.MAX_PRIORITY);int p=cur.getPriority();System.out.println("Thread Name :"+Thread.currentThread().getName());System.out.println("Thread Priority :"+cur);}

}}public class ThreadPriority{

public static void main(String args[]){

MyThread1 m1=new MyThread1("My Thread 1");MyThread2 m2=new MyThread2("My Thread 2");

}}Output of the Program:C:\nisha>javac ThreadPriority.java

C:\nisha>java ThreadPriorityThread Name :My Thread 1Thread Name :My Thread 2Thread Priority :Thread[My Thread 2,10,main]Thread Name :My Thread 2Thread Priority :Thread[My Thread 2,10,main]Thread Name :My Thread 2Thread Priority :Thread[My Thread 2,10,main]

Page 119: Java Final Material

119 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Thread Priority :Thread[My Thread 1,1,main]Thread Name :My Thread 1Thread Priority :Thread[My Thread 1,1,main]Thread Name :My Thread 1Thread Priority :Thread[My Thread 1,1,main]

In this program two threads are created. We have set up maximum priority for the first thread "MyThread2"and minimum priority for the first thread "MyThread1" i.e. the after executing the program, the first thread isexecuted only once and the second thread "MyThread2" started to run until either it gets end or anotherthread of the equal priority gets ready to run state.

DeadlockA situation where a thread is waiting for an object lock that holds by second thread and this second threadis waiting for an object lock that holds by first thread, this situation is known as Deadlock.Lets see a situation in the diagram shown below where the deadlock condition is occurred :

In this diagram two threads having the Printing & I/O operations respectively at a time. But Thread1need to printer that is hold up by the Thread2, likewise Thread2 need the keyboard that is hold up bythe Thread1. In this situation the CPU becomes ideal and the deadlock condition occurs because no onethread is executed until the holdup resources are free.The following program demonstrates the deadlock situation:

public class DeadDemo{public static void main(String args[]){String s1="Dead";String s2="Lock";MyThread1 m=new MyThread1(s1,s2);MyThread2 m1=new MyThread2(s1,s2);}

}

class MyThread1 extends Thread{String s1;String s2;MyThread1(String s1, String s2){this.s1=s1;this.s2=s2;

Page 120: Java Final Material

120 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

start();}

public void run(){while(true){synchronized(s1){synchronized(s2){System.out.println(s1+s2);}

}}

}}class MyThread2 extends Thread{

String s1;String s2;MyThread2(String s1,String s2){this.s1=s1;this.s2=s2;

start();}

public void run(){while(true){synchronized(s2){

synchronized(s1){System.out.println(s2+s1);}

}}

}}

Output of the program is:C:\j2se6\thread>javac DeadDemo.javaC:\j2se6\thread>java DeadDemoDeadLockDeadLockDeadLockDeadLockDeadLockDeadLockDeadLockDeadLockLockDeadLockDead

Page 121: Java Final Material

121 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

LockDeadLockDeadLockDeadLockDeadLockDeadDeadLockDeadLockDeadLockDeadLockDeadLockDeadLockDeadLock..................

C:\j2se6\thread>Synchronized ThreadsIn Java, the threads are executed independently to each other. These types of threads are called asasynchronous threads. But there are two problems may be occur with asynchronous threads.

Two or more threads share the same resource (variable or method) while only one of them can accessthe resource at one time.

If the producer and the consumer are sharing the same kind of data in a program then either producermay produce the data faster or consumer may retrieve an order of data and process it without itsexisting.

Suppose, we have created two methods as increment( ) and decrement( ). which increases or decreasesvalue of the variable "count" by 1 respectively shown as:

public void increment( ){

count++;}

public void decrement( ){

count--;}

public int value(){

return count;}

When the two threads are executed to access these methods (one for increment( ),another for decrement()) then both will share the variable "count". in that case, we can't be sure that what value will be returnedof variable "count".We can see this problem in the diagram shown below:

Page 122: Java Final Material

122 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

To avoid this problem, Java uses monitor also known as “semaphore” to prevent data from beingcorrupted by multiple threads by a keyword synchronized to synchronize them and intercommunicate toeach other. It is basically a mechanism which allows two or more threads to share all the availableresources in a sequential manner. Java's synchronized is used to ensure that only one thread is in a criticalregion. critical region is a lock area where only one thread is run (or lock) at a time. Once the thread is inits critical section, no other thread can enter to that critical region. In that case, another thread will has towait until the current thread leaves its critical section.General form of the synchronized statement is as:

synchronized(object){// statements to be synchronized}

Inter-Thread CommunicationJava provides a very efficient way through which multiple-threads can communicate with each-other. Thisway reduces the CPU’s idle time i.e. A process where, a thread is paused running in its critical region andanother thread is allowed to enter (or lock) in the same critical section to be executed. This technique isknown as Interthread communication which is implemented by some methods. These methods aredefined in "java.lang" package and can only be called within synchronized code shown as:

Method Description

wait( )It indicates the calling thread to give up the monitor and go to sleep until some other

thread enters the same monitor and calls method notify() or notifyAll().notify( ) It wakes up the first thread that called wait() on the same object.

notifyAll( )Wakes up (Unloack) all the threads that called wait( ) on the same object. The highest

priority thread will run first.All these methods must be called within a try-catch block.Lets see an example implementing these methods :

class Shared{int num=0;boolean value = false;synchronized int get(){

if (value==false)try {

wait();}

catch (InterruptedException e)

Page 123: Java Final Material

123 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

{System.out.println("InterruptedException caught");

}System.out.println("consume: " + num);value=false;notify();return num;}synchronized void put(int num){

if (value==true)try{

wait();}

catch (InterruptedException e){

System.out.println("InterruptedException caught");}this.num=num;System.out.println("Produce: " + num);value=false;notify();}}

class Producer extends Thread{

Shared s;Producer(Shared s){

this.s=s;this.start();

}public void run()

{int i=0;s.put(++i);

}}

class Consumer extends Thread{

Shared s;Consumer(Shared s)

{this.s=s;this.start();

}public void run()

Page 124: Java Final Material

124 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

{s.get();

}}public class InterThread{

public static void main(String[] args){

Shared s=new Shared();new Producer(s);new Consumer(s);

}}

Output of the Program:C:\jdk\bin>javac InterThread.javaC:\jdk\bin>java InterThreadProduce: 1consume: 1

In this program, two threads "Producer" and "Consumer" share the synchronized methods of the class"Shared". At time of program execution, the "put( )" method is invoked through the "Producer" classwhich increments the variable "num" by 1. After producing 1 by the producer, the method "get( )" isinvoked by through the "Consumer" class which retrieves the produced number and returns it to theoutput. Thus the Consumer can't retrieve the number without producing of it.

Lesson 12: Exceptions

The Java programming language uses exceptions to handle errors and other exceptional events. This lessondescribes when and how to use exceptions.Types of ErrorsErrors may broadly be classified into two categories:

1. Compile-time Errors2. Run-time Errors

Compile-time Errors:All Syntax errors will be detected and displayed by the Java compiler and therefore these errors are known ascompile-time errors. Whenever the compiler displays an error, it will not create the .class file. It is thereforenecessary that we fix all the errors before we can successfully compile and run the program.Most of the compile-time errors are due to typing mistakes. The common problems are:

Missing semicolons Missing brackets in classes and methods Misspelling of identifiers and keywords. Missing double quotes in strings Use of undeclared variables Incompatible types in assignments/initialization. Bad reference to objects. Use of = in place of == operator.

Run-time Errors:Sometimes, a program may compile successfully creating the .class file but may not run properly. Suchprograms may produce wrong output due to wrong logic or may terminate due to errors such as stackoverflow. Most common run-time errors are:

Page 125: Java Final Material

125 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Dividing an integer by zero. Accessing an element that is out of the bounds of an array. Trying to store a value into an array of an incompatible class or type. Trying to cast an instance of a class to one of its subclass. Passing a parameter that is not in a valid range or value for a method Trying to illegally change the state of a thread. Attempting to use a negative size for an array. Converting invalid string to number. Accessing a character that is out of bounds of a string.

What Is an Exception?The term exception is shorthand for the phrase "exceptional event."

Definition: An exception is an event, which occurs during the execution of a program, which disrupts thenormal flow of the program's instructions.

When an error occurs within a method, the method creates an object and hands it off to the runtime system.The object, called an exception object, contains information about the error, including its type and the state ofthe program when the error occurred. Creating an exception object and handing it to the runtime system iscalled throwing an exception.After a method throws an exception, the runtime system attempts to find something to handle it. The set ofpossible "somethings" to handle the exception is the ordered list of methods that had been called to get to themethod where the error occurred. The list of methods is known as the call stack (see the next figure).

The call stack.The runtime system searches the call stack for a method that contains a block of code that can handle theexception. This block of code is called an exception handler. The search begins with the method in which theerror occurred and proceeds through the call stack in the reverse order in which the methods were called.When an appropriate handler is found, the runtime system passes the exception to the handler. An exceptionhandler is considered appropriate if the type of the exception object thrown matches the type that can behandled by the handler.The exception handler chosen is said to catch the exception. If the runtime system exhaustively searches allthe methods on the call stack without finding an appropriate exception handler, as shown in the next figure,the runtime system (and, consequently, the program) terminates.

Page 126: Java Final Material

126 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Searching the call stack for the exception handler.Using exceptions to manage errors has some advantages over traditional error-management techniques.The purpose of exception handling mechanism is to provide a means to detect and report an “exceptionalcircumstances” so that appropriate action can be taken. The mechanism suggests incorporation of a separateerror handling code that performs the following tasks:

1. Find the problem (Hit the exception)2. Inform that an error has occurred (Throw the exception)3. Receive the error information (Catch the exception)4. Take corrective action (Handle the exception)

Some common exceptions that we must watch out for catching are listed below:Exception Type Cause of ExceptionArithmeticExcepton Caused by math error such as division by zeroArrayIndexOutOfBoundsException Caused by bad array indexesArrayStoreException Caused when a program tries to store the wrong type of data in an arrayFileNotFoundException Caused by an attempt to access a nonexistent fileIOException Caused by general I/O failures, such as inability to read from a fileNullPointerException Caused by referencing a null objectNumberFormatException Caused when a conversion between strings and number failsOutOfMemoryException Caused when there’s not enough memory to allocate a new object.StringIndexOutOfBoundsException Caused when a program attempts to access a nonexistent character

position in a string.

The Catch or Specify RequirementValid Java programming language code must honor the Catch or Specify Requirement. This means that codethat might throw certain exceptions must be enclosed by either of the following:

A try statement that catches the exception. The try must provide a handler for the exception, asdescribed in Catching and Handling Exceptions.

A method that specifies that it can throw the exception. The method must provide a throws clausethat lists the exception, as described in Specifying the Exceptions Thrown by a Method.

Code that fails to honor the Catch or Specify Requirement will not compile.Not all exceptions are subject to the Catch or Specify Requirement. To understand why, we need to look atthe three basic categories of exceptions, only one of which is subject to the Requirement.

The Three Kinds of Exceptions

Page 127: Java Final Material

127 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

The first kind of exception is the checked exception. These are exceptional conditions that a well-writtenapplication should anticipate and recover from. For example, suppose an application prompts a user for aninput file name, then opens the file by passing the name to the constructor for java.io.FileReader.Normally, the user provides the name of an existing, readable file, so the construction of the FileReaderobject succeeds, and the execution of the application proceeds normally. But sometimes the user supplies thename of a nonexistent file, and the constructor throws java.io.FileNotFoundException. A well-written program will catch this exception and notify the user of the mistake, possibly prompting for acorrected file name.Checked exceptions are subject to the Catch or Specify Requirement. All exceptions are checked exceptions,except for those indicated by Error, RuntimeException, and their subclasses.The second kind of exception is the error. These are exceptional conditions that are external to theapplication, and that the application usually cannot anticipate or recover from. For example, suppose that anapplication successfully opens a file for input, but is unable to read the file because of a hardware or systemmalfunction. The unsuccessful read will throw java.io.IOError. An application might choose to catchthis exception, in order to notify the user of the problem — but it also might make sense for the program toprint a stack trace and exit.Errors are not subject to the Catch or Specify Requirement. Errors are those exceptions indicated by Errorand its subclasses.The third kind of exception is the runtime exception. These are exceptional conditions that are internal to theapplication, and that the application usually cannot anticipate or recover from. These usually indicateprogramming bugs, such as logic errors or improper use of an API. For example, consider the applicationdescribed previously that passes a file name to the constructor for FileReader. If a logic error causes anull to be passed to the constructor, the constructor will throw NullPointerException. Theapplication can catch this exception, but it probably makes more sense to eliminate the bug that caused theexception to occur.Runtime exceptions are not subject to the Catch or Specify Requirement. Runtime exceptions are thoseindicated by RuntimeException and its subclasses.Errors and runtime exceptions are collectively known as unchecked exceptions.

Bypassing Catch or SpecifySome programmers consider the Catch or Specify Requirement a serious flaw in the exception mechanismand bypass it by using unchecked exceptions in place of checked exceptions. In general, this is notrecommended. The section Unchecked Exceptions — The Controversy talks about when it is appropriate touse unchecked exceptions.

Catching and Handling ExceptionsThis section describes how to use the three exception handler components — the try, catch, andfinally blocks — to write an exception handler. The last part of this section walks through an example andanalyzes what occurs during various scenarios.The following example defines and implements a class named ListOfNumbers. When constructed,ListOfNumbers creates a Vector that contains 10 Integer elements with sequential values 0 through9. The ListOfNumbers class also defines a method named writeList, which writes the list of numbersinto a text file called OutFile.txt. This example uses output classes defined in java.io, which arecovered in Basic I/O.//Note: This class won't compile by design!import java.io.*;import java.util.Vector;class ListOfNumbers{

Page 128: Java Final Material

128 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

private Vector vector;private static final int SIZE = 10;public ListOfNumbers (){

vector = new Vector(SIZE);for (int i = 0; i < SIZE; i++){

vector.addElement(new Integer(i));}

}public void writeList(){

PrintWriter out = new PrintWriter(new FileWriter("OutFile.txt"));for (int i = 0; i < SIZE; i++){

out.println("Value at: " + i + " = " + vector.elementAt(i));}out.close();

}}The first line in boldface is a call to a constructor. The constructor initializes an output stream on a file. If thefile cannot be opened, the constructor throws an IOException. The second boldface line is a call to theVector class's elementAt method, which throws an ArrayIndexOutOfBoundsException if thevalue of its argument is too small (less than 0) or too large (more than the number of elements currentlycontained by the Vector).If you try to compile the ListOfNumbers class, the compiler prints an error message about the exceptionthrown by the FileWriter constructor. However, it does not display an error message about the exceptionthrown by elementAt. The reason is that the exception thrown by the constructor, IOException, is achecked exception, and the one thrown by the elementAt method,ArrayIndexOutOfBoundsException, is an unchecked exception.Now that you're familiar with the ListOfNumbers class and where the exceptions can be thrown within it,you're ready to write exception handlers to catch and handle those exceptions

The try BlockThe first step in constructing an exception handler is to enclose the code that might throw an exception withina try block. In general, a try block looks like the following.

try{

Code // generates an exception}catch and finally blocks…

The segment in the example labeled code contains one or more legal lines of code that could throw anexception. (The catch and finally blocks are explained in the next two subsections.)To construct an exception handler for the writeList method from the ListOfNumbers class, enclosethe exception-throwing statements of the writeList method within a try block. There is more than oneway to do this. You can put each line of code that might throw an exception within its own try block andprovide separate exception handlers for each. Or, you can put all the writeList code within a single tryblock and associate multiple handlers with it. The following listing uses one try block for the entire methodbecause the code in question is very short.private Vector vector;

Page 129: Java Final Material

129 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

private static final int SIZE = 10;PrintWriter out = null;try{

System.out.println("Entered try statement");out = new PrintWriter(new FileWriter("OutFile.txt"));for (int i = 0; i < SIZE; i++){

out.println("Value at: " + i + " = " + vector.elementAt(i));}

}catch and finally statements . . .If an exception occurs within the try block, that exception is handled by an exception handler associatedwith it. To associate an exception handler with a try block, you must put a catch block after it; the nextsection shows you how.

The catch BlocksYou associate exception handlers with a try block by providing one or more catch blocks directly after thetry block. No code can be between the end of the try block and the beginning of the first catch block.try{

}catch (ExceptionType name){

}catch (ExceptionType name){

}Each catch block is an exception handler and handles the type of exception indicated by its argument. Theargument type, ExceptionType, declares the type of exception that the handler can handle and must be thename of a class that inherits from the Throwable class. The handler can refer to the exception with name.The catch block contains code that is executed if and when the exception handler is invoked. The runtimesystem invokes the exception handler when the handler is the first one in the call stack whoseExceptionType matches the type of the exception thrown. The system considers it a match if the thrownobject can legally be assigned to the exception handler's argument.The following are two exception handlers for the writeList method — one for two types of checkedexceptions that can be thrown within the try statement.try{

}catch (FileNotFoundException e){

System.err.println("FileNotFoundException: " + e.getMessage());throw new SampleException(e);

}

Page 130: Java Final Material

130 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

catch (IOException e){

System.err.println("Caught IOException: " + e.getMessage());}Both handlers print an error message. The second handler does nothing else. By catching any IOExceptionthat's not caught by the first handler, it allows the program to continue executing.The first handler, in addition to printing a message, throws a user-defined exception. (Throwing exceptions iscovered in detail later in this chapter in the How to Throw Exceptions section.) In this example, when theFileNotFoundException is caught it causes a user-defined exception called SampleException tobe thrown. You might want to do this if you want your program to handle an exception in this situation in aspecific way.Exception handlers can do more than just print error messages or halt the program. They can do errorrecovery, prompt the user to make a decision, or propagate the error up to a higher-level handler usingchained exceptions, as described in the Chained Exceptions section.

The finally BlockThe finally block always executes when the try block exits. This ensures that the finally block isexecuted even if an unexpected exception occurs. But finally is useful for more than just exceptionhandling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return,continue, or break. Putting cleanup code in a finally block is always a good practice, even when noexceptions are anticipated.

Note: If the JVM exits while the try or catch code is being executed, then the finally block will notexecute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finallyblock will not execute even though the application as a whole continues.

The try block of the writeList method that you've been working with here opens a PrintWriter. Theprogram should close that stream before exiting the writeList method. This poses a somewhatcomplicated problem because writeList's try block can exit in one of three ways.

1. The new FileWriter statement fails and throws an IOException.2. The vector.elementAt(i) statement fails and throws an

ArrayIndexOutOfBoundsException.3. Everything succeeds and the try block exits normally.

The runtime system always executes the statements within the finally block regardless of what happenswithin the try block. So it's the perfect place to perform cleanup.The following finally block for the writeList method cleans up and then closes the PrintWriter.finally{

if (out != null){

System.out.println("Closing PrintWriter");out.close();

}else{

System.out.println("PrintWriter not open");}

}

Page 131: Java Final Material

131 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

In the writeList example, you could provide for cleanup without the intervention of a finally block.For example, you could put the code to close the PrintWriter at the end of the try block and againwithin the exception handler for ArrayIndexOutOfBoundsException, as follows.try{

out.close(); //Don't do this; it duplicates code.}catch (FileNotFoundException e){

out.close(); //Don't do this; it duplicates code.System.err.println("Caught: FileNotFoundException: " +

e.getMessage());throw new RuntimeException(e);

}catch (IOException e){

System.err.println("Caught IOException: " + e.getMessage());}However, this duplicates code, thus making the code difficult to read and error-prone should you modify itlater. For example, if you add code that can throw a new type of exception to the try block, you have toremember to close the PrintWriter within the new exception handler.

Important: The finally block is a key tool for preventing resource leaks. When closing a file or otherwiserecovering resources, place the code in a finally block to ensure that resource is always recovered.Putting It All TogetherThe previous sections described how to construct the try, catch, and finally code blocks for thewriteList method in the ListOfNumbers class. Now, let's walk through the code and investigate whatcan happen.When all the components are put together, the writeList method looks like the following.void writeList(){

PrintWriter out = null;try{

System.out.println("Entering try statement");out = new PrintWriter(new FileWriter("OutFile.txt"));

for (int i = 0; i < SIZE; i++)out.println("Value at: " + i + " = " +

vector.elementAt(i));

}catch (ArrayIndexOutOfBoundsException e){

System.err.println("Caught " + "ArrayIndexOutOfBoundsException:"

+ e.getMessage());

}catch (IOException e)

Page 132: Java Final Material

132 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

{System.err.println("Caught IOException: " + e.getMessage());

}finally{

if (out != null){

System.out.println("Closing PrintWriter");out.close();

}else{

System.out.println("PrintWriter not open");}

}}

Throwing our own ExceptionThere may be times when we would like to throw our own exceptions. We can do this by using the keywordthrow as follows:

throw new Throwable_subclass;Example:

throw new ArithmeticException();Following program demonstrate the use of user-defined subclass of Throwable class. Note that Exception isa subclass of Throwable and therefore MyException is a subclass of Throwable class. An object of a classthat extends Throwable can be thrown and caught.import java.lang.Exception;class MyException extendsException{

MyException(String message){

super(message);}

}class TestMyException{

public static void main(String args[]){int x=5, y=1000;try{

float z = (float) x / (float) y;if( z < 0.01){

throw new MyException(“Number is too small.”);}

}catch (MyException e){

System.out.println(“Caught my exception”);System.out.println(e.getMessage());

Page 133: Java Final Material

133 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

}finally{

System.out.println(“I am always here.”);}

} }A run of program produce:

Caught my exceptionNumber is too small.I am always here.

The object e which contains the error message “Number is too small” is caught by the catch block which thendisplays the message using the getMessage() method.

Lesson 13: Applet

IntroductionApplet is java program that can be embedded into HTML pages. Java applets runs on the java enables webbrowsers such as mozila and internet explorer. Applet is designed to run remotely on the client browser, sothere are some restrictions on it. Applet can't access system resources on the local computer. Applets areused to make the web site more dynamic and entertaining.

Advantages of Applet: Applets are cross platform and can run on Windows, Mac OS and Linux platform Applets can work all the version of Java Plugin Applets runs in a sandbox, so the user does not need to trust the code, so it can work without security

approval Applets are supported by most web browsers Applets are cached in most web browsers, so will be quick to load when returning to a web page User can also have full access to the machine if user allows

Disadvantages of Java Applet: Java plug-in is required to run applet Java applet requires JVM so first time it takes significant startup time If applet is not already cached in the machine, it will be downloaded from internet and will take time Its difficult to design and build good user interface in applets compared to HTML technology

How Applets differ from ApplicationsAlthough both the applets and stand-alone applications are Java programs, there are significant differencesbetween them. Applets are not full-featured application programs. They are usually written to accomplish asmall task or a component of a task. Since they are usually designed for use on the Internet, they imposecertain limitations and restrictions in their design.1. Applets do not use the main() method for initiating the execution of the code. Applets, when loaded,automatically call certain methods of Applet class to start and execute the applet code.2. Unlike stand-alone applications, applets cannot be run independently. They are run from inside a webpageusing a special feature known as HTML tag.3. Applets cannot read from or write to the files in the local computer.4. Applets cannot communication with other servers on the network.5. Applets cannot run any program from the local computer.6. Applets are restricted from using libraries from other languages such as C or C++.

Page 134: Java Final Material

134 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

Life Cycle of AppletApplet runs in the browser and its lifecycle method are called by JVM when it is loaded and destroyed.Here are the lifecycle methods of an Applet:

init(): This method is called to initialized an appletstart(): This method is called after the initialization of the applet.stop(): This method can be called multiple times in the life cycle of an Applet.destroy(): This method is called only once in the life cycle of the applet when applet is destroyed.

init () method: The life cycle of an applet begins when the applet is first loaded into the browser andcalled the init() method. The init() method is called only one time in the life cycle on an applet. The init()method is basically called to read the PARAM tag in the html file. The init () method retrieve the passedparameter through the PARAM tag of html file using get Parameter() method All the initialization such asinitialization of variables and the objects like image, sound file are loaded in the init () method .After theinitialization of the init() method user can interact with the Applet and mostly applet contains the init()method.

Start () method: The start method of an applet is called after the initialization method init(). This methodmay be called multiple times when the Applet needs to be started or restarted. For Example if the userwants to return to the Applet, in this situation the start Method() of an Applet will be called by the webbrowser and the user will be back on the applet. In the start method user can interact within the applet.

Stop () method: The stop() method can be called multiple times in the life cycle of applet like the start ()method. Or should be called at least one time. There is only miner difference between the start() methodand stop () method. For example the stop() method is called by the web browser on that time When the userleaves one applet to go another applet and the start() method is called on that time when the user wants togo back into the first program or Applet.

destroy() method: The destroy() method is called only one time in the life cycle of Applet like init()method. This method is called only on that time when the browser needs to Shut down.

The steps involved in developing and testing in applet are:1. Building an applet code (.java file)2. Creating an executable applet. (.class file)3. Designing a web page using HTML tags.4. Preparing <APPLET> tag.5. Incorporating <APPLET> tag into the web page.6. Creating HTML file.7. Testing the applet code.

Creating First Applet ExampleFirst of all we will know about the applet. An applet is a program written in java programming languageand embedded within HTML page. It runs on the java enabled web browser such as Netscape navigator orInternet Explorer.In this example you will see, how to write an applet program. Java source of applet is then compiled intojava class file and we specify the name of class in the applet tag of html page. The java enabled browserloads class file of applet and run in its sandbox.Here is the java code of program:

import java.applet.*;import java.awt.*;

Page 135: Java Final Material

135 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

public class FirstApplet extends Applet{

public void paint(Graphics g){

g.drawString("Welcome in Java Applet.",40,20);}

}Here is the HTML code of the program:

<HTML><HEAD></HEAD><BODY><APPLET ALIGN="CENTER" CODE="FirstApplet.class" WIDTH="800"HEIGHT="500"></APPLET></BODY></HTML>

Passing Parameter in Java AppletJava applet has the feature of retrieving the parameter values passed from the html page. So, you can passthe parameters from your html page to the applet embedded in your page. The param tag(<parma name=""value=""></param>) is used to pass the parameters to an applet. For the illustration about the concept ofapplet and passing parameter in applet, a example is given below.In this example, we will see what has to be done in the applet code to retrieve the value from parameters.Value of a parameter passed to an applet can be retrieved using getParameter() function. E.g. code:String strParameter = this.getParameter("Message");

Printing the valueThen in the function paint (Graphics g), we prints the parameter value to test the value passed from htmlpage. Applet will display "Hello! Java Applet" if no parameter is passed to the applet else it will displaythe value passed as parameter. In our case applet should display "Welcome in Passing parameter in javaapplet example." message.Here is the code for the Java Program :

import java.applet.*;import java.awt.*;public class appletParameter extends Applet

{private String strDefault = "Hello! Java Applet.";public void paint(Graphics g)

{String strParameter = this.getParameter("Message");if (strParameter == null)strParameter = strDefault;g.drawString(strParameter, 50, 25);

}}

Here is the code for the html program:<HTML><HEAD><TITLE>Passing Parameter in Java Applet</TITLE>

Page 136: Java Final Material

136 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

</HEAD><BODY>This is the applet:<P><APPLET code="appletParameter.class" width="800" height="100"><PARAM name="message" value="Welcome in Passing parameter in java appletexample."></APPLET></BODY></HTML>

There is the advantage that if need to change the output then you will have to change only the value of theparam tag in html file not in java code.Compile the program:javac appletParameter.javaOutput after running the program:To run the program using appletviewer, go to command prompt and type appletviewerappletParameter.html Appletviewer will run the applet for you and it should show output like Welcome inPassing parameter in java applet example. Alternatively you can also run this example from yourfavorite java enabled browser.Here is the code for the html program :

<HTML><HEAD><TITLE>Passing Parameter in Java Applet</TITLE></HEAD><BODY>This is the applet:<P><APPLET code="appletParameter.class" width="800" height="100"><PARAM name="message" value="Welcome in Passing parameter in java applet example."></APPLET></BODY></HTML>

There is the advantage that if need to change the output then you will have to change only the value of theparam tag in html file not in java code.Compile the program :javac appletParameter.javaOutput after running the program :To run the program using appletviewer, go to command prompt and type appletviewerappletParameter.html Appletviewer will run the applet for you and and it should show output likeWelcome in Passing parameter in java applet example. Alternatively you can also run this examplefrom your favorite java enabled browser.

Lesson 14: Graphics

Graphics environment variablesGraphics commands are called as methods belonging to a special type of variable, called a GraphicsEnvironment variable. Normally, these commands will only be called in the special method called paint,which is given the task of drawing the screen.When the Java applet is activated, Java looks for a method called paint which has a single parameter of typeGraphics. If it doesn't find one, then it doesn't spit out an error - but it doesn't draw anything on the screeneither! Java also calls the paint method automatically in some other circumstances. For instance, if you resize

Page 137: Java Final Material

137 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

the browser window in which the applet is sitting, you will see the applet flicker as the screen is automaticallyupdated.Usually, Java applets contain a method like this:

public void paint (Graphics g){

Screen-drawing statements go here}

All the screen drawing instructions will start with the characters g., indiciating that they are part of theGraphics parameter passed. However, the parameter is only called g by tradition - there's no logical reasonwhy the parameter shouldn't be called any legal name you want. You could easily write a paint method thatlooked like this:

public void paint (Graphics three_blind_mice){

three_blind_mice.drawLine(100,150,325,72);}

In this case, all the drawing instructions would start with three_blind_mice. as that is the name of theparameter. There may be cases where you need to draw things on the screen at some other point in theprogram. You can access the screen at any point by declaring a variable of type Graphics and using themethods within it. I will go into variables in more detail in a later section, but suffice it to say that if you everneed to draw something on the screen at some point other than in the paint() method, then include thefollowing lines in your program at the relevant point:

Graphics temp_g = getGraphics();temp_g.drawOval(300,120,100,75);

The first of the two lines declares a graphics environment variable - I've chosen to call it temp_g, but youcould give it any name you wanted - and sets it to the current graphics settings, using the built-in methodgetGraphics. Be careful to get the capital letter in that - Java is case sensitive, and it won't recognise themethod if you call it GETGRAPHICS or Getgraphics etc.The second of the two lines is an example of how the new graphics variable could be used. Obviously, youwould replace that line with the particular instruction that you wanted.The co-ordinate systemAll graphics instructions use a co-ordinate system just like the one that you learned at school. Each "unit" isone pixel wide, so the entire screen is about 600 units wide and about 400 or so units high. This is why co-ordinates in Java programs tend to be fairly large values.The (0,0) point of the co-ordinates (the origin) is always the top-leftcorner of the Java applet window. The first number of each pair refers tothe number of pixels across the screen, the second number refers to thenumber of pixels down the screen. The maximum co-ordinate values ineach case depend on the size of the applet window, which was determinedwhen the applet was called in the web page. You will recall that you calledit with the command

<applet code="first.class" width="150" height="150"></applet>The width="150" height="150" part determines the maximum co-ordinate as (150,150). If you try to draw something at a co-ordinate larger than this, then it wouldn't appear onthe screen. If you draw anything (a line, oval or rectangle) that would be partly on the screen and partly off,then only a fraction of the shape would appear, chopped off by the edge of the window.Lines, ovals, rectangles and arcsThe graphics environment contains the following instructions for drawing lines, ovals (ellipses - includingcircles), rectangles and arcs:g.drawLine(100,100,420,312);g.drawRect(72,160,200,35);

Page 138: Java Final Material

138 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

g.drawOval(300,120,100,75);g.drawArc(250,250,100,100,0,180);Note that all the instructions start with g. as they are part of the Graphics Environment variable g. They allalso end with a semicolon (;). All statements - graphics or otherwise - in Java end with a semicolon. Also,bear in mind that names in Java are case sensitive, so the names must be typed in in lower case letters with thesingle upper case (capital) letter in the middle of the name as shown. Otherwise the compiler won't recognisethem.The instruction drawLine draws a line (surprise, surprise!) It is given fournumbers. The first two numbers represent the x- and y-co-ordinates of one end ofthe line, and the last two number represent the x- and y-co-ordinates of the otherend. The instruction that you see abovedraws aline fromco-ordinates (100,100) to (420,312).The instruction drawRect drawsa rectangle. It is given fournumbers. The first two numbers arethe x- and y-co-ordinates of the top-left corner. You might expect the other two numbers to be the x- and y-co-ordinates of the opposite corner (as they would be in some other programming languages), but no! Theyrepresent the width and the height of the rectangle. In the case of the example above, the rectangle has its top-left corner at (72,160) and a width of 200 and a height of 35. Its bottom-right corner is at (72+200,160+35)i.e. (272,195).The instruction drawOval is given four numbers. You have toimagine that the oval is drawn within an invisible rectangle. Thefour numbers represent the top-left co-ordinates of the rectangleand its width and height, in the same way as for rectangles. Thismean that the oval drawn in the example above completely fillsan invisible rectangle whose top-left co-ordinate is at (300,120)and whose bottom-right co-ordinate is at (400,195). The widthof the oval at its widest point is 100 pixels, and its height at itsmaximum point is 75. There is no standard way of drawing an oval at a slanted angle.The graphics environment also gives a method which draws arcs, i.e. sections of oval shapes (or circles, ofcourse). Arcs have starting angles and arc angles, with all angles being measured from the "East" position(pointing to the right). The arc angle basically means the ending angle minus the starting angle.To draw an arc, use the drawArc command. This is given six numbers. The first four specify the rectangle inwhich the entire oval is enclosed, even though only part of that oval is to be drawn. The last two numbersspecify the starting angle and the arc angle (both in degrees). Here's an example:drawArc(100,100,80,60,45,120);Of course, if the start angle is specified as 0 and the ending angle as360, then the arc drawn is a complete oval.Filled shapesThere are three more shape-drawing instructions, they are the "fill"equivalent of drawRect, drawOval and drawArc:g.fillRect(72,160,200,35);g.fillOval(300,120,100,75);g.fillArc(250,250,100,100,0,180);The results they produce is simply a filled-in version of the basic shape, except for fillArc which produces apie-slice effect.Text strings

Page 139: Java Final Material

139 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

You already met the instruction used to display strings on the screen. In case you didn't, you won't besurprised to hear that it is drawString. Just to remind you - a string is a piece of text, anything from a singlecharacter (a term which includes letters, punctuation, symbols such as @ or ^, and even the space character)to a whole sentence. Strings are specified by placing them within double quotation marks.The method drawString is given three parameters between brackets. The first item is the string itself to bedisplayed on the screen. The other two numbers specify where the string is to appear. It represents the top-leftcorner of the string. However, the second number actually specifies the y-co-ordinate of a line on which thetext sits. Some characters, such as 'g' or 'y' will drop down below this imaginary line, as shown in thefollowing example:g.drawString("This is hugely easy",40,60);

ColorIf you don't specify a color for drawing shapes or text, then Java uses the default color of black. Specifying acolor is fairly easy - although you can only specify one of 13 standard colors (including white).There is a standard method built into graphics environment variables called setColor (note the Americanspelling of 'Color'). It expects to be given a color name, but the color name must be of a standard typespecified in yet another class called Color. What all this means is that colors are chosen as follows:

g.setColor(Color.blue);g.setColor(Color.orange);

Here are the thirteen standard colors. Make sure you use them exactly as specified - don't alter the case of theletters or insert spaces in the middle of them, and note the spelling of 'Gray'.black Gray orange yellow blue

green pink cyan lightGray red

darkGray magenta white

Any color that you choose will then be used for drawing all lines, text, shapes and as the fill-in color forshapes until you choose another color. You can also determine the color of the background to the applet. Thisis done using the following instruction:

setBackground(Color.cyan);Again, like the setColor method, it is important to note that the name of the method is all lower case lettersexcept for the capital B in the middle. However, please note that setBackground is not part of the graphicsenvironment, and as such, does not need to be preceded by g. In fact, if you do put g. at the beginning, thenthe Java compiler complains. I have fallen into this trap many times!

An example graphical appletHere is an example Java applet which demonstrates the commands that described ablove.

import java.awt.*;import java.applet.*;public class graph_ex extends Applet{

public void paint (Graphics g){ setBackground(Color.cyan);

g.drawString("Here are a selection of blank shapes.",20,40);g.drawLine(20,40,200,40);g.setColor(Color.blue);g.drawLine(20,50,70,90);g.setColor(Color.red);g.drawRect(100,50,32,55);g.setColor(Color.green);

Page 140: Java Final Material

140 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

g.drawOval(150,46,60,60);g.setColor(Color.magenta);g.drawArc(230,50,65,50,30,270);g.setColor(Color.black);g.drawString("Here are the filled equivalents.",20,140);g.drawLine(20,140,200,140);g.setColor(Color.yellow);g.fillRect(100,150,32,55);g.setColor(Color.pink);g.fillOval(150,146,60,60);g.setColor(Color.darkGray);g.fillArc(230,150,65,50,30,270);

}}

Using control loops in AppletsWe can use all control structures in an applet. Following program uses for loop for drawing circles repeatedly.import java.awt.*;import java.applet.*;public class ControlLoop extends Applet{

public void paint(Graphics g){

for(int i=0; i<=4; i++){

if( (i%2) == 0)g.drawOval(120, i*60+10, 50, 50);

elseg.fillOval(120, i*60+10, 50, 50);

}}

}Output:

Page 141: Java Final Material

141 6,7(2nd Floor ) Ronak Plaza, Nr. Tulsidham char Rasta, Manjalpur. Ph: 320902903rd (Floor) Kanchan Ganga Appt., Nr. Chakli Circle, Race course Ph: 3249499

repaintOccasionally, there will be points in the program where you will want it redraw the screen. Perhaps the screenhas changed (the paint method can easily cope with if statements that get it to draw different things indifferent circumstances). To call the paint method in these circumstances, use the following instruction:

repaint();Note that there are no parameters (no numbers, strings or graphics environments) passed to this method, butyou still must include the two brackets and follow them with the obligatory semicolon, like this ();It is vital that you don't include this method inside the paint method itself. If you did, the paint method wouldnever terminate, as it would always be calling itself.