Вы находитесь на странице: 1из 175

SYLLABUS

SYLLABUS Basic concepts of Object Oriented Programming, Genesis of java, History of java, Features of java,

Basic concepts of Object Oriented Programming, Genesis of java, History of java, Features of java, Java Virtual Machine (JVM), Difference between java and C++, Java Tokens, Variables and Operators, Array, Conditional Statements, Control Statements. Garbage Collector

Classes and Objects, Assess Specifier, Constructor, Subclasses, Inheritance, Abstract Class, Packages and Interfaces, Exception Handling, Applet Programming, AWT package, Layout, Swings, Java Streams, JDBC, Multithreading, Java.Util package

www.arihantinfo.com

Table of Content

UNIT 1: Concepts of Object Oriented Programming

1. Basics of OOP’s

1.1Introduction

1.2Object Oriented Paradigm 1.3Basic concepts of Object Oriented Programming

1.3.1 Object

1.3.2 Classes

1.3.3 Data Abstraction and Encapsulation

1.3.4 Inheritance

1.3.5 Polymorphism

UNIT 2: Fundamentals of Java Language

1. Introduction to Java

2.1 Genesis of Java

2.2 Why Java?

2.3 History of Java

2.4 Oak

2.5 Java Feature

2.5.1 Simple

2.5.2 Secure

2.5.3 Portable

2.5.4 Object Oriented

2.5.5 Interpreted

2.5.6 Robust

2.5.7 Multithreaded

2.5.8 Interpreted

2.5.9 Dynamic and Distributed

2.5.10 Architecture Nature and Portable

2.6 Difference between java and C++

2.7 The Java Virtual Machine

2.8 Java Program Structure

2.9 Java Token

2.9.1 Identifiers

2.9.2 Keywords

2.9.3 Literals

2.9.4 Operators

2.9.5 Separators

2.10Comments

2.11White Space

2.12Constants

2.13Backslash Character Constant

UNIT 3: Variables and Operators

3.1Variables

3.2Data Types in java 3.3Scope of Variables

www.arihantinfo.com

3.4Array

3.4.1

One-Dimensional Array

3.4.2

Two-Dimensional Array

3.5Strings

3.6Operators

3.6.1

Arithmetic Operators

3.6.2

Assignment Operators

3.6.3

Conditional Operators

3.6.4

Special Operators

3.6.5

Relational Operators

3.6.6

Boolean Logical Operators

3.6.7

Incrementing and Decrementing Operators

3.6.8

Bitwise Operators

3.7Operator Precedence

UNIT 4: Control Statements 4.1Selection Statements

4.1.1 If

4.1.2 If

Else

4.1.3 If

Else

if

else

4.2The Switch Statement

4.3Iteration Statement

4.3.1 The while Statement

4.3.2 The do Statement

4.3.3 The for Statement

4.4The Comma Operator 4.5The break Statement 4.6The continue Statement

UNIT 5: Classes and Objects

5.1Classes

5.1.1 The class Declaration

5.1.2 Declaring a class’s Superclass

5.1.3 Listing the interface implemented by a class

5.1.4 Summary of a class Declaration

5.2Declaring Member Variables 5.3Declaring Constants

5.4The Method Declaration 5.5Object Creation and Constructors

5.5.1

Object Creation

4.5.2

Constructor

5.6Controlling access to member of a class

5.6.1 Private

5.6.2 Protected

5.6.3 Public

5.7Subclasses and Inheritance

5.7.1 Definition

5.7.2 Creating Subclasses

5.8Overriding Methods

5.9Final classes and Methods

5.9.1 Final Classes

www.arihantinfo.com

5.9.2 Final Methods

5.10 Abstract classes and Methods

5.10.1 Abstract classes

5.10.2 Abstract Methods

UNIT 6: Packages and Interfaces

6.1Packages

6.1.1

How to create your own packages

6.2Classpath

6.3The meaning of static 6.4Cleanup: Finalization and Garbage collection 6.5Forcing Finalization and Garbage collection

6.6Interfaces

6.6.1

What is an interface

6.6.2

The interface Declaration

6.6.3

Multiple Extension (Inheritance)

6.6.4

Implementing an interface

6.6.5

Using an interface as a type

6.6.6

Interfaces verses abstract classes

UNIT 7: GUI Programming

7.1Introduction to Applet Programming 7.2What are Applets

7.2.1 What applet can do

7.2.2 What applet can not do

7.3Types of an Applet

7.3.1

Local Applet

7.3.1.1

Remote Applet

7.4Lifecycle of an Applet 7.5Passing parameters to an Applet

UNIT 8: Programming the Abstract Windowing Toolkit (AWT) 8.1Introduction of AWT 8.2AWT Component Hierarchy 8.3How to Add a Component to a Container 8.4AWT Component

8.4.1 Labels

8.4.2 Buttons

8.4.3 Checkbox

8.4.4 TextFields

8.4.5 TextAreas

8.4.6 Choice lists

8.4.7 Scrolling Lists

8.5Event Handling

8.5.1 Introduction

2.5.2 Event Listener Interfaces

8.6How to implement event handlers:

8.6.1 Buttons

8.6.2 Canvases

8.6.3 Checkboxes

www.arihantinfo.com

8.6.4 Choices

8.6.5 Lists

8.6.6 ScrollPanes

8.6.7 TextComponent

8.6.8 Menus

8.7AWT Containers

8.7.1

Frames

8.7.2

Panels

8.7.3

Dialogs

8.8Layouts

8.8.1

The FlowLayout Class

8.8.2

The BoderLayout Class

8.8.3

The GridLayout Class

8.8.4

The GridBagLayout Class

8.8.5

The CardLayout class

8.8.6

Combining Layouts with Nested Panels

8.9Using Adapters to Handle Events

UNIT 9: JFC AND SWING COMPONENT

9.1Introduction

9.2Difference between AWT and Swing Components 9.3Overview of Jcomponent 9.4All about Controls (JComponents)

9.4.1 JApplet Example

9.4.2 JFrame

9.4.3 Changing the Look and Feel (LAF)

9.4.4 Jlabel

9.4.5 JButton

9.4.6 New Feature in JDK 1.2.2

9.4.7 JtoolTip

9.4.8 JtextField

9.4.9 JcheckBox

9.4.10 Jpanel

9.4.11 JSlider Basics

UNIT 10: Advance Programming Element Java Streams 10.1What is Stream 10.2Byte Stream

10.2.1 File Stream

10.2.2 Data Stream

10.3 Character Streams

10.3.1 Reading Text Files

10.3.2 Writing Text Files

UNIT 11: Exception Handling

11.1Introduction

11.2What are Exception

www.arihantinfo.com

11.3Try/catch

11.4The finally clause 11.5The throws clause 11.6The throw clause 11.7User Define Exception

UNIT 12: Java Database Connectivity

12.1 Getting started with JDBC

12.2 What is JDBC

12.3 JDBC Architecture

12.4 JDBC API Interface in a Nutshell

12.4.1 Driver Manager

12.4.2 Connection

12.4.3 Statement

12.4.4 Resultset

12.4.5 CallabelStatement

12.4.6 DatabaseMetaData

12.4.7 Driver

12.4.8 PreparedStatement

12.4.9 ResultSetMetaData

12.4.10DriverPropertyInfo

12.4.11Date

12.4.12Time

12.4.13TimeStamp

12.4.14Types

12.4.15Numeric

12.4.16Driver Interface

12.5 Application Area

12.6 Getting to Work

12.6.1 How to configure ODBC Driver

12.6.2 Connecting to a database

12.6.3 Executing database Queries

12.7 The Statement clause

12.8 The ResultSet class

12.9 More Complex Uses of JDBC

12.9.1 The PreaparedStatement class

12.9.2 The CallableStatement class

12.10Working with Multiple Database 12.11“DNSLess” Connection with the JDBC-ODBC “Bridge” Driver

12.11.1.1 MS Access Example

12.11.1.2 ODBC Driver for Oracle(from Oracle)

12.11.1.3 ODBC Driver for Oracle(from Microsoft)

12.11.1.4 ODBC Driver for Excel

UNIT 13: Multithreaded Application

13.1Introduction of Multithreading 13.2What is a Thread 13.3Creating New Threads

13.3.1 Subclassing the Thread class

13.4Implementing the Runnable Interface

13.5Thread States

www.arihantinfo.com

13.6The Thread API 13.7Scheduling and Priority 13.7.1 Setting Thread Priority 13.7.2 Waking up a Thread 13.7.3 Suspending and Resuming Thread Execution 13.7.4 Putting a Thread to Sleep

UNIT 14: The Java.util Package

14.1Introduction

14.2The Java collection Advantage: An Overview 14.3A good API 14.4Other Capabilities 14.5Sorting a Collection 14.6Unmodifiable collection 14.7Synchronized Collection

www.arihantinfo.com

UNIT 1: BASICS OF OOP’S

UNIT 1: BASICS OF OOP’S 1.1 Introduction 1.2 Object Oriented Paradigm 1.3 Basic concepts of Object

1.1 Introduction

1.2 Object Oriented Paradigm

1.3 Basic concepts of Object Oriented Programming

1.3.1 Object

1.3.2 Classes

1.3.3 Data Abstraction and Encapsulation

1.3.4 Inheritance

1.3.5 Polymorphism

1.1 Introduction

The object-oriented paradigm was first conceived in the 1960's and implemented in languages such as SIMULA-67. One of the initial concerns with early object-oriented languages was their efficiency. Programs written using structured languages, such as Pascal and C, executed faster than programs written using early object-oriented languages. Although programs which used the object-oriented paradigm were more extensible and easier to maintain from a programmer's point of view, an unacceptable price had to be paid in the program's runtime behaviour. Recently, however, the runtime execution of object- oriented programs has improved considerably. This has been due in part to both the development of faster hardware and the creation of efficient languages and compilers which support object-oriented programming, such as C++. These facts, in addition to the ever- increasing accessibility of object-oriented languages to the common programmer has created a major evolution in the area of software development.

There is, as yet, no universally agreed upon definition of exactly what constitutes object- oriented programming. Booch suggests:

“Object-oriented programming is a method of implementation in which programs are organized as cooperative collections of objects, each of which represents an instance of some class, and whose classes are all members of a hierarchy of classes united via inheritance relationships.''

From this definition, one can infer that object-oriented programming consists of instantiating a number of objects which communicate with one another so as to achieve some desired behaviour. This paradigm is natural with how humans see the world; as a series of cause-effect relationships, where an action performed on one object has effects on the objects with which it communicates.

1.2 Object Oriented Paradigm

The major objectives of object-oriented approach are to eliminate some of the flaws encountered in the procedural approach. OOP treat data as a critical element in the program development and does not allow it to flow freely around the system. It ties data more closely to the functions that operate on it and protect it from unintentional

www.arihantinfo.com

modification by other functions. OOP allows us to decompose a problem into a number of entities called Object and then build data and function (known as methods in java) around these entities. The combination of data and methods make up an object.

The data of an object can be accessed only by the methods associated with that object. However, methods of one object can access the methods of other objects. Some of the features of object-oriented paradigm are:

Emphasis is on data rather than procedure.

Programs are divided into what are known as Objects.

Data structures are designed such that they characterized the objects.

Methods that operate on the data of an object are tied together in the data structure.

Data is hidden and cannot be accessed by external functions.

Objects may communication with each other through methods.

New data and methods can be easily added whenever necessary.

1.3 Basic concepts of Object Oriented Programming

1.3.1 Object

Objects are key to understanding object-oriented technology. You can look around you now and see many examples of real-world objects: your dog, your desk, your television set, your bicycle.

These real-world objects share two characteristics: They all have state and behavior. For example, dogs have state (name, color, breed, hungry) and behavior (barking, fetching, and wagging tail). Bicycles have state (current gear, current pedal cadence, two wheels, and number of gears) and behavior (braking, accelerating, slowing down, and changing gears).

Software objects are modeled after real-world objects in that they too have state and behavior. A software object maintains its state in one or more variables. A variable is an item of data named by an identifier. A software object implements its behavior with methods. A method is a function (subroutine) associated with an object.

Definition: An object is a software bundle of variables and related methods.

You can represent real-world objects by using software objects. You might want to represent real-world dogs as software objects in an animation program or a real-world bicycle as software object in the program that controls an electronic exercise bike. You can also use software objects to model abstract concepts. For example, an event is a common object used in GUI window systems to represent the action of a user pressing a mouse button or a key on the keyboard.

The following illustration is a common visual representation of a software object:

www.arihantinfo.com

Everything that the software object knows (state) and can do (behavior) is expressed by the

Everything that the software object knows (state) and can do (behavior) is expressed by the variables and the methods within that object. A software object that modeled your real- world bicycle would have variables that indicated the bicycle's current state: its speed is 10 mph, its pedal cadence is 90 rpm, and its current gear is the 5th gear. These variables are formally known as instance variables because they contain the state for a particular bicycle object, and in object-oriented terminology, a particular object is called an instance.

The following figure illustrates a bicycle modeled as a software object.

figure illustrates a bicycle modeled as a software object. In addition to its variables, the software

In addition to its variables, the software bicycle would also have methods to brake, change the pedal cadence, and change gears. (The bike would not have a method for changing the speed of the bicycle, as the bike's speed is just a side effect of what gear it's in, how fast the rider is pedaling, whether the brakes are on, and how steep the hill is.) These methods are formally known as instance methods because they inspect or change the state of a particular bicycle instance.

1.3.2 Classes

In the real world, you often have many objects of the same kind. For example, your bicycle is just one of many bicycles in the world. Using object-oriented terminology, we say that your bicycle object is an instance of the class of objects known as bicycles. Bicycles have some state (current gear, current cadence, two wheels) and behavior (change gears, brake) in common. However, each bicycle's state is independent of and can be different from that of other bicycles.

When building bicycles, manufacturers take advantage of the fact that bicycles share characteristics, building many bicycles from the same blueprint. It would be very inefficient to produce a new blueprint for every individual bicycle manufactured.

In object-oriented software, it's also possible to have many objects of the same kind that share characteristics: rectangles, employee records, video clips, and so on. Like the bicycle manufacturers, you can take advantage of the fact that objects of the same kind are similar and you can create a blueprint for those objects. A software blueprint for objects is called a class.

www.arihantinfo.com

Definition: A class is a blueprint, or prototype, that defines the variables and the methods common to all objects of a certain kind.

and the methods common to all objects of a certain kind. The class for our bicycle

The class for our bicycle example would declare the instance variables necessary to contain the current gear, the current cadence, and so on, for each bicycle object. The class would also declare and provide implementations for the instance methods that allow the rider to change gears, brake, and change the pedaling cadence, as shown in the next figure.

change the pedaling cadence, as shown in the next figure. After you've created the bicycle class,

After you've created the bicycle class, you can create any number of bicycle objects from the class. When you create an instance of a class, the system allocates enough memory for the object and all its instance variables. Each instance gets its own copy of all the instance variables defined in the class.

own copy of all the instance variables defined in the class. In addition to instance variables,

In addition to instance variables, classes can define class variables. A class variable contains information that is shared by all instances of the class. For example, suppose that all bicycles had the same number of gears. In this case, defining an instance variable to hold the number of gears is inefficient; each instance would have its own copy of the variable, but the value would be the same for every instance. In such situations, you can define a class variable that contains the number of gears. All instances share this variable. If one object changes the variable, it changes for all other objects of that type. A class can also declare class methods. You can invoke a class method directly from the class, whereas you must invoke instance methods on a particular instance.

www.arihantinfo.com

1.3.3 Data Abstraction and Encapsulation The wrapping up of data and methods into a single

1.3.3 Data Abstraction and Encapsulation

The wrapping up of data and methods into a single unit (called class) is known as encapsulation. Data encapsulation is the most striking feature of a class. The data is not accessible to the outside world and only those methods, which are wrapped in the class, can access it. These methods provide the interface between the object’s data and program. The insulation of data from direct access by the program is called data hiding. Encapsulation makes it possible for objects to be treated like ‘black boxes’, each performing a specific task without any concern for internal implementation.

Information “in” Data

for internal implementation. Information “in” Data and Method Information “out” Encapsulation is like a

and

Method

Information “out”

Information “in” Data and Method Information “out” Encapsulation is like a capsule: the doctor tells you

Encapsulation is like a capsule: the doctor tells you to take a medicinal capsule or pill. Far too small for you to see is the structure of the compound or molecule that does work in your bloodstream or organs to cure your disease. You don't even see the components of the mixture, which might be white medicine mixed with, say green flour. The complexity is hidden from you. Your orders are simple and external to the encapsulation: take one green pill each day with water.

Encapsulation is like a black box. When you purchase a television set, you do not need to know the details of the electronics inside (raster-scanning cathode ray tube with magnetic electron gun, alternating current transformer, hundreds of capacitors, thousands of transistors). Instead, you only need to know how to plug in the UNIT, attach the cable, turn the on switch, and press buttons on the remote control. You have a UNIT that sends visual and audio messages to you, and you do not care about the hidden actions within the unit.

Abstraction

Refers to the act of representing essential features without including the background details or explanations.

1.3.4 Inheritance

www.arihantinfo.com

Generally speaking, objects are defined in terms of classes. You know a lot about an object by knowing its class. Even if you don't know what a penny-farthing is, if I told you it was a bicycle, you would know that it had two wheels, handle bars, and pedals.

Object-oriented systems take this a step further and allow classes to be defined in terms of other classes. For example, mountain bikes, racing bikes, and tandems are all kinds of bicycles. In object-oriented terminology, mountain bikes, racing bikes, and tandems are all subclasses of the bicycle class. Similarly, the bicycle class is the superclass of mountain bikes, racing bikes, and tandems. This relationship is shown in the following figure.

tandems. This relationship is shown in the following figure. Each subclass inherits state (in the form

Each subclass inherits state (in the form of variable declarations) from the superclass. Mountain bikes, racing bikes, and tandems share some states: cadence, speed, and the like. Also, each subclass inherits methods from the superclass. Mountain bikes, racing bikes, and tandems share some behaviors: braking and changing pedaling speed, for example.

However, subclasses are not limited to the state and behaviors provided to them by their superclass. Subclasses can add variables and methods to the ones they inherit from the superclass. Tandem bicycles have two seats and two sets of handle bars; some mountain bikes have an extra set of gears with a lower gear ratio.

Subclasses can also override inherited methods and provide specialized implementations for those methods. For example, if you had a mountain bike with an extra set of gears, you would override the "change gears" method so that the rider could use those new gears.

You are not limited to just one layer of inheritance. The inheritance tree, or class hierarchy, can be as deep as needed. Methods and variables are inherited down through the levels. In general, the farther down in the hierarchy a class appears, the more specialized its behavior.

The Object class is at the top of class hierarchy, and each class is its descendant (directly or indirectly). A variable of type Object can hold a reference to any object, such as an instance of a class or an array. Object provides behaviors that are required of all objects running in the Java Virtual Machine. For example, all classes inherit Object's toString method, which returns a string representation of the object.

Inheritance offers the following benefits:

Subclasses provide specialized behaviors from the basis of common elements provided by the superclass. Through the use of inheritance, programmers can reuse the code in the superclass many times.

Programmers can implement superclasses called abstract classes that define "generic" behaviors. The abstract superclass defines and may partially implement the behavior, but much of the class is undefined and unimplemented. Other programmers fill in the details with specialized subclasses.

www.arihantinfo.com

1.3.5 Polymorphism

Polymorphism is the combination of the two Greek world, poly i.e. many and morphism i.e. forms, means the ability to take more than one form. For example, an operation may exhibit different behavior in different instance. The behavior depends upon the types of data used in the operation. For example, consider the operation of addition. For two numbers, the operation will generate a sum. If the operands are string, then the operation would produce a third string by concatenation.

www.arihantinfo.com

UNIT 2 : INTRODUCTION TO JAVA

UNIT 2 : INTRODUCTION TO JAVA

Introduction to Java 2.1Genesis of Java 2.2Why Java? 2.3History of Java

2.4Oak

2.5Java Feature

2.5.1 Simple

2.5.2 Secure

2.5.3 Portable

2.5.4 Object Oriented

2.5.5 Interpreted

2.5.6 Robust

2.5.7 Multithreaded

2.5.8 Interpreted

2.5.9 Dynamic and Distributed

2.5.10 Architecture Nature and Portable

2.6Difference between java and C++

2.7The Java Virtual Machine 2.8Java Program Structure 2.9Java Token

2.9.1 Identifiers

2.9.2 Keywords

2.9.3 Literals

2.9.4 Operators

2.9.5 Separators

2.10Comments

2.11White Space

2.12Constants

2.13Backslash Character Constant

2.1 Genesis of Java

Java is related to C++, which is a direct descendent of C. Much of the character of Java is inherited from these two languages. From C, Java derives its syntax. Many of Java's object oriented features were influenced by C++.

By the end of the 1980's and early 1990's object oriented programming using C++ took hold. It seemed that programmers had finally found the perfect language but there were forces brewing that would drive the computer language evolution forward. These forces were the World Wide Web and the Internet.

As stated earlier in these notes, in 1990 a group at SUN Microsystems developed Java. In some sense Java is what C++ might have been if it was not required to be backward compatible with C. Java was originally called Oak but that turned out to be a copyrighted name so after some brainstorming they chose the name Java. It doesn't really mean Just another Vague Acronym.

www.arihantinfo.com

The original motivation of Java was not the Internet but was the need for a platform independent language. This platform independence is exactly what is needed for Internet programming. The Internet helped push Java to the forefront of programming and Java in turn has a profound effect on the Internet.

Java has gone through two major upgrades from the original version 1.0.2 to version 1.1 and now to version 1.2 (also called Java 2). There are major changes in the language between the versions.

2.2 Why Java?

In one of their early papers about the language, Sun described Java as follows:

Java: a simple, object-oriented, distributed, interpreted, robust, secure, architecture neutral, portable, high-performance, multithreaded, and dynamic language.

Even though this is quite a string of buzzwords, they aptly describe the language.

2.3 History of Java

At first glance, it may appear that Java was developed specifically for the World Wide Web. However, interestingly enough, Java was developed independently of the web, and went through several stages of metamorphosis before reaching its current status of de facto programming language for the World Wide Web. Below is a brief history of Java since its infancy to its current state.

2.4 Oak

Bill Joy, currently a vice president at Sun Microsystems, is widely believed to have been the person to conceive of the idea of a programming language that later became Java. In late 1970's, Joy wanted to design a language that combined the best features of MESA and C. In an attempt to re-write the UNIX operating system in 1980's, Joy decided that C++ was inadequate for the job. A better tool was needed to write short and effective programs. It was this desire to invent a better programming tool that swayed Joy, in 1991, in the direction of Sun's "Stealth Project" - as named by Scott McNealy, Sun's president.

In January of 1991, Bill Joy, James Gosling, Mike Sheradin, Patrick Naughton (formerly the

project leader of Sun's OpenWindows user environment), and several other individuals met in Aspen, Colorado for the first time to discuss the ideas for the Stealth Project. The goal of the Stealth Project was to do research in the area of application of computers in the consumer electronics market. The vision of the project was to develop "smart" consumer electronic devices that could all be centrally controlled and programmed from a handheld-

remote-control-like device. According to Gosling, "the goal was

to build a system that

would let us do a large, distributed, heterogeneous network of consumer electronic devices all talking to each other." With this goal in mind, the stealth group began work.

www.arihantinfo.com

Members of the Stealth Project, which later became known as the Green Project, divided the tasks amongst themselves. Mike Sheradin was to focus on business development, Patrick Naughton was to begin work on the graphics system, and James Gosling was to identify the proper programming language for the project. Gosling, who had joined Sun in 1984, had previously developed the commercially unsuccessful NEWS windowing system as well as GOSMACS - a C language implementation of GNU EMACS. He began with C++, but soon after was convinced that C++ was inadequate for this particular project. His extensions and modifications to C++ (also know as C++ ++ --), were the first steps towards the development of an independent language that would fit the project objectives. He named the language "Oak" while staring at an oak tree outside his office window! The name "Oak" was later dismissed due to a patent search which determined that the name was copyrighted and used for another programming language. According to Gosling, "the Java development team discovered that Oak was the name of a programming language that predated Sun's language, so another name had to be chosen."

"It's surprisingly difficult to find a good name for a programming language, as the team discovered after many hours of brainstorming. Finally, inspiration struck one day during a trip to the local coffee shop" Gosling recalls. Others have speculated that the name Java came from several individuals involved in the project: James gosling, Arthur Van hoff, Andy bechtolsheim.

There were several criteria that Oak had to meet in order to satisfy the project objective given the consumer electronics target market. Given the wide array of manufacturers in the market, Oak would have to be completely platform independent, and function seamlessly regardless of the type of CPU in the device. For this reason, Oak was designed to be an interpreted language, since it would be practically impossible for a complied version to run on all available platforms. To facilitate the job of the interpreter, Oak was to be converted to an intermediate "byte-code" format, which is then passed around across the network, and executed/interpreted dynamically.

Additionally, reliability was of great concern. A consumer electronics device that would have to be "rebooted" periodically was not acceptable. Another important design objective for Oak would then have to be high reliability by allowing the least amount of programmer- introduced errors. This was the motivation for several important modifications to C++. The concepts of multiple-inheritance and operator overloading were identified as sources of potential errors, and eliminated in Oak. Furthermore, in contrast to C++, Oak included implicit garbage collection thereby providing efficient memory utilization and higher reliability. Finally, Oak attempted to eliminate all unsafe constructs used in C and C++ by only providing data structures within objects.

Another essential design criterion was security. By design, Oak-based devices were to function in a network and often exchange code and information. Inherently, security is of great concern in a networked environment, especially in an environment as network dependent as the conceived Oak-based systems. For this reason, pointers were excluded in the design of Oak. This would theoretically eliminate the possibility of malicious programs accessing arbitrary addresses in memory.

2.5 Java Feature

Simple

Secure

Portable

www.arihantinfo.com

Object Oriented

Robust

Multithreaded

Interpreted

Distributed

Architecture Neutral and Portable

2.5.1

Simple

Java was designed to be easy for the professional programmer. It is easy to learn and can be used effectively. If you are an experienced C++ programmer, moving to Java will require very little effort.

Does not use pointers. Since Java does not have structures, and strings and arrays are objects, there's no need for pointers.

Does not use goto -- instead, provide labeled Break and Continue statements, and exception handling.

Unlike C++, Java has no operator overloading, no multiple inheritance.

2.5.2 Secure

There is a concept of applets in Java, which can be downloaded without fear or virus or malicious content, because the Java programs are confined to Java execution environment and are not allowed to access other parts of the CPU.

Java programs cannot forge pointers to memory, or overflow arrays, or read memory outside of the bounds of an array or string.

Byte-code verification process, performed by interpreter on any untrusted code that it loads -- checks for stack overflows and underflows, illegal byte-codes, etc.

2.5.3 Portable

The Java programs called Applets run in the JVM (Java virtual machine) environment that is in every browser therefore the programs can run anywhere.

2.5.4 Object Oriented

Class: collection of data and methods that operate on that data

Java comes with an extensive set of classes, arranged in packages.

Most things in Java are objects. The only exceptions: the primitive number, character, and boolean types.

Strings are represented by objects, as are threads.

www.arihantinfo.com

A class is the basic unit of compilation and of execution in Java; all Java programs are

classes.

2.5.5 Interpreted

The Java compiler generates byte-codes for the Java Virtual Machine (JVM), rather than native machine code.

2.5.6 Robust

Garbage collection and Exception handling make Java a robust language. In garbage

collection the user doesn’t have to bother about the memory allocation as, when the object

is no longer in use it is automatically deleted to release memory space.

2.5.7 Multithreaded

A single threaded application has one thread of execution running at all times and such

programs can do only one task at a time. A multi-threaded application can have several

threads of execution running independently and simultaneously. These threads may communicate and cooperate and will appear to be a single program to the user.

2.5.8 Interpreted

The Java code is compiled into the byte code, which is the class file. The byte code is then interpreted to the machine language by the JVM environment.

2.5.9 Dynamic and Distributed

Any class can be loaded into a running Java interpreter at any time, then dynamically instantiated. Native code libraries can also be dynamically loaded.

Classes in Java are represented by the Class class. Information about a class is available dynamically at run-time. See Reflection

"Distributed" means lots of high-level support for networking (e.g. URL class in java.net package).

Distributed nature of Java, combined with dynamic class loading capabilities, make it possible for a Java interpreter to download and run code across the Internet.

1.5.10 Architecture Neutral and Portable

"Write once, run anywhere"

JVM = interpreter and run-time system, ported to various platforms

www.arihantinfo.com

No implementation-dependent aspects -- e.g. all primitive data types are defined in Java, have same byte size on all platforms.

2.6 Differences between Java and C++

Perhaps the single biggest difference between Java and C++ is that Java does not support pointers. After examining C++ in detail we know that the pointer is one of C++'s most powerful and important language features. It is also one of the most dangerous. Pointers don't exist in Java, as their existence would violate security aspects of the language. For example, using a pointer to gain access to memory addresses outside a program's code and data a malicious program could damage the system, perform unauthorized access etc.

In Java all object variables, arguments and return types are references. There is no need for the reference operator, &, of C++.

In Java, assigning one object to another does not invoke an assignment operator function. Instead, assigning one object to another has the effect of associating the variable with another location in memory, much like a pointer assignment.

Java has a streamlined approach to memory allocation. Like C++, it supports the new keyword (which returns a reference). However it does not have a delete. Instead, when the last reference to an object is destroyed (goes out of scope), the object itself is destroyed the next time garbage collection occurs. The garbage collector runs as a background process freeing up unused memory.

Java does not support operator overloading. This is not such a big restriction as we might think. After all, it is just as easy to say u = v.add (w) as u = v + w. This is precisely the notation used when we make the matrix class within Java.

Java does not support complex numbers and since it does not support operator overloading we can't build complex numbers ourselves as is done in C++.

Java does not include a preprocessor nor does it support preprocessor directives. The preprocessor plays a lesser role in C++ than in C and the designers of Java felt that it was time to eliminate it entirely.

Java does not support automatic type conversions that result in a loss of precision.

All the code in a Java program is encapsulated within one or more classes. Therefore Java does not have what you would normally think of as global variables or functions.

Java does not allow default arguments.

Java does not support multiple inheritance. Java does support the interface, which is similar to abstract classes in C++, and does give a form of multiple inheritance.

Java does not support templates. In Java all classes inherit from a single class called Object so that it is not difficult to write generalized classes building on the Object class as the base type.

www.arihantinfo.com

2.7 The Java Virtual Machine

MACHINE LANGUAGE CONSISTS of very simple instructions that can be executed directly by the CPU of a computer. Almost all programs, though, are written in high-level programming languages such as Java, Pascal, or C++. A program written in a high-level language cannot be run directly on any computer. First, it has to be translated into machine language. This translation can be done by a program called a compiler. A compiler takes a high-level-language program and translates it into an executable machine-language program. Once the translation is done, the machine-language program can be run any number of times, but of course it can only be run on one type of computer (since each type of computer has its own individual machine language). If the program is to run on another type of computer it has to be re-translated, using a different compiler, into the appropriate machine language.

There is an alternative to compiling a high-level language program. Instead of using a compiler, which translates the program all at once, you can use an interpreter, which translates it instruction-by-instruction, as necessary. An interpreter is a program that acts much like a CPU, with a kind of fetch-and-execute cycle. In order to execute a program, the interpreter runs in a loop in which it repeatedly reads one instruction from the program, decides what is necessary to carry out that instruction, and then performs the appropriate machine-language commands to do so.

One use of interpreters is to execute high-level language programs. For example, the programming language Lisp is usually executed by an interpreter rather than a compiler. However, interpreters have another purpose: they can let you use a machine-language program meant for one type of computer on a completely different type of computer. For example, there is a program called "Virtual PC" that runs on Macintosh computers. Virtual PC is an interpreter that executes machine-language programs written for IBM-PC-clone computers. If you run Virtual PC on your Macintosh, you can run any PC program, including programs written for Windows. (Unfortunately, a PC program will run much more slowly than it would on an actual IBM clone. The problem is that Virtual PC executes several Macintosh machine-language instructions for each PC machine-language instruction in the program it is interpreting. Compiled programs are inherently faster than interpreted programs.)

The designers of Java chose to use a combination of compilation and interpretation. Programs written in Java are compiled into machine language, but it is a machine language for a computer that doesn't really exist. This so-called "virtual" computer is known as the Java virtual machine. The machine language for the Java virtual machine is called Java bytecode. There is no reason why Java bytecode could not be used as the machine language of a real computer, rather than a virtual computer. In fact, Sun Microsystems -- the originators of Java -- have developed CPU's that run Java bytecode as their machine language.

However, one of the main selling points of Java is that it can actually be used on any computer. All that the computer needs is an interpreter for Java bytecode. Such an interpreter simulates the Java virtual machine in the same way that Virtual PC simulates a PC computer.

Of course, a different Java bytecode interpreter is needed for each type of computer, but once a computer has a Java bytecode interpreter, it can run any Java bytecode program. And the same Java bytecode program can be run on any computer that has such an

www.arihantinfo.com

interpreter. This is one of the essential features of Java: the same compiled program can be run on many different types of computers.

program can be run on many different types of computers. Why, you might wonder, use the

Why, you might wonder, use the intermediate Java bytecode at all? Why not just distribute the original Java program and let each person compile it into the machine language of whatever computer they want to run it on? There are many reasons. First of all, a compiler has to understand Java, a complex high-level language. The compiler is itself a complex program. A Java bytecode interpreter, on the other hand, is a fairly small, simple program. This makes it easy to write a bytecode interpreter for a new type of computer; once that is done, that computer can run any compiled Java program. It would be much harder to write a Java compiler for the same computer.

Furthermore, many Java programs are meant to be downloaded over a network. This leads to obvious security concerns: you don't want to download and run a program that will damage your computer or your files. The bytecode interpreter acts as a buffer between you and the program you download. You are really running the interpreter, which runs the downloaded program indirectly. The interpreter can protect you from potentially dangerous actions on the part of that program.

2.8 Java Program Structure

public class ClassName

{

www.arihantinfo.com

class body public static void main (String[] args)

{

method body

}

}

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

{

System.out.println("Hello");

}

}

Save this program in the folder say C:\javaprogram. The name of the class is the same as the name of the file. When you’re creating a stand-alone program such as this one, one of the classes in the file must have the same name as the file. (The compiler complains if you don’t do this.) That class must contain a method called main () with the signature shown:

public static void main(String[] args)

The public keyword means that the method is available to the outside world. The static keyword means that no need to create an object of this class to access the main function. The void means function is not returning anything. The main keyword is the name of the main function from where the execution will start and args are the command line arguments.

By default java import a package java.lang and in this package we have a System class, and System class has a static object out of PrintStream class. Since it’s static you don’t need to create anything. The out object is always there and provides a println( ) function, which is used to print the string on the console and end with a new line.” Thus, in any Java program you write you can say System.out.println("things") whenever you want to print something to the console.

Compiling and running

In order to compile the program open the command prompt and go to your directory and write this command.

C:\javaprogram>javac Hello.java

This command should produce no response. But it will create Hello.class file in your folder which is the bytecode of this program.

In order to run this program, write this command on the same command prompt.

C:\javaprogram>java Hello

Output will be: Hello

www.arihantinfo.com

2.9 Java Token:

A java program is a collection of tokens, comments and white spaces. Java language includes five types of tokens. They are:

Identifier

Keyword

Literal

Separator

Operator

2.9.1 Identifiers

The Java identifiers are the names given for classes, methods, variables, objects, labels, packages and interfaces in a program. Here are the rules for creating a properly formed identifier:

1. are names for classes, methods, or variables.

2. begin with a letter, underscore (_), or dollar sign ($).

Java

Identifiers

3. are case sensitive.

4. have no maximum length.

5. must not begin with digit.

Identifiers must be meaningful, short enough to be quickly and easily typed and long enough to be descriptive and easily read.

2.9.2 Keywords

The following character sequences are reserved for use as keywords and cannot be used as identifiers Keyword: one of

abstract

default

if

private

this

boolean

do

implements

protected

throw

break

double

import

public

throws

byte

else

instanceof

return

transient

case

extends

int

short

try

catch

final

interface

static

void

char

finally

long

strictfp

volatile

class

float

native

super

while

const

for

new

switch

continue

goto

package

synchronized

The keywords const and goto are reserved, even though they are not currently used. This may allow a Java compiler to produce better error messages if these C++ keywords incorrectly appear in programs.

2.9.3 Literals

www.arihantinfo.com

Literal in java are a sequence of characters (digits, letters, and other characters) that represent constant values to be stored in variables. Java language specifies five major types of literals. They are:

Integer Literal Floating-Point Literal Boolean Literal Character Literal String Literal Null Literal

2.9.4 Operators

An operator is a symbol that takes one or more arguments and operates on them to produce a result. The following 37 tokens are the operators, formed from ASCII characters:

Operator: one of

>

<=

-

>>

^=

<

!

~

?

:

= ==

>=

!=

&&

||

++

--

*

/

&

|

*=

^

%

+ <<

>>>

+=

-=

/=

&=

|=

%=

<<=

>>=

>>>=

2.9.5 Separators

Separators are symbols used to indicate where groups of code are divided and arranged. They basically define the shape and function of our code. The following ASCII characters are the separators (punctuators):

Separator: one of

(

)

Parentheses

{ }Braces

[

]

Brackets

 

;

Semicolon

,

Comma

.

Period

2.10 Comments

There are two kinds of comments

/* text */

/* to the ASCII characters */ is ignored (as in C and C++).

A traditional comment: all the text from the ASCII characters

// text

// to the end of the line is ignored (as in C++).

A end-of-line comment: all the text from the ASCII characters

2.11 White Space

White space is defined as the ASCII space, horizontal tab, and form feed characters, as well as line terminators WhiteSpace:

www.arihantinfo.com

the ASCII SP character, also known as "space" the ASCII HT character, also known as "horizontal tab" the ASCII FF character, also known as "form feed" LineTerminator

2.12

Constants

A constant is an identifier that is similar to a variable except that it holds one value for its entire existence

The compiler will issue an error if you try to change a constant

In Java, we use the final modifier to declare a constant

final int count = 100;

2.13

Backslash Character Constants

Constants

‘\b’

‘\f’

‘\n’

‘\r’

‘\t’

‘\’’

‘\”’

‘\\’

Meanings

back space form feed new line carriage return horizontal tab single quote double quote backslash

www.arihantinfo.com

UNIT 3: VARIABLES AND OPERATORS

UNIT 3: VARIABLES AND OPERATORS

3.1Variables

3.2Data Types in java 3.3Scope of Variables

3.4Array

3.4.1 One-Dimensional Array

3.4.2 Two-Dimensional Array

3.5Strings

3.6Operators

3.6.1 Arithmetic Operators

3.6.2 Assignment Operators

3.6.3 Conditional Operators

3.6.4 Special Operators

3.6.5 Relational Operators

3.6.6 Boolean Logical Operators

3.6.7 Incrementing and Decrementing Operators

3.6.8 Bitwise Operators

3.6.9 Operator Precedence

3.1 Variables

A variable is an identifier that denotes a storage location used to store a data value. A variable name can be chosen by the programmer in a meaningful way so as to reflect what it represents in the program. Variable name may consist of alphabets, digits, the underscore ( _ ) and dollar character, subject to the following conditions:

1. They must not begin with a digit.

2. Uppercase and lowercase are distinct. This means that the variable Amount is not equal to amount or AMOUNT.

3. It should not be a keyword.

4. White space is not allowed.

5. Variable name can be of any length.

www.arihantinfo.com

Data Types

Non-primitive Primitive Numeric Non-numeric classes Interface Arrays Integer Floating-point Character Boolean
Non-primitive
Primitive
Numeric
Non-numeric
classes
Interface
Arrays
Integer
Floating-point
Character
Boolean
char
boolean
byte
short
float
int
double
long

Every variable must have a data type. A variable's data type determines the values that the variable can contain, size it takes in memory and the operations that can be performed on it.

2.2 Data type in Java

The Java programming language has two categories of data types:

1. Primitive

2. Reference

A variable of primitive type contains a single value of the appropriate size and format for its type: A Number, A Character, or A boolean value. The following table lists, by keyword, all of the primitive data types supported by Java, their sizes and a brief description of each.

Primitive Data Types

Keyword

Description

Size

(integers)

www.arihantinfo.com

Byte

Byte-length integer

One byte

Short

Short integer

Two bytes

Int

Integer

Four bytes

Long

Long integer

Eight bytes

(real numbers)

Float

Single-precision floating point

Four bytes

Double

Double-precision floating point

Eight bytes

(other types)

Char

A single character

Two bytes (Unicode character)

Boolean

A Boolean value (true or false)

true or false

Purity Tip: In other languages, the format and size of primitive data types may depend on the platform on which a program is running. In contrast, the Java programming language specifies the size and format of its primitive data types. Hence, you don't have to worry about system-dependencies.

You can put a literal primitive value directly in your code. For example, if you need to assign the value 4 to an integer variable you can write this:

int anInt = 4;

The digit 4 is a literal integer value. Here are some examples of literal values of various primitive types:

Examples of Literal Values and Their Data Types

Literal

Data Type

 

178

Int

8864L

Long

37.266

Double

37.266D

Double

87.363F

Float

26.77e3

Double

'

c '

Char

 

True

Boolean

False

Boolean

Generally speaking, a series of digits with no decimal point is typed as an integer. You can specify a long integer by putting an 'L' or 'l' after the number. 'L' is preferred, as it cannot be confused with the digit '1'. A series of digits with a decimal point is of type double. You can specify a float by putting an 'f' or 'F' after the number. A literal character value is any single

www.arihantinfo.com

Unicode character between single quote marks. The two boolean literals are simply true and false.

Arrays, classes, and interfaces are reference types. The value of a reference type variable, in contrast to that of a primitive type, is a reference to (an address of) the value or set of values represented by the variable.

A reference is called a pointer or a memory address in other languages. The Java

programming language does not support the explicit use of addresses like other languages

do. You use the variable's name instead.

other languages do. You use the variable's name instead. 3.3 Scope of Variables A variable's scope

3.3 Scope of Variables

A variable's scope is the region of a program within which the variable can be referred to by its simple name. Secondarily, scope also determines when the system creates and destroys memory for the variable. Scope is distinct from visibility, which applies only to member variables and determines whether the variable can be used from outside of the class within which it is declared. Visibility is set with an access modifier.

The location of the variable declaration within your program establishes its scope and places it into one of these categories:

Instance variables

Class variables

Local variable

Instance and class variables are declared inside a class. Instance variable are created when the objects are instantiated and therefore they are associated with the objects. They take different values for each object. On the other hand, class variables are global to a class and belong to the entire set of objects that class creates. Only one memory location is created for each class variable.

Variables declared and used inside methods are called local variables. They are called so because they are not available for use outside the method definition. Local variables can also be declared inside program blocks that are defined between an opening brace { and a closing brace }.These variables are visible to the program only from the beginning of its program block to the end of the program block. When the program control leaves a block, all the variables in the block will cease to exist. The are of the program where the variable is accessible (i.e. usable) is called its scope.

3.4 Array

An array is a group of contiguous or related data items that share a common name.

Or we can say that an array stores multiple variables of

the same type.

www.arihantinfo.com

a specific number of indices ("slots").

you access an element by using its index.

3.4.1 One-Dimensional Arrays

A

list of items can be given one variable name using only one subscript and such a variable

is

called a single-subscript variable or a one-dimensional array.

Declaration of Arrays:

type arrayname [] = new type[size];

For example we want to represent a set of five numbers, say (35, 40, 20, 57, 19) by an array variable number, then we may create the variable number as follows

int number[]=new int[5];

and computer reserves five storage locations as shown below

35

40

20

57

19

 

number[0]

number[1]

number[2]

number[3]

number[4]

Note that java creates arrays starting with a subscript of 0 and ends with a value one less than the size specified. Unlike C, Java protects arrays from overruns and underruns. Trying to access an array beyond its boundaries will generate an error message.

Initialization of Arrays:

arrayname[subscript]=value;

we can also initialize array automatically in the same way as the ordinary variables when they are declared, as shown below.

type arrayname[ ] = {list of values};

Example :

int number [ ] = {35, 40, 20, 57, 19};

ArrayArray LeLengngthth

In java, all arrays store the allocated size in a variable named length. We can access the length of the array a using a.length. Example:

int aSize = a.length;

3.4.2 Two-Dimensional Arrays

www.arihantinfo.com

So far we have discussed the array variables that can store a list of values. There will be situations where a table of values will have to be stored. Consider the following data table, which shows the value of sales of three items by four salesgirls:

 

Item1

Item2

Item3

Salesgirl #1

310

275

365

Salesgirl #2

210

190

325

Salesgirl #3

405

235

240

Salesgirl #4

260

300

380

The table contains a total of 12 values, there in each line. We can think of this table as a matrix consisting of four rows and three columns. Each row represents the values of sales by a particular salesgirl and each column represents the values of sales of a particular item.

For creating two-dimensional arrays, we must follow the same steps as that of simple arrays, we may create a two-dimensional array like this:

type arrayname[][]=new type[row][col]; int myarray = new int[3][4];

like the one-dimensional array, two-dimensional array may be initialized by following their declaration with a list of initial values enclosed in braces. For example,

int table[2][3] = {2, 2, 2, 4, 4, 4};

initialize the elements of the first row to zero and the second row to one. The initialization is done row by row. The above statement can be equivalently written as

int table[ ] [ ] = { {2, 2, 2}, {4, 4, 4}};

by surrounding the elements of each row by braces.

3.5 Strings

Internally, a String is an array of characters, an array of char. The Java API, however, considers a String to be an object. Therefore, you benefit from built-in methods and property to help you handle strings.

3.6 Operators

3.6.1 Arithmetic Operators

Operator

Name

+ Addition

- Subtraction

Use

Op1 + op2

Description

Adds op1 and op2

Op1 - op2 Subtracts op2 from op1

www.arihantinfo.com

* multiplication

Op1 * op2 Multiplies op1 by op2

/ Division

Op1 / op2

Divides op1 by op2

% modulus (or mod)

Op1 % op2

Computes the remainder of dividing op1 by op2

The arithmetic operators return a number. numeric return value = <operand1> <operator> <operand2>; example: myLongString = myShortString + myOtherString;

+ addition

o

adds two numbers

o

concatenates two string objects

- subtraction

o subtract one number from another

* multiplication

o multiply two numbers

/ division

o divide two numbers

% modulus

o

the remainder of an integer division

o

5 % 3 = 2 Because 5/3 = 1 and leaves 2.

o

myRemainder = 5 % 3;

3.6.2 Assignment Operator

You use the assignment operator, =, to assign one value to another.

Compound Assignment Operator

Operator

Use

Equivalent to

+=

Op1 += op2

Op1 = op1 + op2

-=

Op1 -= op2

Op1 = op1 - op2

*=

Op1 *= op2

Op1 = op1 * op2

/=

Op1 /= op2

Op1 = op1 / op2

%=

Op1 %= op2

Op1 = op1 % op2

www.arihantinfo.com

&=

Op1 &= op2

Op1 = op1 & op2

|=

Op1 |= op2

Op1 = op1 | op2

^=

Op1 ^= op2

Op1 = op1 ^ op2

<<=

Op1 <<= op2

Op1 = op1 << op2

>>=

Op1 >>= op2

Op1 = op1 >> op2

>>>=

Op1 >>>= op2

Op1 = op1 >>> op2

3.6.3 Conditional Operator

Operator

?:

Use

Exp1 ? exp2 : exp3

3.6.43.6.4 SpeciSpecialal OperaOperatorstors

[]

Type []

[]

Type[

op1 ]

[]

op1[ op2 ]

.

op1.op2

()

op1(params)

(type)

(type) op1

new

New op1

Instanceof op1 instanceof

op2

3.6.5 Relational Operators

Description

If op1 is true, returns op2. Otherwise, returns op3. (This is the conditional operator.)

Declares an array of unknown length, which contains type elements.

Creates and array with op1 elements. Must be used with the new operator.

Accesses the element at op2 index within the array op1. Indices

begin at 0 and extend through the length of the array minus one.

Is a reference to the op2 member of op1.

Declares or calls the method named op1 with the specified parameters. The list of parameters can be an empty list. The list is comma-separated.

Casts (converts) op1 to type. An exception will be thrown if the type of op1 is incompatible with type.

Creates a new object or array. op1 is either a call to a constructor, or an array specification.

Returns true if op1 is an instance of op2

Logical operators test a condition by comparing values and return a boolean value (true or false).

== equal (two adjacent equal signs) if (sum = = 100) { // do something

www.arihantinfo.com

WARNING: Testing for identical values with = = is different from assigning a value with =

!= not equal if (sum != 100) { // do something

> greater than if (sum > 100) { // do something

< less than if (sum < 100) { // do something

>= greater than or equal to if (sum >= 100) { // do something

<= less than or equal to if (sum <= 100) { // do something

Here's two comparison operators in a sequence:

isBigSum = sum > 100; The variable isBigSum gets the value true only if the sum is greater than 100.

3.6.6 Boolean Logical Operators

& - ampersand is the logical and operator boolean isAllExpensive = (cost1 >= 100) & (cost2 >= 100); Both cost1 and cost2 must be >= 100 to return true and both cost1 and cost2 are evaluated

&& - double ampersand is the logical and operator that can "shortcircuit" when appropriate boolean isAllExpensive = (cost1 >= 100) && (cost2 >= 100); // Both cost1 and cost2 must be >= 100 to return true and if cost1 fails the test, cost2 is NOT evaluated.

| - the logical or operator is the "pipe" key boolean hasExpensive = (cost1 >= 100) | (cost2 >= 100); Either cost1 or cost2 must be >= 100 to return true and both cost1 and cost2 are evaluated

|| or - double "pipe" is the logical or operator that can "shortcircuit" when appropriate boolean isAllExpensive = (cost1 >= 100) || (cost2 >= 100); Either cost1 or cost2 must be >= 100 to return true and if cost1 passes the test, cost2 is NOT evaluated.

Note: Do not confuse the two forward slashes of comments (//) with the two "pipes" of one of the logical operators (||).

Truth table

Operand1

Operand2

==

!=

&&

||

www.arihantinfo.com

True

true

True

false

true

true

true

false

False

true

false

true

False

true

False

true

false

true

False

false

True

false

false

false

3.6.7

Incrementing and Decrementing

 

These short cut unary operators increment or decrement a number by one.

Operator

Use

Description

++

Op++

Increments op by 1; evaluates to the value of op before it was incremented

++

++op

Increments op by 1; evaluates to the value of op after it was incremented

--

Op--

Decrements op by 1; evaluates to the value of op before it was decremented

--

--op

Decrements op by 1; evaluates to the value of op after it was decremented

Note the difference between prefix versus post-fix.

3.6.8 Bitwise Operators

Bitwise operators are used for testing the bits, or shifting them to right or left. Bitwise operators may not be applied to float or double.

Operator

Meaning

&

bitwise AND

!

bitwise OR

^

bitwise exclusive OR

~

one’s complement

<<

shift left

>>

shift right

>>>

shift right with zero fill

3.7 Operator Precedence

Mnemonic

Operator type

Operators

 

Ulcer

Unary

+

- ++--

Addicts

Arithmetic

(and

* / % + -

<< >>

shift)

Really

Relational

>

< >= <= == !=

Like

Logical (and bitwise)

&& ||

&

|

^

C

Conditional (ternary)

A

> B ? X : Y

 

www.arihantinfo.com

A Lot

Assignment

= (and compound assignment like *=)

www.arihantinfo.com

UNIT 4: CONTROL STATEMENTS

UNIT 4: CONTROL STATEMENTS

4.1Selection Statements

4.1.1 If

4.1.2 If

Else

4.1.3 if

If

Else

else

4.2The Switch Statement

4.3Iteration Statement

4.3.1 The while Statement

4.3.2 The do Statement

4.3.3 The for Statement

4.4The Comma Operator 4.5The break Statement

4.6The continue Statement 4.7Selection Statements

4.7.1 If

4.7.2 If

Else

4.7.3 if

If

Else

else

4.8The Switch Statement

4.9Iteration Statement

4.9.1 The while Statement

4.9.2 The do Statement

4.9.3 The for Statement

4.10The Comma Operator 4.11The break Statement 4.12The continue Statement

4.1 Selection Statements

A conditional statement lets us choose which statement will be executed next

Therefore they are sometimes called selection statements

Conditional statements give us the power to make basic decisions

Java's conditional statements are the if statement, the if-else statement, and the switch statement

4.1.1 if

if( boolean expression ) {

statement1;

statementn;

}

www.arihantinfo.com

Note: Curly braces only required if there is more than one execution statement.

4.1.2 If else

if(x==y){ // do this

}

else { // do this

}

Note: The "else" is for the last statement.

4.1.3 If

else

if

if( x == y ) { // do this

else

}

else if( x > y ) {

// nested 'if'

// do this // Note: any number of "else if" clauses after "if" and before "else"

}

else { // do this

}

Note: The "else" is for the last statement.

} Note: The "else" is for the last statement. The output is: x not > or

The output is:

x not > or = to y

4.2 The switch Statement

The switch statement provides another means to decide which statement to execute next

The switch statement evaluates an expression, then attempts to match the result to one of several possible cases

Each case contains a value and a list of statements

www.arihantinfo.com

The flow of control transfers to statement list associated with the first value that matches

The general syntax of a switch statement is:

switch ( expression )

{

 

case value1 :

statement-list1; break; case value2 :

statement-list2; break; case value3 :

statement-list3; break; default :

statement-list4; break;

}

Often a break statement is used as the last statement in each case's statement list

A break statement causes control to transfer to the end of the switch statement

If a break statement is not used, the flow of control will continue into the next case

A switch statement can have an optional default case

If the default case is present, control will transfer to it if no other case value matches

The test variable or expression to be tested can be of the primitive types byte, char, short, or int

Example :

For example, the program:

class Toomany { static void howMany(int k) { switch (k) { case 1:

case 2:

case 3:

}

System.out.print("one "); System.out.print("too "); System.out.println("many");

}

public static void main(String[] args) {

howMany(3);

howMany(2);

howMany(1);

}

}

contains a switch block in which the code for each case falls through into the code for the next case. As a result, the program prints:

many

too many

www.arihantinfo.com

one too many If code is not to fall through case to case in this manner, then break statements should be used, as in this example:

class Twomany { static void howMany(int k) { switch (k) {

case 1:

System.out.println("one");

break;

// exit the switch

case 2:

System.out.println("two");

break;

// exit the switch

case 3:

System.out.println("many");

break;

// not needed, but good style

}

}

public static void main(String[] args) {

howMany(1);

howMany(2);

howMany(3);

}

}

This program prints:

one

two

many

4.3 Iteration Statements

Java has three kinds of repetition statements: the while loop, the do loop, and the for loop

4.3.1 The while Statement

The while statement executes an Expression and a Statement repeatedly until the value of the Expression is false. While Statement:

while (Expression) Statement

The Expression must have type boolean, or a compile-time error occurs. The while is an entry-controlled loop statement. Therefore, the body of a while loop will execute zero or more times

public class WhileTest

{

public static void main(String[] args) { int r = 0; while(r < 3)

{

System.out.println(r);

}

}

}

www.arihantinfo.com

The output will be

0

1

2

4.3.2

The do Statement

The do statement executes a Statement and an Expression repeatedly until the value of the Expression is false.

do

{

statement;

}

while ( condition )

The statement is executed once initially, and then the condition is evaluated The statement is repetitively executed until the condition becomes false

A do loop is similar to a while loop, except that the condition is evaluated after the body of the loop is executed

Therefore the body of a do loop will execute at least one time

The do while is an exit control loop statement.

4.3.3

The for Statement

The for statement executes some initialization code, then executes an Expression, a Statement, and some update code repeatedly until the value of the Expression is false.

for ( initialization ; condition ; increment ) statement;

The increment portion is executed at the end of each iteration

ExamplExample:e:

public class ListCharacters { public static void main(String[] args) { for( char c = 0; c < 128; c++) if (c != 26 ) // ANSI Clear screen System.out.println("value: " + (int)c + " character: " + c);

}

}

www.arihantinfo.com

4.4

The comma operator

Comma operator is used to separate definitions and function arguments public class CommaOperator { public static void main(String[] args) { for(int i = 1, j = i + 10; i < 5;i++, j = i * 2) { System.out.println("i= " + i + " j= " + j); }}}

4.5 The break Statement

The Java break statement causes the Java interpreter to transfer the flow of execution to the end of an enclosing statement. In other words, it is used to break out of a do, for, switch, or while statement.

The syntax of the Java break statement is:

break;

Example:

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

{

if (myArray[i] == null;

{

break; // break out of for loop

}

} // execution resumes at following statement on break

4.6 The continue statement

A Java continue statement is used to terminate the current iteration of a loop and continue with the next iteration. A continue statement can only be used within a do, for, or while loop.

The syntax of the Java continue statement is:

continue;

Example:

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

{

if (myArray[i] == null;

{

continue; // skips remainder of loop and begins next iteration

}

myMethod (myArray[i]); // do something with a non-null myArray[i]

}

www.arihantinfo.com

The different types of looping statements vary in how the continue statement begins a new iteration.

do loop: On encountering a continue statement, the Java interpreter jumps to the bottom of the do loop. Then, it evaluates the test condition to determine whether to begin a new iteration.

for loop: On encountering a continue statement, the Java interpreter begins at the top of the loop in the for statement. First, it evaluates the update expression, e.g. i++. Then, it evaluates the test expression, e.g. i < myArray.length. The important thing is that the update expression is evaluated.

while loop: On encountering a continue statement, the Java interpreter begins at the top of the loop in the while statement. Then, it evaluates the test condition to determine whether to begin a new iteration.

www.arihantinfo.com

UNIT 5: CLASSES AND OBJECTS

UNIT 5: CLASSES AND OBJECTS

5.1Classes

5.1.1 The class Declaration

5.1.2 Declaring a class’s Superclass

5.1.3 Listing the interface implemented by a class

5.1.4 Summary of a class Declaration

5.2Declaring Member Variables 5.3Declaring Constants

5.4The Method Declaration 5.5Object Creation and Constructors

5.5.1 Object Creation

5.5.2 Constructor

5.6Controlling access to member of a class

5.6.1 Private

5.6.2 Protected

5.6.3 Public

5.7Subclasses and Inheritance

5.7.1 Definition

5.7.2 Creating Subclasses

5.8Overriding Methods

5.9Final classes and Methods

5.9.1 Final Classes

5.9.2 Final Methods

5.10 Abstract classes and Methods

5.10.1 Abstract classes

5.10.2 Abstract Methods

5.1 Classes

A class is a blueprint or prototype that you can use to create many objects.

classDeclaration { memberVariableDeclarations methodDeclarations

}

At minimum, a class declaration must contain the class keyword and the name of the class that you are defining:

class NameOfClass { .

}

.

.

www.arihantinfo.com

5.1.2

Declaring a Class's Superclass

In Java, every class has a superclass. If you do not specify a superclass for your class, it is assumed to be the Object class (declared in java.lang).

class NameOfClass extends SuperClassName {

}

.

A subclass inherits variables and methods from its superclass.

5.1.3 Listing the Interfaces Implemented by a Class

An interface declares a set of methods and constants without specifying the implementation for any of the methods. When a class claims to

implement an interface, it's claiming to provide implementations for all of the methods declared in the interface.

class ImaginaryNumber extends Number implements Arithmetic {

}

.

5.1.4 Summary of a Class Declaration

[ modifiers ] class ClassName [ extends SuperClassName ] [ implements InterfaceNames ] { .

.

.

}

modifiers declare whether the class is public, abstract, or final

ClassName sets the name of the class you are declaring

SuperClassName is the name of ClassName's superclass

InterfaceNames is a comma-delimited list of the interfaces implemented

5.2 Declaring Member Variables

class IntegerClass { int anInteger; // define methods here

.}

In short, a member variable declaration looks like this:

[accessSpecifier] [static] [final] type variableName

accessSpecifier defines which other classes have access to the variable. You control access to methods using the same specifiers, so Controlling Access to Members of a Class covers how you can control access to both member variables and methods.

static indicates that the variable is a class member variable as opposed to an instance member variable. You also use static to declare class methods. Instance and Class Members talks about declaring instance and class variables and writing instance and class methods.

www.arihantinfo.com

5.3

Declaring Constants class Avo { final double AVOGADRO = 6.023e23;

}

5.4 The Method Declaration

returnType methodName() {

}

Passing Information into a Method

The Method Body .

.

.

boolean isEmpty() { if (topelement == STACK_EMPTY) return true; else return false;

}

5.5 Object Creation and Constructor

5.5.1 Object Creation

Although most of the design work in object-oriented programming is creating classes, you don't really benefit from that work until you create instances (objects) of those classes. To use a class in a program, you must first create an instance of it.

5.5.2 Constructor

Before getting into the details of how to create an object, there is an important method you need to know about: the constructor. When you create an object, you typically want to initialize its member variables. The constructor is a special method you can implement in all your classes; it allows you to initialize variables and perform any other operations when an object is created from the class. The constructor is always given the same name as the class.

The following Listing contains the complete source code for the Alien class, which contains two constructors.

Listing . The Alien class.

class Alien extends Enemy { protected Color color;

protected int

energy;

protected int

aggression;

public Alien() { color = Color.green; energy = 100; aggression = 15;

}

www.arihantinfo.com

public Alien(Color c, int e, int a) { color = c; energy = e; aggression = a;

}

public void move() { // move the alien

}

public void move(int x, int y) { // move the alien to the position x,y

}

public void morph() { if (aggression < 10) { // morph into a smaller size

}

else if (aggression < 20) { // morph into a medium size

}

else { // morph into a giant size

}

}

}

The Alien class uses method overloading to provide two different constructors. The first constructor takes no parameters and initializes the member variables to default values. The second constructor takes the color, energy, and aggression of the alien and initializes the member variables with them. As well as containing the new constructors, this version of Alien uses access modifiers to explicitly assign access levels to each member variable and method. This is a good habit to get into.

5.6 Controlling Access to Members of a Class

Specifier

-----------------------------------------------------

class

subclass

package

world

private

X

protected

X

X*

X

public

X

X

X

X

package

X

X

5.6.1 Private

The most restrictive access level is private. A private member is accessible only to the class in which it is defined.

www.arihantinfo.com

class Alpha { private int iamprivate; private void privateMethod() { System.out.println("privateMethod");

}

}

class Beta {

void accessMethod() { Alpha a = new Alpha();

a.iamprivate = 10;

// illegal

a.privateMethod();

// illegal

}}

5.6.2 Protected

It allows the class itself, subclasses, and all classes in the same package to access the members.

package Greek; class Alpha { protected int iamprotected; protected void protectedMethod() { System.out.println("protectedMethod");

}

}

package Greek; class Gamma { void accessMethod() { Alpha a = new Alpha(); a.iamprotected = 10;

// legal

a.protectedMethod();

// legal

}

}

package Latin; class Delta extends Alpha { void accessMethod(Alpha a, Delta d) { a.iamprotected = 10; a.protectedMethod();

// illegal

d.iamprotected = 10; d.protectedMethod();

// legal

}

}

5.6.3 Public

Any class, in any package, has access to a class's public members.

package Greek;

class Alpha { public int iampublic; public void publicMethod() { System.out.println("publicMethod");

www.arihantinfo.com

}

}

import Greek.*;

package Roman;

class Beta {

void accessMethod() { Alpha a = new Alpha();

a.iampublic = 10;

// legal

a.publicMethod();

// legal

}

}

5.7 Subclasses and Inheritance

The derived class is called a subclass. The class from which its derived is called the superclass.

The class from which its derived is called the superclass. In Java all classes must be

In Java all classes must be derived from some class. The top-most class, the class from which all other classes are derived, is the Object class defined in java.lang:

www.arihantinfo.com

5.7.1 Definition: A subclass is a class that derives from another class. It subclass inherits

5.7.1 Definition:

A subclass is a class that derives from another class. It subclass inherits state and behavior in the form of variables and methods from all of its ancestors. It can just use the items inherited from its superclass as is, or the subclass can modify or override it. So, as you drop down in the hierarchy, the classes become more and more specialized.

5.7.2 Creating Subclasses

To declare a subclass you would write:

class SubClass extends SuperClass {

}

Note:- A Java class can have only one direct superclass. Java does not support multiple inheritance.

Member variables defined in the subclass hide member variables of the same name in the superclass. Consider this superclass and subclass pair:

class Super {

void addNum(int x,int y) { int sum;

+ y; System.out.println(“Sum of Number = “+sum);

sum=x

}

void display() { System.out.println(“I am from SuperClass”);

}

}

class Sub extends Super { public static void main(String args[]) {

www.arihantinfo.com

Sub s1 = new Sub();

s1.display();

s1.addNum(10,20);

}}

Output is :

I am from SuperClass Sum of Number = 30

5.8Overriding Methods

The following example shows method overriding. When an object’s method is called, java looks for the method definition in the object’s class. If it can not find, then it checks one level up in the hierarchy of classes. Consider the case when the same method name is used in both the superclass and superclass with the same signature (same number of arguments with the same type). Here when the method is called, method defined in the subclass is invoked. The method defined in the super class is overridden. It is now hidden for the objects of the subclass. If the method defined in the super class has to be used, then the super keyword can be used along with the name of the method. In the example below, the method display() and this.display() will invoke method display() of the subclass. The call super.display() will invoke the method display() of the super class. This program uses the super class coded earlier as the program Super.java

class OverRide extends Super { void access() { System.out.println(“Displays from a different palce”); //display method of subclass display(); //display method of superclass super.display(); //display method of subclass this.display();

}

void display()

{

System.out.println(“I am from SubClass”);

}

public static void main(String args[]) {

OverRide s1= new OverRide();

s1.access();

}

}

5.9 Final Classes and Methods

5.9.1 Final Classes

You can declare that your class is final; that is, that your class cannot be subclassed. There are (at least) two reasons why you might want to do this: security reasons and design reasons.

www.arihantinfo.com

5.9.2

Final Methods

You can use the final keyword in a method declaration to indicate to the compiler that the method cannot be overridden by subclasses.

5.10 Abstract Classes and Methods

5.10.1 Abstract Classes

Classes, which implement abstract concepts and should not be instantiated, are called abstract classes. An abstract class is a class that can only be subclassed--it cannot be instantiated.

5.10.2 Abstract Methods

An abstract class may contain abstract methods, that is, methods with no implementation. In this way, an abstract class can define a complete programming interface thereby providing its subclasses with the method declarations for all of the methods necessary to implement that programming interface.

Example:

//use of abstract class and method abstract class AbstractClass { public void printHello() {

System.out.println(“Printing from abstract class”);

}

abstract void printMe();

}

class TestAbstract extends AbstractClass {

public void printMe() { System.out.println(“Implementing abstract method”);

}

public static void main(String args[]) {

TestAbstract p =new TestAbstract(); p.printHello(); p.printMe();

}

}

p =new TestAbstract(); p.printHello(); p.printMe(); } } Architectural advantage Abstract classes provide a way to

Architectural advantage

Abstract classes provide a way to represent objects at a conceptual generic level.

In a graphic library, you can create an abstract class to represent a generic graphic object and a method for drawing it. This method is then only implemented on the derived classes.

www.arihantinfo.com

www.arihantinfo.com

www.arihantinfo.com

UNIT 6: PACKAGES AND INTERFACES

UNIT 6: PACKAGES AND INTERFACES

6.1Packages

6.1.1

How to create your own packages

6.2Classpath

6.3The meaning of static

6.4Cleanup: Finalization and Garbage collection 6.5Forcing Finalization and Garbage collection

6.6Interfaces

6.6.1

What is an interface

6.6.2

The interface Declaration

6.6.3

Multiple Extension (Inheritance)

6.6.4

Implementing an interface

6.6.5

Using an interface as a type

6.6.6

Interfaces verses abstract classes

6.1 Packages:

A package is a collection of classes and interfaces of similar nature. For example java.io

package contains classes and interfaces for various kinds of input and output. Package

defines a boundary to see how classes and interfaces interact with one another. Therefore it also acts as a mode of protection. Java language programs automatically import all classes

in the java.lang package. Packages gives us the following advantages :

Advantages:

It makes classes easier to find and use.

It avoids naming conflicts.

To import classes from a package, import command is used.

Import java.io.*; Import pack.subpack.MyClass;

In the first case all public classes in the package java.io are available. In the second case only class having the name pack.subpack.MyClass is available for use.

6.1.1 How to Create Your Own Packages

The first statement in a java program should be a package statement.

package pack.subpack;

Example :

package graphics; interface Draggable {

class Circle { class Rectangle {

}

}

}

The .class files generated must be placed in a directory named graphics somewhere in your CLASSPATH.

www.arihantinfo.com

6.2

CLASSPATH

A list of directories that indicate where on the file system you've installed

various compiled Java classes and interfaces.

Java searches your CLASSPATH for a directory whose name matches the package name of which the class is a member.

Note: If you don't specify a package, your classes and interfaces become members of the default package, which has no name.

6.3 The meaning of static

With the this keyword in mind, you can more fully understand what it means to make a method static. It means that there is no this for that particular method. You cannot call non-static methods from inside static methods 1 (although the reverse is possible), and you can call a static method for the class itself, without any object. In fact, that’s primarily what a static method is for. It’s as if you’re creating the equivalent of a global function (from C). Except global functions are not permitted in Java, and putting the static method inside a class allows it access to other static methods and to static fields.

Some people argue that static methods are not object-oriented since they do have the semantics of a global function; with a static method you don’t send a message to an object, since there’s no this. This is probably a fair argument, and if you find yourself using a lot of static methods you should probably rethink your strategy. However, statics are pragmatic and there are times when you genuinely need them, so whether or not they are “proper OOP” should be left to the theoreticians. Indeed, even Smalltalk has the equivalent in its “class methods.”

6.4 Cleanup: Finalization and Garbage collection

Programmers know about the importance of initialization, but often forget the importance of

cleanup. After all, who needs to clean up an int? But with libraries, simply “letting go” of an object once you’re done with it is not always safe. Of course, Java has the garbage collector

to reclaim the memory of objects that are no longer used. Now consider a very unusual case.

Suppose your object allocates “special” memory without using new. The garbage collector

knows only how to release memory allocated with new, so it won’t know how to release the object’s “special” memory. To handle this case, Java provides a method called finalize( ) that you can define for your class. Here’s how it’s supposed to work. When the garbage collector

is ready to release the storage used for your object, it will first call finalize( ), and only on the

next garbage-collection pass will it reclaim the object’s memory. So if you choose to use finalize( ), it gives you the ability to perform some important cleanup at the time of garbage collection.

1

The one case in which this is possible occurs if you pass a reference to an object into the static method. Then, via the reference (which is now effectively this), you can call non- static methods and access non-static fields. But typically if you want to do something like this you’ll just make an ordinary, non-static method.

www.arihantinfo.com

This is a potential programming pitfall because some programmers, especially C++ programmers, might initially mistake finalize( ) for the destructor in C++, which is a function that is always called when an object is destroyed. But it is important to distinguish between C++ and Java here, because in C++ objects always get destroyed (in a bug-free program), whereas in Java objects do not always get garbage-collected. Or, put another way:

Garbage collection is not destruction.

If you remember this, you will stay out of trouble. What it means is that if there is some

activity that must be performed before you no longer need an object, you must perform that

activity yourself. Java has no destructor or similar concept, so you must create an ordinary method to perform this cleanup. For example, suppose in the process of creating your object

it draws itself on the screen. If you don’t explicitly erase its image from the screen, it might

never get cleaned up. If you put some kind of erasing functionality inside finalize( ), then if an object is garbage-collected, the image will first be removed from the screen, but if it isn’t, the image will remain. So a second point to remember is:

Your objects might not get garbage-collected.

You might find that the storage for an object never gets released because your program never nears the point of running out of storage. If your program completes and the garbage collector never gets around to releasing the storage for any of your objects, that storage will be returned to the operating system en masse as the program exits. This is a good thing, because garbage collection has some overhead, and if you never do it you never incur that expense.

What is finalize( ) for?

You might believe at this point that you should not use finalize( ) as a general-purpose cleanup method. What good is it?

A third point to remember is:

Garbage collection is only about memory.

That is, the sole reason for the existence of the garbage collector is to recover memory that your program is no longer using. So any activity that is associated with garbage collection, most notably your finalize( ) method, must also be only about memory and its deallocation. Does this mean that if your object contains other objects finalize( ) should explicitly release those objects? Well, no—the garbage collector takes care of the release of all object memory regardless of how the object is created. It turns out that the need for finalize( ) is limited to special cases, in which your object can allocate some storage in some way other than creating an object. But, you might observe, everything in Java is an object so how can this be?

It would seem that finalize( ) is in place because of the possibility that you’ll do something C-

like by allocating memory using a mechanism other than the normal one in Java. This can happen primarily through native methods, which are a way to call non-Java code from Java. (Native methods are discussed in Appendix B.) C and C++ are the only languages currently supported by native methods, but since they can call subprograms in other languages, you can effectively call anything. Inside the non-Java code, C’s malloc( ) family of functions might be called to allocate storage, and unless you call free( ) that storage will not be released, causing a memory leak. Of course, free( ) is a C and C++ function, so you’d need to call it in a native method inside your finalize( ).

www.arihantinfo.com

After reading this, you probably get the idea that you won’t use finalize( ) much. You’re correct; it is not the appropriate place for normal cleanup to occur. So where should normal cleanup be performed?

6.5 Forcing Finalization and Garbage Collection

System.runFinalization(): This method calls the finalize() methods on all objects that are waiting to be garbage collected.

System.gc(): It asks the garbage collector to run at any time by calling System's gc() method.

//: c04:Garbage.java

// Demonstration of the garbage

// collector and finalization

class Chair {

static boolean gcrun = false;

static boolean f = false;

static int created = 0;

static int finalized = 0;

int i;

chair() {

i = ++created;

if(created == 47)

System.out.println("Created 47"); }

public void finalize() {

if(!gcrun) {

// The first time finalize() is called:

gcrun = true;

System.out.println(

"Beginning to finalize after " +

created + " Chairs have been created");

}

if(i == 47) {

www.arihantinfo.com

System.out.println(

"Finalizing Chair #47, " +

"Setting flag to stop Chair creation");

f = true;

}

finalized++;

if(finalized >= created)

System.out.println(

"All " + finalized + " finalized");

}

}

public class Garbage {

public static void main(String[] args) {

// As long as the flag hasn't been set,

// make Chairs and Strings:

while(!Chair.f) {

new Chair();

new String("To take up space");

}

System.out.println(

"After all Chairs have been created:\n" +

"total created = " + Chair.created +

", total finalized = " + Chair.finalized);

// Optional arguments force garbage

// collection & finalization:

if(args.length > 0) {

if(args[0].equals("gc") ||

args[0].equals("all")) {

System.out.println("gc():");

www.arihantinfo.com

System.gc();

}

if(args[0].equals("finalize") ||

args[0].equals("all")) {

System.out.println("runFinalization():");

System.runFinalization();

}

}

System.out.println("bye!");

}

} ///:~

The above program creates many Chair objects, and at some point after the garbage collector begins running, the program stops creating Chairs. Since the garbage collector can run at any time, you don’t know exactly when it will start up, so there’s a flag called gcrun to indicate whether the garbage collector has started running yet. A second flag f is a way for Chair to tell the main( ) loop that it should stop making objects. Both of these flags are set within finalize( ), which is called during garbage collection.

Two other static variables, created and finalized, keep track of the number of Chairs created versus the number that get finalized by the garbage collector. Finally, each Chair has its own (non-static) int i so it can keep track of what number it is. When Chair number 47 is finalized, the flag is set to true to bring the process of Chair creation to a stop.

All this happens in main( ), in the loop while(!Chair.f) { new Chair(); new String("To take up space");

}

You might wonder how this loop could ever finish, since there’s nothing inside the loop that changes the value of Chair.f. However, the finalize( ) process will, eventually, when it finalizes number 47. The creation of a String object during each iteration is simply extra storage being allocated to encourage the garbage collector to kick in, which it will do when it starts to get nervous about the amount of memory available.

When you run the program, you provide a command-line argument of “gc,” “finalize,” or “all.” The “gc” argument will call the System.gc( ) method (to force execution of the garbage collector). Using the “finalize” argument calls System.runFinalization( ) which—in theory— will cause any unfinalized objects to be finalized. And “all” causes both methods to be called.

www.arihantinfo.com

The behavior of this program and the version in the first edition of this book shows that the whole issue of garbage collection and finalization has been evolving, with much of the evolution happening behind closed doors. In fact, by the time you read this, the behavior of the program may have changed once again.

If System.gc( ) is called, then finalization happens to all the objects. This was not necessarily the case with previous implementations of the JDK, although the documentation claimed otherwise. In addition, you’ll see that it doesn’t seem to make any difference whether System.runFinalization( ) is called.

However, you will see that only if System.gc( ) is called after all the objects are created and discarded will all the finalizers be called. If you do not call System.gc( ), then only some of the objects will be finalized. In Java 1.1, a method System.runFinalizersOnExit( ) was introduced that caused programs to run all the finalizers as they exited, but the design turned out to be buggy and the method was deprecated. This is yet another clue that the Java designers were thrashing about trying to solve the garbage collection and finalization problem. We can only hope that things have been worked out in Java 2.

</#></#TIJ3_CHAPTER4_I66>

The preceding program shows that the promise that finalizers will always be run holds true, but only if you explicitly force it to happen yourself. If you don’t cause System.gc( ) to be called, you’ll get an output like this:

Created 47 Beginning to finalize after 3486 Chairs have been created Finalizing Chair #47, Setting flag to stop Chair creation After all Chairs have been created:

total created = 3881, total finalized = 2684 bye!

Thus, not all finalizers get called by the time the program completes. If System.gc( ) is called, it will finalize and destroy all the objects that are no longer in use up to that point. Remember that neither garbage collection nor finalization is guaranteed. If the Java Virtual Machine (JVM) isn’t close to running out of memory, then it will (wisely) not waste time recovering memory through garbage collection.

6.6 Interfaces

6.6.1 What is an Interface?

It is a promise that your class will implement certain methods with certain signatures. In other words an interface is a collection of method definitions (without implementations) and constant values. You even use the keyword implements to indicate that your class will keep these promises.

Advantages:

Capturing

similarities

relationship.

between

unrelated

classes

without

forcing

a

class

Declaring methods that one or more classes are expected to implement.

www.arihantinfo.com

Revealing an object's programming interface without revealing its class (objects such as these are called anonymous objects and can be useful when shipping a package of classes to other developers)

Defining an Interface

The interface declaration and the interface body;

interfaceDeclaration { interfaceBody

}

6.6.2 The interface Declaration:

[public] interface InterfaceName [extends listOfSuperInterfaces]

{

.

.

.

}

interface Collection { int MAXIMUM = 500; void add(Object obj); void delete(Object obj); Object find(Object obj); int currentCount();

}

6.6.3

Multiple Extensions (Inheritanc e )

An interface can extend multiple interfaces (while a class can only extend one), and an interface cannot extend classes.

6.6.4 Implementing an Interface