Java
Java
Java
OBJECTIVES
U
1 1 1 1 1
Define the Java technology Describe the processes java technology uses that make it cross-platform and how this makes it different from the other programming languages List two essential components of java technology List the software needed to write the java program List the reasons that make java technology Superior to other programming languages
1.0 INTRODUCTION
Software industry is witnessing change. Change is the most critical aspect of software development and management. New tools and approaches are announced very frequently. Important issues addressed by software engineers are maintainability, reusability, portability security, and integrity and user friendliness. Java technology is yet another answer in this direction.
Java Technology is a Programming language, development environment, application environment, and deployment environment The syntax of Java programming language is similar to C++ syntax. Java can be used to create all kinds of applications that can be created using any conventional programming language. Java is usually mentioned in the context of World Wide Web (WWW) browsers that are capable of running programs called applets. Applets are programs written in Java that reside on WWW servers. Applets are usually small in size to minimize download and are invoked by a HTML web page. Java applications are standalone programs that do not require a web browser to execute. As a deployment environment, Java technology provides the programmer with a large suite of tools a compiler, an interpreter, a document generator, a class file packaging tool and so on.
Provides an easy to use language by avoiding pitfalls of other languages and enables users to create clear and streamlined code. Provides an interpreted environment for improved speed of development and code portability Provides a way for programs to run more than one thread of activity. Furnishes better security
1 1 1
Applets are different form the applications and are not self-contained programs. They are like application fragments and are typically small programs. Applets find uses that includes displaying graphics, animated text, Loading URLs and doing calculations. Applets runs within a browser. Applets have built in feature for internet such as security. For example, they are Inspected for viruses.
Stealth Project (as named by Scott McNealy) brainstorming meeting in Aspen with Bill Joy, Andy Bechtolsheim, Wayne Rosing, Mike Sheridan, James Gosling and Patrick Naughton. Gosling starts working on the Oak interpreter, which, several years later (following a trademark search), is renamed Java.
4
1993
l
The development team, now incorporated as FirstPerson, focuses on interactive television after learning about Time Warners RFP for its interactive cable TV trial in Orlando, FL. NCSA Mosaic 1.0, the first graphical browser for the Internet, is released.
1994
l
Liveoak project started. Designed by Bill Joy to use Oak for a big small operating system project. Jonathon Payne and Naughton start writing WebRunner, a Mosaic-like browser later renamed HotJava Van Hoff implements Java compiler in Java. (Gosling had previously implemented it in C.)
1995
l l l
Sun formally announces Java and HotJava at SunWorld 95. Netscape announces its intention to license Java for use in Netscape browser. Sun and Netscape announce Javascript, a scripting language based on the Java language which is designed to be accessible to non-programmers. Table 1.1 Major milestones
l l l l
Simple
Most programmers working these days use C, and most programmers doing object-oriented programming use C++. Java is designed as closely to C++ as possible in order to make the system more comprehensible. Java omits many rarely used, poorly understood, confusing features of C++ .
Object-Oriented
Like C++, Java is an object-oriented language. Object-oriented languages allow the programmer to organize a program, so that it closely models the real world in structure and in the interactions among its components.
Distributed
Java was built with the Internet and Web in mind. As do most other languages, Java includes pre-built components or libraries that provide important additional capabilities beyond the language itself. However, Javas standard libraries specifically include network-aware units that greatly facilitate writing Internet applications.
Interpreted
Javas executable files are composed of bytecodes that are instructions and data relating to a hypothetical computer called the Java virtual machine. Each machine that runs a Java program uses a small program, known as the Java run-time system, to execute the Java bytecodes in your program. This design is what makes it possible to run the same program on a Macintosh, a Sun, and a PC.
Robust
Java contains features that make the task of writing robust software easier. In Java programs, exceptions can be detected and handled according to instructions written by the programmer, often allowing software to keep working in the face of unexpected problems.
Secure
One of the potential errors of the Internet is the possibility of security breaches viruses that infect your computer, or hackers who take advantage of a software glitch to invade your personal cyberspace and make off with confidential information.
Applets, which are Java programs automatically downloaded when a Web page is displayed, are subject to a number of limitations that are designed to reduce the chance that simply viewing someones page might result in harm to your system or data. No such system is absolutely reliable and none will ever be; but Java represents the state-of-the-art in reducing the chances of a disaster.
Architecture Neutral
Javas bytecodes are designed to be read and interpretedin exactly the same manneron any computer hardware or operating system that supports a Java run-time. No translation or conversion is necessary.
Portable
Java programs contain no implementation-dependent aspects, so the result of executing a series of Java bytecodes should always be the same no matter on what system they are executed. Moreover, the Java run-time system itself, though it is written in C, is written in a way that simplifies porting the Java runtime to a new computer system.
High Performance
A typical problem with interpreted languages is that they are somewhat less efficient than compiled languages. A program written by use of an interpreted language may run 20 to 100 times slower than the same program written by use of a compiled language. Java aims at overcoming this problem through the use of a technique known as just-in-time compilation. A just-in-time compiler is an interpreter that remembers the machine code sequences it executes corresponding to the input bytecodes. Having figured out the proper machine code sequence once, it doesnt have to figure it out again if the same code is executed. Instead, it retrieves the memorized sequences and executes them straight away. Studies have suggested that just-in-time compilation may make interpretation of Java bytecodes almost as efficient as native execution of machine-language code. Developing multithreaded applications in C or C++ can be agony, because these languages lack standard support for operations necessary to create and control threads. Java includes support for multithreaded applications as part of its basic library.
Dynamic
Javas program units, classes, are loaded dynamically (when needed) by the Java run-time system. Loaded classes are then dynamically linked with existing classes to form an integrated unit. The lengthy link-and-load step required by third-generation programming languages is eliminated.
Java does not have a preprocessor, and as such, does not have macros like #define. Constants can be created by using the final modifier when declaring class and instance variables. Java does not have template classes as in C++. Java does not include Cs const keyword or the ability to pass by const reference explicitly. Java classes are singly inherited, with some multiple-inheritance features provided through interfaces. All functions must be methods. There are no functions that are not tied to classes. The goto keyword does not exist in Java (its a reserved word, but currently unimplemented). You can, however, use labeled breaks and continues to break out of and continue executing complex switch or loop constructs. Java does not use pointers Java doesnt contain the data types: struct, union, enum.
l l l
l l
l l
Web browsers
Web browsers are used to navigate through the information found on the net. Browsers allow us to retrieve the information from the internet and display it using the hypertext markup language(HTML). Hotjava, Netscape navigator and Internet explorer are some popular web browsers.
8
1 1 1 1 1 1 1
Applet viewer for viewing java applets. Enables us to run java applets Javac (javac compiler): translates java source code to byte code Java (java interpreter): runs applets and applications by reading and interpreting byte code Javap (java disassembler): converts byte code file into program description. Javah (for c header files):produces leader files for use with native network Javadoc(for creating html documents):creates html format documentation from java source file Jdb(java debugger)
Language support packages :A collection of classes and methods required for implementing basic features of java. Utilities packages: A group of classes that provide utility functions such as date and time functions Input / output package: collection of classes required for input/output manipulation. Networking package: Set of classes for communicating for other computers is a internet . Awt package: Collections of classes that implement platform independent GUI Applet package: Collection of classes that allows to create java applets
1 1 1 1 1
1.9 SUMMARY
Java is a pure object oriented language introduced by sun Microsystems. In this chapter, we have introduced an overview of java history and its salient features. It has many characteristics that make it suitable for Internet programming. Fundamental differences between Java and c++ have also been discussed. Various tools and environment required for implementation of java programs have also been included.
EXERCISES
1. 2. 3. 4. 5. 6. 7. Why is Java known as platform-neutral language? How is Java more secured than other languages? What is multithreading? How does it improve the performance of JAVA? List at least seven major differences between C and Java. How is Java strongly associated with the Internet? What is Hypertext Markup Language? Describe its role in the implementation of Java applets. List out primary goals of Java Technology?
Chapter 2
OBJECTIVES
1 1 1 1
Identify various programming approaches Define object-oriented paradigm Discuss different features of OOP Lists the advantages and disadvantages of OOP
2.0 INTRODUCTION
Object oriented programming (OOP) is an approach to program organization and development which attempts to eliminate some of the pitfalls of conventional programming methods by incorporating the best of structured programming methods with several new concepts. It is a new way of organizing and developing and has nothing to do with any particular language. Before learning the oops concepts, we will see some of the features of programming approaches as mentioned below
10
11
applications. These include techniques such as unstructured programming, procedural programming, modular programming and object-oriented programming.
Unstructured Programming
Usually, people start learning programming by writing small and simple programs consisting only of one main program. Here main program stands for a sequence of commands or statements, which modify data, which is global throughout the program. We can illustrate this as shown in Fig.2.1
Figure 2.1: Unstructured programming. The main program directly operates on global data.
Procedural Programming :
With procedural programming you are able to combine returning sequences of statements into one single place. A procedure call is used to invoke the procedure. After the sequence is processed, flow of control proceeds right after the position where the call was made (Fig.2.2).
Figure 2.2: Execution of procedures. After processing flow of controls proceed where the call was made.
With introducing parameters as well as procedures of procedures (sub procedures) programs can now be written more structured and error free. For example, if a procedure is correct, every time it is used it produces correct results. Consequently, in cases of errors you can narrow down your search to those places, which are not proven to be correct. Now a program can be viewed as a sequence of procedure calls. The main program is responsible to pass data to the individual calls, the data is processed by the procedures and, once the program has
12
finished, the resulting data is presented. Thus, the flow of data can be illustrated as a hierarchical graph, a tree, as shown in Fig. 2.3 for a program with no sub procedures.
The main program coordinates calls to procedures and hands over appropriate data as parameters.
Modular Programming
With modular programming procedures of a common functionality are grouped together into separate modules. A program therefore no longer consists of only one single part. It is now divided into several smaller parts which interact through procedure calls and which form the whole program (Fig.2.4).
13
The main program coordinates calls to procedures in separate modules and hands over appropriate data as parameters. Each module can have its own data. This allows each module to manage an internal state, which is modified by calls to procedures of this module. However, there is only one state per module and each module exists at most once in the whole program.
Object-Oriented Programming
In object oriented programming, a complex system is decomposed in accordance to the key abstractions of the problem. Rather than decomposing the problems into steps, we identify objects, which are delivered directly from the vocabulary of the problem domain. we view the world (problem domain) as a set of autonomous agents that collaborate to perform some higher level behavior. Each object in the solution embodies its own unique behavior and each one models some object in the real world. The object is simply a tangible entity that exhibits some well defined behavior. Objects do things we ask them to perform what they do by sending the messages. OOP paradigm helps us to organize the inherent complexities of software systems.
Definition
It is a method of implementation in which programs are organized as co-operative collection of objects, each of which represents an instance of some class and whose classes all members of a hierarchy of classes united in inheritance relationships.
14
15
in OOP language. An instance of a tree and a tree object are both the same thing.
Abstraction
Abstraction - the act or process of leaving out of consideration one or more qualities of a complex object so as to attend to others. Solving a problem with objects requires you to build the objects tailored to your solution. We choose to ignore its inessential details, dealing instead with the generalized and idealized model of the object.
Encapsulation
The ability to provide users with a well-defined interface to a set of functions in a way, which hides their internal workings. In object oriented programming, the technique of keeping together data structures and the methods (procedures) which act on them. The easiest way to think of encapsulation is to reference phones. There are many different types of phones, which consumers can purchase today. All of the phones used today will communicate with each other through a standard interface. A phone made by GE can be used to call a phone made by Panasonic for example. Although their internal implementation may be different their public interface is the same. This is the idea of encapsulation.
Information Hiding
It is a process of hiding all the secrets of an object that do not contribute to its essential characteristics. Typically, the structure of an object is hidden as well as the implementation of the methods.
Inheritance
Inheritance in object oriented programming means that a class of objects can inherit properties from another class of objects. When inheritance occurs, one class is then referred to as the parent class or superclass or base class. In turn, these serve as a pattern for a derived class or subclass. Inheritance is an important concept since it allows reuse of class definition without requiring major code changes. Inheritance can mean just reusing code, or can mean that you have used a whole class of object with all its variables and functions. Why not reuse an existing class that has behaviors similar to what you need in a new program? For example, the bike is a part of the class two wheelers, which is again a part of class vehicle as shown in following Fig 2.6
16
Vehicle Attributes: Model Make
Polymorphism
It is a key concept in object-oriented programming. Poly means many...morph means change (or form). Many changes of form or changes of form by many. Polymorphism is simply a name given to an action that is performed by similar objects. Polymorphism allows a common data-gathering message to be sent to each class and allows each subclass object to respond to a message format in an appropriate manner to its own properties. Polymorphism encourages something we call extendibility. In other words, an object or a class can have its uses extended.
Message passing
In an object based world the only way for anything to happen is by objects communicating with each other and acting on the results. This communication is called message passing and involves one object sending a message to another and (possibly) receiving a result.
17
Reusability Elimination of redundant code and use of existing classes through inheritance. Thus provides economy of expression.
Easy mapping. Object in the problem domain can be directly mapped to the objects in the program.
Scalability. Can be easily upgraded from small programs to large programs. Object oriented systems are also resilient to change and evolves over time in a better way.
2.4 APPLICATIONS
OOP can be used for such diverse applications as Real-time systems, simulation and modeling, AI and Expert systems parallel programming and Neural networks, Decision support systems, Office automation systems and others.
2.5 SUMMARY
In this chapter, various programming approaches followed since the computers were invented has been discussed. How OOP evolved as a powerful programming concept has been explained. The basic concepts of object oriented programming namely classes, objects, encapsulation, inheritance, and polymorphism have been introduced. Benefits and applications of OOP approach have been discussed briefly.
18
EXERCISES
1. 2. 3. 4.
What is object-oriented programming? How is it different from the procedure-oriented programming? How are data and methods organized in an object-oriented program? What are unique advantages of an object-oriented programming paradigm? Distinguish between the following terms: a) b) c) d) Objects and classes Data abstraction and data encapsulation Inheritance and polymorphism Dynamic binding and message passing
5. 6. 7.
Describe inheritance as applied to OOP. List a few areas of application of OOP technology. State whether the following statements are TRUE or FALSE. a) b) c) In conventional, procedure-oriented programming, all data are shared by all functions. The main emphasis of procedure-oriented programming is on algorithms rather than on data. One of the striking feature of object-oriented programming is the division of programs into objects that represent real-world entities. Wrapping up of data of different types into a single unit is known as encapsulation. One problem with OOP is that once a class is created, it can never be changed. Inheritance means the ability to reuse the data values of one object by other objects. Polymorphism is extensively used in implementing inheritance. Object-oriented programs are executed much faster than conventional programs. Object-oriented systems can scale up better from small to large. Object-oriented approach cannot be used to create databases.
d) e) f) g) h) i) j)
Chapter 3
OBJECTIVES
A
1 1 1 1 1
Define stand-alone applications and applets Write a simple java program Explain the java program structure Create, compile, run a java program Differentiate between a compiler and java virtual machine
3.0 INTRODUCTION
Java is a general-purpose, object-oriented programming language. We can develop two types of Java programs : * Stand-alone applications * Web applets They are implemented as shown in the Figure 3.1.
19
20
Stand-alone applications
Stand-alone applications are program written in JAVA to carry out certain tasks on a stand-alone local computer. Java program involves two steps : 1. Compiling source code into bytecode using javac compiler 2. Executing the bytecode program using java interpreter
Web applets
Applets are small Java programs developed for Internet applications. An applet located on a distant computer (Server) can be downloaded via Internet and executed on a local computer(Client) using a Java-capable browser.
Java Sourc
Java Compiler
Java Interpreter
Output
Output
21
Class Declaration
The first line, class Example, declares a class, which is an object-oriented construct. Java is a true object-oriented language and therefore, everything must be placed inside a class. Class is a keyword. Example is a Java identifier that specifies the name of the class. In Java, the class definition begins with a call to the main( ) method. Similar to a C or C++ environment, the execution of all Java applications begins with a call to the main( ) method.
An interpreter is guided by the main( ) method in determining the position from which byte code should be interpreted. A program can contain various classes. However, only one of these needs, to contain the main( ) method.
22
In the main( ) method, all the components that make up the main( ) method are specified within a second set of braces. The entire body of the main( ) method is contained within these braces.
The main( ) method body ends with the first brace, and the second brace ends the class definition. // This program displays a message import java, lang.*; class Example { public static void main(String args[ ]) { int x, y, z; x = 100; y = 200; z= 300; System.out.println(This is an example of a Java program.); } }
23
After specifying the keyword static, you specify the void keyword. This keyword indicates to the compiler that, the main( ) method does not return a value.
For example, the displayed code declares that the main( ) method accepts the parameters as an array of the String object
Blocks of code
Java allows two or more logically inseparable statements to be grouped into blocks of code. A block of code is specified within the main( ) method body and is contained within braces. A block of code can be referred to as a subset of the main( ) method. For example:
24
Lets review
Notice that the statement linking the code to a package is specified first. It is followed by the class definition. The class definition begins with a call to the main( ) method. The main( ) method body contains various data types, variables, and commands. The main( ) method body also contains a statement for generating a specified output. Java allows two or more logically inseparable statements to be grouped into blocks of code. Developing a Java program by using the correct structure reduces the time and effort spent by a developer in debugging a program.
25
The statement begins with System.out. This is a constant that represents the default output mode, which in this case is the screen. The constant helps to read and display the data in a Java program. The output is generated using the built-in println( ) method. The string that is assigned to the println( ) method is displayed when the statement is executed. In the example displayed on the screen, the output generated is the text
26
Documentation Section Package Statement Impot Statements Interface Statements Class Definitions Main Method class { Main Method Definition }
Documentation Section
The documentation section comprises a set of comment lines giving the name of the program , the author and other details. Java also uses comment /***/ known as documentation comment.
Package Statement
The first statement allowed in a Java file is a package statement. This statement declares a package name and informs the compiler that the classes defined here belong to this package. Eg : package student;
Import Statement
The next thing after a package statement (but before any class definitions) may be a number of import statements. This is similar to the #include statement in C. Example : Import student.test; This statement instructs the interpreter to load the test class contained in the package student.
Interface Statements
An interface is like a class but includes a group of method declarations. This is also an optional section and is used only when we wish to implement the multiple inheritance feature in the program.
27
Class Definitions
A Java program may contain multiple class definitions. Classes are the primary and essential elements of a Java program.
Keywords
Keywords are an essential part of a language definition. They implement specific features of the language. Java language has reserved 60 words as keywords. The following table lists the keywords. These keywords have specific meaning in Java, we cannot use them as names for variables, classes, methods. All keywords are to be written in lower case letters. Since Java is case-sensitive.
Java Keywords
Abstract
boolean Case cast Const* continue Else extends Float For If implements Int interface Null** operator* Protected public Static super Threadsafe* throw Try var* * Reserved for future use
break catch default false** future* import long outer* rest* switch throws void
byte char do final generic* inner* native package return synchronization transient volatile
byvalue* class double finally goto* instanceof new private short this true** while
28
Identifiers
Identifiers are used for naming classes, methods, variables, objects, labels, package and interfaces in a program. Java identifiers follow the following rules: 1. They can have alphabets, digits, and the underscore and dollar sign characters. 2. They must not begin with a digit 3. Uppercase and lowercase letters are distinct. 4. They can be of any length. Examples : Average, sum, Batch_strength
Literals
Literals 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 :
l l l l l
Interger literals Floating_point literals Character literals String literals Boolean literals
Operators
An operator is a symbol that takes one or more arguments and operates on them to produce a result.
29
Java Compiler
Bytecode
Windows Interpreter
ABC Interpreter
Macintosh Interpreter
Machine Code
Machine Code
Machine Code
Windows Computer
ABC Computer
Macintosh Computer
Java filename
Now, the interpreter looks for the main method in the program and begins execution from there. When executed, our program displays the following: This is an example of a java program
30
produces an intermediate code known as bytecode for a machine that does not exist. This machine is called the Java Virtual Machine and it exists only inside the computer memory. The following Figure 3.4 illustrates the process of compiling a Java program into bytecode which is also referred to as virtual machine code.
Java Compiler
Fig 3.4 Process of compilation
The virtual machine code is not machine specific. This machine specific code ( known as machine code) is generated by the Java interpreter by acting as an intermediary between the virtual machine and the real machine as shown in the Figure3.5. Interpreter is different for different machines
Bytecode
Java Interpreter
Fig 3.5 Process of converting bytecode into machine code
Machine Code
3.6 SUMMARY
In this chapter, we have discussed a simple application program to familiarize the readers with basic java structure and syntax. the basics of java language and steps involved in creating and executing a java application program has also been presented.
EXERCISES
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. Describe the structure of a typical Java program. What is the task of the main method in a Java program? What is a token? List the various types of tokens supported by Java. Why cant we use a keyword as a variable name? Enumerate the rules for creating identifiers in Java. What are the conventions followed in Java for naming identifiers? Give examples. Explain println statement in Java with an example? Why main method in Java is declared as static? What is Applet? Explain with a simple example how to create, compile and run a program in Java?
Chapter 4
OBJECTIVES
A
1 1 1 1
Define java constants and variables Describe their representation inside computer Discuss data type conversion Discuss what is typecasting
4.0 INTRODUCTION
A programming language is developed to process certain kinds of data consisting of numbers, characters and strings and to provide useful output known as information. The task of processing data is accomplished by executing a sequence of instructions constituting a program. Constants in Java refer to fixed values that do not change during the execution of a program
4.1 CONSTANTS
Integer Constant
Integer constants may be decimal or hexadecimal. Decimal constants are written as ordinary integers
31
32
with no decimal point using the digits 0 through 9.. They can range in magnitude from negative to positive 231 - 1 (approximately two billion). Constants larger than these permissible magnitudes will produce unpredictable results. Leading plus or minus signs are permitted, as are leading zeros. Valid examples of decimal integer constants are 1 ,-45, 377849 ,-1999999999,0 ,12 , -45 , 078 , +99 An octal integer constant consists of any combination of digits from the set of 0 through 7 with a leading 0. Some examples are 037 ,0 0435,0551
Real Constants
Quantities are represented by numbers containing fractional parts like 17.548. Such numbers are called real (or floating point) constants. A real number may also be expressed in exponential (or scientific) notation. For example, the value 215.65 may be written as 2.1565e2 in exponential notation. E2 means multiply by 102. The general form is:
Mantissa
exponent
The mantissa is either a real number expressed in decimal notation or an integer. The exponent is an integer with an optional plus or minus sign. The letter e separating the mantissa and the exponent can be written in either lowercase or uppercase Further examples of real constants are 3.14159 ,-8.92E-45 ,0.0001724 ,8.95e294, 0.0 -12.0 3E4 4e+5 +12.3e-45
Character Constants
A character constant consists of a single character enclosed in single quotes. Control characters can be placed in character constants by a # character followed by an integer constant (decimal or hexadecimal) corresponding to the desired ASCII value.. Valid examples of character constants are a 1 ; #10 #$1A A character constant has the char type.
String Constants
A string constant consists of zero or more characters enclosed in double quotes, as in
33
ab Hello! A line... If the string is two or more characters, it can be enclosed in single quotes instead of double quotes: ab is the same as ab If there is only one character in the string and you enclose it in single quotes, it will be taken as a character constant rather than a string constant. This causes no problems
* Numbering of the bits starts at 0 Fig.4.1.Determining Number of Possible Values, and Range of Values, for a Value
34
Sign Bit: 0/1 7 -/+ 0/1 6 0/1 5 0/1 4 Value bits: 0/1 3 0/1 2
0/1 1
0/1 0*
* Numbering of the bits starts at 0 Fig.4.1.Determining Number of Possible Values, and Range of Values, for a Value
Primitive (Intrinsic)
Non-Primitive (Derived)
Numeric
Non-numeric
Classes
Arrays
Integer
Floating-point
Character
Boolean
Interface
35
Integer Types
Integer types can hold whole numbers such as 123,-96,and 5639. The size of the values that can be stored depends on the integer data type we choose. Java supports four types of integers. Byte, short, int, and long. Java does not support the concept of unsigned types and therefore all Java values are signed, meaning they can be positive or negative. The different integer types along with their range and length are given in Table.4.1.
Type Byte Short Int Length 8 bits 16 bits 32 bits Range Examples of Allowed Literal Values 2 -114 2 -62699 2 147,334,778
Long
64 bits
-27 to 27 1 (-128 to 127, or 256 possible values) -215 to 215 1 (-32,768 to 32,767 or 65,535 possible values) -231 to 231 1 (-2,147,483,648 to 2,147,483,648 or 4,294,967,296 possible values) -263 to 263 1 ( 2 -9,223,372,036854,775,808 to -2,036854,775,808L 9,223,372,036854,775,808, or 1L 18,446,744,073709,551,616 possible values
Table 4.1. Integer Types
Double
64 bits
When you specify a literal value for a float, put a capital F(float) to the right of the value to explicitly state that it is a float, not a double. Literal values for floating point types are assumed to be doubles unless you specify otherwise, using the F.
36
Character Type
Another data type you need to store and manipulate is single-character information. The primitive type used for storing a single character is char.
Note You can store only one character in a char variable. If you want to store whole words or phrases you use an object type (not a primitive type) called String. This will be discussed later.
Most computer languages use the American Standard Code for Information Interchange (ASCII), an 8-bit character set that has an entry for every English character and punctuation mark, numbers and so on. The Java programming language uses a 16-bit character set called Unicode that can store all the necessary displayable characters from the vast majority of languages used in the modern world. Your programs can therefore be written so that they will work and display the correct language for countries. Unicode contains a subset of ASCII (the first 128 characters)
4.3 VARIABLES
A variable is an identifier that denotes a storage location used to store a data value. Unlike constants that remain unchanged during the execution of a program, a variable may take different values at different times during the execution of the program. * average * height * total_height * classStrength As mentioned earlier, variable names may consist of alphabets, digits, the underscore ( _ ) and dollar characters, subject to the following conditions: 1. They must not begin with a digit. 2. Uppercase and lowercase are distinct. This means that the variable Total is not same as total or TOTAL. 3. It should not be a keyword. 4. White space is not allowed. 5. Variable names can be of any length.
37
Declaration of variables
In Java, variables are the names of storage locations. After designing suitable variable names, we must declare them to the compiler. Declaration does three things: 1. It tells the compiler what the variable name is. 2. It specifies what type of data the variable will hold. 3. The place of declaration (in the program) decides the scope of the variable. A variable must be declared before it is used in the program. A variable can be used to store a value of any data type. That is, the name has nothing to do with the type. Java allows any properly formed variable to have any declared data type. The declaration statement defines the type of variable. The general form of declaration of a variable is :
Variables are separated by commas. A declaration statement must end with a semicolon. Some valid declaration are:
Assignment Statement
A simple method of giving value to a variable is through the assignment statement as follows:
VariableName = value;
38
For example initialValue = 0; finalvalue yes = 100; = x;
we can also string assignment expressions as shown below: x = y = z = 0; It is also possible to assign a value to a variable at the time of its declaration. This takes the form:
The process of giving initial values to variables is known as the initialization. The ones that are not initialized are automatically set to zero. The following are valid Java statements: float x, y, z; int m = 5, n = 10; int m, n = 10; // declares three float variables // declares and initializes two int variables // declares m and n initializes n
39
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. 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 area of the program where the variable is accessible (i.e., usable) is called its scope.
The process of converting one data type to another is called casting. Examples Int m Byte n = 50; = (byte)m;
4.6 SUMMARY
Java constants and variables, and their representation inside the computer have been described in this chapter. Way and means of declaring and initializing java variables has also been presented. We have also discussed how data type conversions is achieved in java.
EXERCISES
1. 2. 3. 4. What is a Constant? What is a variable? List the eight basic data types used in Java. Give examples. What is scope of a variable.
40
5. 6. What is type casting? Why is it required in programming? Which of the following are invalid constants and why.
n1+n2 N$ Total-Marks
Find errors, if any, in the following declaration statements: int x; float length, height; double = p,q; character c1; final int total; final pi = 3.142; long int m;
9.
Write a program to determine the sum of the following harmonic series for a given value of n: 1+1/2 + 1/3+ ..+1/n The value of n should be given interactively through the keyboard.
10.
Write a program to convert the given temperature in Fahrenheit to Celsius using the following conversion formula F-32 C= 1.8 And display the values in a tabular form.
Chapter 5
OBJECTIVES
A
1 1 1 1 1
Use rich set of operator that java provides Write mathematical and logical expression in java Understand manipulation of data and variables Describe type conversions and order of precedence of operators Conclude that java types are of fixed size and machine independent
5.0 INTRODUCTION
Java supports a rich set of operations. An operator is a symbol that tells the computer to perform certain mathematical or logical manipulations they usually form a part of mathematical or logical operations. Java operators can be classified into number categories, namely: Arithmetic operators, relational operators, logical operators ,assignment operators ,Increment and decrement operators,conditional operators,bit wise operators,special operators
41
Java provides all the basic arithmetic operators. They are listed in the following table 5.1 The basic operators in Java are:
Operator + * /
Explanation adds two numbers subtracts two numbers multiplies two numbers divides two numbers
x = 17 % 3 //x = 2
There are five basic arithmetic operators in Java: addition (+), subtraction (-), multiplication (*), division (/) and modulus (%). All operators can be used with all primitive numeric types (char, byte, short, int, long, float and double). In addition any two numeric types can be combined (mixed mode arithmetic). Although the operators can be used with any numeric type, Java actually only does arithmetic with the types int, long, float and double. Therefore, the following rules are used to first convert both operands into one of these four types: 1. If either operand is a double then the other is converted to double. 2. if either operand is a float then the other is converted to float. 3. if either operand is a long then the other is converted to a long. 4. both are converted to int.
43
called an integer expression, and the operation is called integer arithmetic. Integer arithmetic always yields an integer value. In the following examples, if x and y are integers, then for x=12 and y=5 we get the following results: xy = 7 x + y = 17 x * y = 60 x / y = 2 (decimal part truncated) x % y = 2 (remainder of integer division) x / y, when x and y are integer types, gives the result division of x and y after truncating the divisor. This operation is called the integer division. For modulo division, the sign of the result is always the sign of the first operand (the dividend). That is - 20 % 3 = -2 - 20 % -3 = -2 20 % -3 = 2 (when the module division is defined as: x%y=x-(x/y)*y, where x/y is the integer division)
44
Int d=c-a; Int e= -d; System.out.println(a = +a); System.out.println(b = +b); System.out.println(c= +c); System.out.println(d = +d); System.out.println(e= +e); System.out.pritln(\nfloating point Arthamatic); double fa=1+1; double fb=a*3; double fc=b/4; double fd=c-a; double fe= -d; System.out.println(fa = +fa); System.out.println(fb = +fb); System.out.println(fc= +fc); System.out.println(fd = +fd); System.out.println(fe= +fe); } }
Result
Integer Arithmetic a=2 b=6 c=1 d=-1 e=1 Floating point arithmetic fa=2.0 fb=6.0 fc=1.5
45
fd=-0.5 fe=0.5
46
System.out.println(j is + j); int k = i/j; System.out.println(i/j is + k); k = i * j; System.out.println(i * j is + k); } } Heres the result: % javac MultiplyDivide.java % java MultiplyDivide i is 10 j is 2 i/j is 5 i * j is 20
Floats and doubles are multiplied and divided in exactly the same way. When faced with an inexact integer division, Java rounds the result down. For instance dividing 10 by 3 produces 3. Class modulus { public static void main(string args[ ]) { int x=42; double y=42.3; System.out.println(x mod 10 = + x%10); System.out.println(x mod 10= +y%10); } } Result: X mod 10 = 2 X mod 10 = 2.3
47
v op= exp;
Java also provides several short cut assignment operators that allow you to perform an arithmetic, logical, or bitwise operation and an assignment operation all with one operator. Suppose we wanted to add a number to a variable and assign the result back into the variable, like this: i = i + 2; You can shorten this statement using the short cut operator +=. i += 2; The two previous lines of code are equivalent. This table 5.2 lists the shortcut assignment operators and their lengthy equivalents:
48
Java supports six relational operators in all. These operators and their meaning are as shown the below table 5.3.
Operator
> >= < <=
Returns true if is greater than op2 is greater than or equal to op2 is less than op2 is less than or equal to op2 and op2 are equal and op2 are not equal
Op1 < op2 Op1 <= op2 Op1 == op2 Op1 != op2
==
op1
!=
op1
A simple relational expression contains only one relational operator and is of the following form.
Expression 15. 6 <= 20 9.5 < - 10 -20 >= 0 10 < 7 + 8 a+b == c+d TRUE FALSE FALSE TRUE TRUE
Value
* Only if the sum of values of a and b is equal to the sum of values of c and d.
49
Operator
T&&
Use
Op1 && op2 op1
|| !
op1 || op2 ! op
is false.
Following table gives the false and true conditions for the && and !! operations when applied on two operands op1 and op2.
&& is logical and. && combines two boolean values and returns a boolean which is true if and only if both of its operands are true. For instance
50
boolean b; b = 3 > 2 && 5 < 7; // b is true b = 2 > 3 && 5 < 7; // b is now false
|| is logical or. || combines two boolean variables or expressions and returns a result that is true if either or both of its operands are true. For instance boolean b; b = 3 > 2 || 5 < 7; // b is true b = 2 > 3 || 5 < 7; // b is still true b = 2 > 3 || 5 > 7; // now b is false The last logic operator is ! which means not. It reverses the value of a boolean expression. Thus if b is true !b is false. If b is false !b is true. boolean b; b = !(3 > 2); // b is false b = !(2 > 3); // b is true These operators allow you to test multiple conditions more easily. For instance the previous example can now be written as if (x == 2 && y != 2) { System.out.println(Both conditions are true.);}
51
Consider the following: m=5; y = ++m; In this case, the value of y and m would be 6. Suppose, if we rewrite the above statement as m = 5; y = m++; Then, the value of y would be 5 and m would be 6. A prefix operator first adds 1 to the operand and then the result is assigned to the variable on left. On the other hand, a postfix operator first assigns the value to the variable on left and then increments the operand. Table 5.6 illustrates the use of increment and decrement operators
Operator ++
Purpose Pre-Increment
Syntax j=++i
Post-Increment
j=i++
--
Pre-Decrement
j=--i
Post-Decrement
j=i--
Example int i=6 int j=++i; i is 7 ,j is 7 int i=6; int j=i++; i is 7,j is 6 int i=6; int j=--i; i is 5, j is 5 int i=6; int j=i--; i is 5, j is 6
The following programs illustrates the working of increment and decrement operators class incdec { public static void main(string args[ ]) { int a = 3; int b = 4; int c; int d;
52
c = ++b; d = a++; c++; system.out.println(a= +a); system.out.println(b= +b); system.out.println(c= +c); system.out.println(d= +d); } }
Result
a=4 b=5 c=6 d=3
Class incr01 { //define the controlling class public static void main(String[ ] args){ //define main int x = 5, X = 5, y = 5, Y = 5; System.out.println("x = " + x ); System.out.println("X = " + X ); System.out.println("x + X++ = " + (x + X++) ); System.out.println("X = " + X ); System.out.println(); System.out.println("y = " + y ); System.out.println("Y = " + Y ); System.out.println("y + ++Y = " + (y + ++Y) ); System.out.println("Y = " + Y ); }//end main }//End incr01 class. //End Java application
A - The output from this Java application follows: x=5 x=5 x + x++ = 10
53
5.7
BITWISE OPERATORS
A shift operator allows you to perform bit manipulation on data. The table 5.7 summarizes the shift operators available in the Java programming language.
Operator
>> << >>>
Use
op1 >> op2 op1 << op2 op1 >>> op2
Operation shift bits of op1 right by distance op2 shift bits of op1 left by distance op2 shift bits of op1 right by distance op2 (unsigned)
Each shift operator shifts the bits of the left-hand operand over by the number of positions indicated by the right-hand operand. The shift occurs in the direction indicated by the operator itself. For example, the following statement shifts the bits of the integer 13 to the right by one position: 13 >> 1; The binary representation of the number 13 is 1101. The result of the shift operation is 1101 shifted to the right by one position110 or 6 in decimal. Note that the bit farthest to the right falls off the end into the bit bucket. The Java programming language also provides these four operators that perform logical functions on their operands:
Operator
& | ^ ~
Use
op1 & op2 op1 | op2 op1 ^ op2 ~op2
The & operation performs the logical and function on each parallel pair of bits in each operand. The and function sets the resulting bit to 1 if both operands are 1, as shown in this following table:
op1 op2
0 0 1 1
0 1 0 1
Result 0 0 0 1
55
Suppose you were to and the values 12 and 13: 12 & 13 The result of this operation is 12. Why? Well, the binary representation of 12 is 1100, and the binary representation of 13 is 1101. The and function sets the resulting bit to 1 if both operand bits are 1, otherwise, the resulting bit is 0. So, if you line up the two operands and perform the and function, you can see that the two high-order bits (the two bits farthest to the left of each number) of each operand are 1. Thus the resulting bit in the result is also 1. The low-order bits evaluate to 0 because either one or both bits in the operands are 0: 1101 & 1100 1100 The | operator performs the inclusive or operation and ^ performs the exclusive or operation. Inclusive or means that if either of the two bits are 1 then the result is 1. The following table shows the results of your inclusive or operations:
op1 op2
0 0 1 1
0 1 0 1
Result 0 1 1 1
Exclusive or means that if the two operand bits are different the result is 1, otherwise the result is 0. The following table shows the results of your exclusive or operation.
op1 0 0 1 1
op2 0 1 0 1
Result 0 1 1 0
And finally, the complement operator inverts the value of each bit of the operand: if the operand bit is 1 the result is 0 and if the operand bit is 0 the result is 1. Once you have a boolean value, either stored in a variable representing a primitive boolean value (e.g.
56
boolean done = false;) or as the result of an expression involving a relational operator (e.g. x < y) then you can combine these boolean values using the logical operators. Java provides four logical operators: and, (&) or, (|) exclusive or, (^) and not (!). The meaning of these operators is given by the following rules:
l l l l
x & y is true if both x AND y are true and false otherwise. x | y is true if either x OR y (or both) is true and false otherwise. x ^ y is true if exactly one of x OR y is true and false otherwise. ! x is true is x is false and false otherwise.
For example if you wanted to check that a person in a database was an adult but not a senior citizen you could check if their age was greater than or equal to 18 and their age was less than or equal to 65.
5.7.3 Type-Casting
Casting means assigning a value of one type to a variable of another type If the two types are compatible, the java technology performs the conversation Automatically. For example, an int value can always be assigned to a long Variable. Where information would be lost in an assignment ,the compiler requires that you confirm the assignment with a typecast. This can be done ,for example , bysqueezing a long value into an int variable. Explicit casting is done like this: Long bigvalue= 99L Int small= (int) (bigvalue); The desired target type is placed in parentheses and used as a prefix to the expression that must be modified.
57
The basic evaluation procedure includes two left-to-right passes through the expressions. During the first pass, the high priority operators (if any) are applied as they are encountered. During the second pass, the low priority operators (if any) are applied as they are encountered. Consider the following evaluation statement: x = a-b/3+c*2-1 When a=9, b=12 and c=3, the statement becomes x = 9-12/3+3*2-1 and is evaluated as follows:
First pass
Step1 : x = 9-4+3*2-1 Step2: x = 9-4+6-1 (12/3 evaluated) (3*2 evaluated)
58
Second pass
Step3 : x = 5+6-1 Step4: x = 11-1 Step5: x = 10 (9-4 evaluated) (5+6 evaluated) (11-1 evaluated)
However, the order of evaluation can be changed by introducing parenthesis into an expression. Consider the same expression with parenthesis as shown below: 9-12/ (3+3) * (2-1) Whenever the parenthesis are used, the expressions within parenthesis assume highest priority. If two or more sets of parenthesis appear one after another as shown above, the expression contained in the leftmost set is evaluated first and the right-most in the last. Given below are the new steps.
First pass
Step1 : Step2: 9-12/6*(2-1) 9-12/6*1
Second pass
Step3 : Step4: 9-2*1 9-2
Third pass
Step5: 7
59
Associativity Left to right Rank 1
Operator . () [] ++ -! ~ (type) * / % + << >> >>> < <= > >= instanceof == != & ^ | && || ?: = Op=
Description Member selection Function call Array element reference Unary minus Increment Decrement Logical negation Ones complement Casting Multiplication Division Modulus Addition Subtraction Left shift Right shift Right sift with zero fill Less than Less than or equal to Greater than Greater than or equal to Type comparison Equality Inequality Bitwise AND Bitwise XOR Bitwise OR Logical AND Logical OR Conditional operator Assignment operators Shorthand assignment
Right to left
Left to right
Left to right
Left to right
Left to right
Left to right Left to right Left to right Left to right Left to right Left to right Right to left Right to left
7 8 9 10 11 12 13 14
Mathematical functions such as cos, sqrt, log, etc, are frequently used in analysis of real-life problems. Java supports these basic math functions through Math class defined in the the java.lang package. The following table lists the math functions defined in the Math class. These functions should be used as follows: Math.function_name( ) Example double y = Math. Sqrt(x);
Mathematical Functions
Functions Sin (x) Cos (x) Tan (x) Asin (y) Acos (y) Atan(y) Atan2(x,y) pow(x,y) exp(x) log(x) sqrt(x) ceil(x) floor(x) rint(x) abs(x) max(a,b) min(a,b) Action Returns the sine of the angle x in radians Returns the cosine of the angle x in radians Returns the cosine of the angle x in radians Returns the angle whose sine is y Returns the angle whose cosine is y Returns the angle whose tangent is y Returns the angle whose tangent is x/y Returns x raised to y (xy) Returns e raised to x (ex) Returns the natural logarithm of x Returns the square root of x Returns the smallest whole number greater than or equal to x. (Rounding up) Returns the largest whole number greater than or equal to x. (Rounding down) Returns the truncated value of x. Returns the absolute value of x. Returns the maximum of a and b. Returns the minimum of a and b.
Note : x and y are double type parameters. And b may be ints, longs, floats and doubles.
5.9 SUMMARY
In this chapter, we have discussed all the operators in java and their usage in expressions. We have highlighted the type conversions and order of precedence
61
While evaluating expressions simple programs are presented to demonstrate use of different type expressions operators It should be noted that all java types are of fixed size and are machine independent.
EXERCISES
1. Which of the following arithmetic expressions are valid?
a) 25/3 % 2 b) +9/4 + 5 c) 7.5 % 3 d) 14 % 3 + 7 % 2 e) 14 % 3 f) 15.25 + -5.0 g) (5/3) * 3 + 5 % 3 h) 21 % (int) 4.5
2. 3.
a) Area
= pr2+2prh 2m1 m2
b) Torque = m1 + m2 c) Side =
*g
d) Energy = mass acceleration * height + 2 4. Identify unnecessary parenthesis in the following arithmetic expressions. a) b) c) d) 5. (x-(y/5)+z) % 8) + 25 ((x-y) * p) + q (m*n) + (-x/y) x/(3*y)
Find errors, if any, in the following assignment statements and rectify them. a) b) c) d) x = y = z = 0.5, 2.0 5.75; m = ++a * 5; y = sqrt(100); p * x/y;
62
e) f) 6. s = /5; a = b++ -c * 2
Determine the value of each of the following logical expressions if a=5, b=10 and c=-6 a) b) c) d) e) a>b && a<c a<b && a>c a==c || b>a b>15 && c<0 || a>0 (a/2.0 == 0.0 && b/2.0 != 0.0) || c< 0.0
7.
The straight-line method of computing the early depreciation of the value of an item is given by Depreciation = Years of service Write a program to determine the salvage value of an item when the purchase price, years of service, and the annual depreciation are given. Purchase price Salvage value
8.
The total distance traveled by a vehicle in t seconds is given by Distance = ut + (at2)/2 Where u is the initial velocity (metres per second), a is the acceleration (metres per second). Write a program to evaluate the distance traveled at regular intervals of time, given the values of u and a. The program should provide the flexibility to the user to select his own time intervals and repeat the calculations for different values of u and a.
9.
In inventory management, the Economic Order Quality for a single item is given by
Write a program to compute EOQ and TBO, given demand rate (items per unit time), setup costs (per order), and the holding cost(per item per unit time).
Chapter 6
A
1 1 1
fter going through this chapter, you will be able to understand the
6.0 INTRODUCTION
Java language possesses decision making capabilities and supports the following statements known as control or decision-making statements.
l l l
63
64
It takes the following form: if (test expression) { statement block; }
It allows the computer to evaluate the expression first and then , depending on whether the value of the expression (relation or condition) is true (non-zero) or false (zero), it transfers the control to a particular statement. This point of program has two paths to follow , one for the true condition and the other for the false condition. The if statement may be implemented in different forms depending on the complexity of the conditions to be tested.
l l l l
65
The following program using simple if statement finds the greatest of two numbers. Example : // Program to find the greatest of two numbers public class Greater { public static void main(String [ ] args) { int x=10,y=20; if (x > y) { System.out.println(x + is greater than + y); } if(y>x) { System.out.println(y + is greater than + x); } System.out.println(); } }
66
The example used for simple if statements is rewritten in the following using the if else statement
67
//program to find the greatest of two numbers public class Greater { public static void main(String [ ] args) { int x=10,y=20; if (x > y) { System.out.println(x + is greater than + y); } else { System.out.println(y + is greater than + x); } System.out.println( ); } In the following we write a simple program to find whether the given number is odd or even public class OddOrEven{ public static void main(String [ ] args) { int number = 25; /* determine whether the number is odd or even and print a message to the screen. */ System.out.println(); if (number % 2 == 0) { System.out.println(number + is even.); } else { System.out.println(number + is odd.); } System.out.println(); } }
68
if(test condition1) if (test condition2) { statement-1; } Else { statement-2; } else { Statement-3; } Statement-x;
If the condition-1 is false statement-3 will be executed; otherwise it continues to perform the second test. If the condition-2 is true, the statement-1 will be evaluated; otherwise the statement-2 will be evaluated and then the control is transferred to the statement-x.
Example: To find the greatest of two numbers public class Greater { public static void main(String [ ] args) { int x,y; x = 10; y = 10; /* determine which number is the greater of the two and display the greater number on the screen.*/ System.out.println( ); if (x > y) { System.out.println(x + " is greater than " + y); }
69
else if (x == y) { System.out.println("The two numbers are equal.") } else { System.out.println(y + " is greater than " + x); } System.out.println(); } }
Point to Note
This program uses an if - else if - else construct. The if part is evaluated first. If the boolean expression evaluates to true, the statements between the first set of brackets are executed. If the if part evaluates to false, the boolean expression in the else if part is evaluated. If this is true, the statements between the second set of brackets are executed. If the else if part evaluates to false, the statements between the third set of brackets (the else part) are executed.
70
if (condition 1) Statement-1;
................
else if(condition n)
Statement-n; else default-statement; Statement-x;
Fig 6.4 General form of else-if ladder
This construct is known as the else if ladder. The conditions are evaluated from the top (of the ladder), downwards. As soon as a true condition is found, the statement associated with is executed and the control is transferred to the statement x (skipping the rest of the ladder). When all the n conditions become false, then the final else containing the default statement will be executed.
71
False
Statement-1
True
Condition 2
False
True
Condition 3
False
Statement-2
True
False
Condition 4
Statement-3
Statement-x Next Statement Fig 6.5 Flowchart for the else-if ladder
Fig 6.5 Flowchart for the else-if ladder
72
Example :
Let us consider an example of grading the students in an academic institution. The grading is done according to the following rules: Average marks Grade 80-100 Honours 60- 79 First Division 50- 59 Second Division 40- 49 Third Division 0- 39 Fail This grading can be done using the else if ladder follows: if (marks > 79) grade = Honours; else if (marks >59) grade = First Division; else if (marks > 49) grade = Second Division; else if(marks > 39) grade = Third division; else grade = Fail;
Java program
Class grade( ) { public static void main(String[ ] args) { int testscore = 76; char grade; if (testscore >= 79) { grade = Honours;
73
} else if (testscore >= 59) { grade = First division; } else if (testscore >= 49) { grade = second division; } else if (testscore >= 39) { grade = Third division; } else { grade = Fail; } System.out.println(Grade = + grade); } } The output from this program is: Grade = First division You may have noticed that the value of testscore can satisfy more than one of the expressions in the compound if statement: 76 >= 59 and 76 >= 60. However, as the runtime system processes a compound if statement such as this one, once a condition is satisfied, the appropriate statements are executed (grade = First division;), and control passes out of the if statement without evaluating the remaining conditions.
74
A switch statement has the form:
switch (expression) { case 1: statements-1 break; case 2: statements-2 break; . . // (more cases) . case N: statements-N break; default: // optional default case } // end of switch statement
The break statements are technically optional. The effect of a break is to make the computer jump to the end of the switch statement. If you leave out the break statement, the computer will just forge ahead after completing one case and will execute the statements associated with the next case label. This is rarely what you want, but it is legal. However, that inside a subroutine, the break statement is sometimes replaced by a return statement. In a nutshell, - switch statement is convenient for handling multiple if-else cases - need to use single value as decision variable - need to identify code to be executed for each case - essential to end each case with break command can use default for all cases not specifically labeled. The case statement is diagrammatically shown in Fig. 6.6
75
The following example illustrates the use of switch statement which prints the name of the month when an integer value is given
public class SwitchDemo { public static void main(String[ ] args) { int month = 8; switch (month) { case 1: System.out.println("January"); break; case 2: System.out.println("February"); break; case 3: System.out.println("March"); break; case 4: System.out.println("April"); break;
76
case 5: System.out.println("May"); break; case 6: System.out.println("June"); break; case 7: System.out.println("July"); break; case 8: System.out.println("August"); break; case 9: System.out.println("September"); break;
case 10: System.out.println("October"); break; case 11: System.out.println("November"); break; case 12: System.out.println("December"); break; }
The switch statement evaluates its expression, in this case the value of month, and executes the appropriate case statement. Thus, the output of the program is: August. Of course, you could implement this by using an if statement: Deciding whether to use an if statement or a switch statement is a judgment call. You can decide which to use, based on readability and other factors. An if statement can be used to make decisions based on ranges of values or conditions, whereas a switch statement can make decisions based only on a single integer value. Also, the value provided to each case statement must be unique. Another point of interest in the switch statement is the break statement after each case. Each break statement terminates the enclosing switch statement, and the flow of control continues with the first statement following the switch block. The break statements are necessary because without them, the case statements fall through. That is, without an explicit break, control will flow sequentially through subsequent case statements.
77
6.4 SUMMARY
In this chapter, we discussed the features of the following selection statements Available in java: If statement, switch,conditional operator Several applications of these statements have been presented. We also discussed how these can be used to solve problems. These concepts are useful in developing complex systems. Control execution is an important tool.
EXERCISES :
1. Determine whether the following are true or false; a) b) c) When if statements are nested, the last else gets associated with the nearest if without an else. One if can have more than one else clause. A switch statement can always be replaced by a series of if.else statements
78
d) e) 2. 3. A switch expression can be of any type.
In what ways does a switch statement differ from an if statement? Find errors, if any, in each of the following segments; a) b) if (x+y = z && y > 0) if (code>1); a = b+c else a=0 c) if (p < 0) || (q < 0)
4.
Rewrite each of the following without using compound relations: a) if (grade < = 59 && grade >=50) second = second + 1 b) if (number > 100 && number < 0) System.out.print(Out of range); Else Sum = sum + number; c) if ((M1>60 && M2>60 || T >200) y=1; else y=0;
5.
Write a program to find the number of and sum of all integers greater than 100 and less than 200 that are divisible by 7.
6.
Given a list of marks ranging from 0 to 100, write a program to compute and print the number of students who have obtained marks a) b) c) d) in the range 81 to 100, in the range 61 to 80, in the range 41 to 60, and in the range 0 to 40.
79
The program should use a minimum number of if statements. 8. A cloth showroom has announced the following seasonal discounts on purchase of items:
Chapter 7
LOOPING
OBJECTIVES
A
1 1 1
fter going through this chapter, you will be able to write simple programs using the following loop constructs
7.0 INTRODUCTION
In looping, a sequence of statements are executed until some condition for the termination of the loop is satisfied. A program loop therefore consists of two segments , first the body of the loop and other is control Statement. The control statements test certain conditions and then makes the repeated execution of the statements contained in the block. There are two types of loops. They are pre-test loop and post-test loop. In pre-test loop the control variable is tested prior to the start of each iteration whereas in post-test loops the control variable is tested at the end of each iteration (Fig. 7.1.). From an efficiency point of view, the advantage is that ,we can reduce the number of tests required provided that we know that the loop must be exercised at least once. If there is a possibility that the loop should not be exercised at all then a post-test loop will not be appropriate (a pre-test loop will be required instead).
80
Chapter 7 - Looping
81
82
Chapter 7 - Looping
All the variables used in the condition of the while statement must be initialized before the while loop. The values of the variables used in the condition must be changed in the loop body. Otherwise, the condition may always remain true and the loop may never terminate. You change the values of the variables by performing arithmetic operations on the variables. You can write a single statement or multiple statements in the loop body. Multiple statements should be enclosed within braces. Otherwise, the code may generate an unexpected output. Before the loop body is executed, the condition of the while statement is evaluated. Only when the condition evaluates to true is the loop body executed. Therefore, the while loop is also called the top tested loop. After the loop body is executed, the condition is evaluated again. The sequence of evaluating the condition and executing the loop body continues until the condition becomes false.
Example: class numbers { public static void main(String args[ ]) { int n=0; int num=5; while(n<=num) { sysytem.out.printfln(n); n++; } } }
7.2 DO STATEMENT
Similar to the while statement, the do-while statement is a loop statement provided by Java. The statement helps to perform certain repetitive actions depending on a condition. The major difference between the do-while statement and the while statement is that in the while statement, the loop body is executed only when the condition stated in the statement is true. In contrast, in the do-while loop, the loop body is executed at least once, regardless of the condition evaluating to true or false. After the loop body is executed once, the condition in the do-while statement is checked. If the condition evaluates to true, the loop body is executed repeatedly until the condition becomes false. Therefore, the do-while loop is also called the bottom tested loop.
83
You can use the do-while loop in situations where an action must be performed at least once without evaluating the condition. Syntax and flowchart of the do while statement is shown in Fig. 7.3
Example 1: Ex://program to print the numbers form 1 to 5 Class numbers { public static void main(String args[ ]) { int n=0; int num=5; do { sysytem.out.printfln(n); n++; }while(n<=5); } }
84
Chapter 7 - Looping
Example 2: //Program to print the fibinocci numbers form 1 to 50 Class fibinocci { public static void main(stsring args[ ]) { int loopCounter = 0; int fib1 = 0; int fib2 = 1; int tempTerm; do { if (loopCounter == 0) System.out.print(fib1 + " "); else { if (loopCounter == 1) System.out.print(fib2 + " "); else { tempTerm = fib1 + fib2; fib1 = fib2; fib2 = tempTerm; System.out.print(fib2 + " "); } } loopCounter++; } while (loopCounter <= 50); System.out.println(); }
{ statement1; statement2; }
The for statement starts with the for keyword. This statement has three elements enclosed within parentheses.
85
The first element of the for statement is initialization expressions. The initialization expressions element is an assignment statement. The assignment is done only once before the for statement begins execution. The second element, test condition, is evaluated before each iteration of the for statement. This element determines whether the execution of the for loop should continue or terminate. Update expressions is the third element in the for statement. This element changes the values of the variables used in the test condition. Update expressions are executed at the end of each iteration after the loop body is executed. The elements of a for statement are separated by semicolons.
Example ://the program display a number form 2 to 10 class displaynumber { public static void main(stsring args[ ]) { for ( j = 2; j <= 10; j++ ) system.print(output,"i = %d",j); } }
In the for loop(Fig. 7.4.), first variable j is initialized to 2. Next, the value of j is compared with 10. If the test condition is true, the value of j is displayed on the screen. Next, the value of j is incremented by one.
86
Chapter 7 - Looping
After the value of j is incremented, the test condition is evaluated again. If the test condition evaluates to true, the print function is executed again. If the test condition evaluates to false, the flow of control comes out of the for loop. Example 2:
Similarities between for and while loops are illustrated in Fig. 7.5
Fig. 7.5 Flow charts showing similarities between for and while statements
87
For example, i=1; for(j=0; j<10; j++) can be rewritten as for(i=1,j=0; j<10; j++)
2) Like the initialization section, the increment section may also have more than two parts. For Example
Class comma { public static void main (string args[ ]) { int i,j; for(i=1 , j=4; i<j ; i++, j--) { system.out.println(i= +i); system.out.println(j= +j); } } }
3) The test condition in the for loop may have any compound relation and the testing need not be limited only to the loop control variable
Chapter 7 - Looping
Nesting of loop i.e., One for statement within another for statement is allowed in java and is illustrated in Fig. 7.6.
Example: class NestedFor { public static void main (String [ ] args) { for (int i = 0; i<5; i++) { for (int j = 1; j<=i; j++) { System.out.print("*"); } System.out.println(i); } } }
89
90
Chapter 7 - Looping
The continue statement causes the flow of control to move to the condition part of the while and dowhile loops. In the case of the for statement, the continue statement causes the flow of control to move to the update expressions part of the for statement before moving to the test condition part.
Class Breakloop { public static void main(string args[ ]) { for(int i=0; i<00; i++) { if (i == 10) break; system.out.println(i =:+i); } system.out.prinln(loop complete); } }
In several instances, such as an error or incorrect input from the user, it may be necessary for the flow of control to exit from a loop statement. To accomplish this, Java provides a jump statement called break. The break statement forces the control to come out from a:
l l l l
After the control moves out of a switch statement or various loop statements, it moves to the statement after the loop statement or the switch statement. Exiting from a loop with a break statement is shown in Fig. 7.7.
91
do {
.............
(d)
92 7.5 SUMMARY
Chapter 7 - Looping
We have covered the loops, continue and break statements in this chapter. Following loop structures were discussed While structure do structure for structure These are useful in developing concise ,compact and structured programs. Break and Continue statements are used to jump or skip out of a loop whenever the need arises.
EXERCISES :
1. Compare in terms of their functions, the following pairs of statements: (a) while and do..while. (b) while and for (c) break and continue. 2. 3. Write a program to compute the sum of the digits of a given integer number Given a number, write a program using while loop ti reverse the digits of the number . For examples, the number is 12345 should be written as 54321 4. Analyze each of the program segments that follow and determine how many times the body of each loop will be executed.
a)
b)
. .
}
93
d) int m = 10 int n= 7; while ( m % n >= 0) { .. m = m + 1; n = n + 2; . }
c)
5.
Chapter 8
OBJECTIVES
A
1 1 1 1 1
define a class create objects add methods to classes extend or reuse a class write application programs
8.0 INTRODUCTION
Java is a true object oriented language and hence all java programs have classes as their underlying structure. Anything we wish to represent in java program must be encapsulated in a class . Class defines the state and behavior of objects . classes create objects. Objects use methods to communicate between them.
8.1 CLASSES
CLASS IS a template that defines a particular type of object. Classes contain all the features of a
94
95
particular set of objects. We can use the class definition to create objects of that of class type, that is, to create objects that incorporate all the features belonging to that class. An instance of a class is another word for an actual object. If the class is the general representation of an object, then an instance is its concrete representation
Syntax of the class declaration class classname { member variable declarations; method declarations; }
Example: You might perhaps define a motorcycle class that describes the features of all motorcycles (has color, make, engineon etc..). The motorcycle class serves as an abstract model for the concept of a motorcycle-to interact with each type of motorcycle ,we should have a concrete instance of that motorcycle. Of course once you have a motorcycle class we can create lots of different instances of that motorcycle. Different motorcycles can have different features .
Variables
Variables are the data types that store data items that typically differentiate one object of the class from another. They are also referred to as data members of a class. Every class you write in Java is generally made up of two components: attributes and behavior. Lets consider an object to define a motorcycle. Attributes are the individual things that differentiate one object from another and determine the state, appearance, or other qualities of that object. The attributes of our motorcycle might include:
l l l
color: red, green, silver, brown. make: Honda, BMW, Bultaco. engineOn: true, false.
96
Attributes are defined by variables, in fact, you can consider them because each instance of a class can have different values for its variables, each variable is called an instance variable.
Instance variables
Each object of the class will have its own copy of each of the instance variables that appear in the class definition. Each object will have its own values for each instance variable. The name instance variable originates from the fact that an object is an instance or an occurrence of a class and the values stored in the instance variables for the object differentiate the object from others of the same class type. An instance variable is declared within the class definition in the usual way, with a type name and a variable name, and can have an initial value specified. Instance variables define the attributes of an object. The class defines the type of the attribute, and each instance stores its own value for that attribute
Class variables
A given class will only have one copy of each of its class variables, and these will be shared between all the objects of the class. The class variables exist even if no objects of the class have been created. They belong to the class, and they can be referenced by any object or class, not just instances of that class. If the value of a class variable is changed, the new value is available in all the objects of the class. This is quite different from instance variables where changing a value for one object does not affect the values in other objects. A class variable must be declared using the keyword static preceding the type name. Look at the following diagram (Fig 8.1), which illustrates the difference between the two: This shows a schematic of a class Sphere with one class variable
Fig. 8.1 Difference between the class variables and instance variables
97
Methods
These define the operations you can perform for the classso they determine what you can do to, or with, objects of the class. Methods typically operate on the fieldsthe variables of the class. A classs behavior determines what instances of that class do when asked to by another class or object. Behavior is the only way that objects can have anything done to them. Our motorcycle class might well have the following behavior:
l l l l
To define an objects behavior you create methods. Methods are functions defined inside classes that operate on instances of those classes The methods in a class definition are named, self-contained blocks of code that typically operate on the variables that appear in the class definition.
98
Class box contains three double type variables.
Class account contains three different types of variables each for acc_no , name and balance. Class motorcycle contains a variables to show the make,color and engine_on, a Boolean variable defined to check whether the engine is on or off.
99
l 1.0
Example 1:
class Box { double width; double height; double length; void getdata( double x,double y, double z) { width = x; height = y; length = z; } double volume( ) } } Example 2: class Sphere { // Class variable to count objects // Radius of a sphere // 3D coordinates // of the center // of a sphere static final double PI = 3.14; // Class variable that has a fixed value static int count = 0; // Instance variables double radius; double xCenter; double yCenter; double zCenter; static int getCount( ){ return count; } // Instance method to calculate volume double volume( ) { return 4.0/3.0*PI*radius*radius*radius; } // Return current object count { return(width*height*length);
100
There are two varieties of methodsinstance methods and class methods. You can execute class methods even when no objects of a class exist, whereas instance methods can only be executed in relation to a particular object, so if no objects exist, there are no instance methods to be executed. Again, like class variables, class methods are declared using the keyword static so they are sometimes referred to as static methods. Since class methods can be executed when there are no objects in existence, they cannot refer to instance variables.. In fact the Java compiler wont let you try. If you reference an instance variable in the code for a class method, it wont compileyoull just get an error message. The method main(), where execution of a Java application starts, must always be declared as static, as you have seen. The reason for this should be apparent by now. Before an application starts execution, no objects exist, so in order to start execution, you need a method that is executable even though there are no objectsa static method therefore. Note that, although instance methods are specific to objects of a class, there is only one copy of an instance method in memory that is shared by all objects of the class, as it would be extremely expensive to replicate all the instance methods for each object. There is a special mechanism that ensures that, each time you call a method the codes executes in a manner that is specific to an object. You can access program code when you do not have an instance of a particular object available. A method that is marked using the keyword static can be used in this way and is called a class method. Methods that are static can be accessed using the class name rather than a reference to an object, as follows:
101
After executing the return statement, the program continues from the point where the method was called. The value, return_value, that is returned by the method, can be any expression that produces a value of the type specified for the return value in the declaration of the method. Methods that return a valuethat is methods declared with a return type other than voidmust always finish by executing a return statement that returns a value of the appropriate type. Note, though, that you can put several return statements within a method if the logic requires this. If a method does not return a value, you can just use the keyword return by itself to end execution of the method: return; // Return from a method Note that, for methods that do not return a value, falling through the closing brace enclosing the body of the method is equivalent to executing a return statement
A parameter has a name and appears in the parameter list in the definition of a method. A parameter defines the type of value that can be passed to the method, and the name that is used to reference it within the code for the method. An argument is a value that is passed to a method when it is executed, and the value of the argument is referenced by the parameter name during execution of the method.
102
Fig. 8.2 parameter passing and returning a value from the method
Here we have the definition of a method Add( ). This can only appear within the definition of a class, but the rest of the class definition has been omitted so as not to clutter up the diagram. You can see that the method has two parameters, value1, and value2, both of which are of type double, that are used to refer to the arguments 3.0 and 5.0 respectively within the body of the method. Since this method has not been defined as static, you can only call it for an object of the class. We call Add( ) in our example for the object, obj. When you call the method from another method (from main( ) in this case, but it could be from some other method), the values of the arguments passed are the initial values assigned to the corresponding parameters. You can use any expression you like for an argument when you call a method, as long as the
103
value it produces is of the same type as the corresponding parameter in the definition of the method. With our method Add( ), both parameters are of type double, so both argument values must always be of type double. The method Add( ) declares the variable result, which only exists within the body of the method. The variable is created each time you execute the method and it is destroyed when execution of the method ends. All the variables that you declare within the body of a method are local to the method, and are only around while the method is being executed. Variables declared within a method are called local variables because they are local to the method. Local variables are not initialized automatically. If you want your local variables to have initial values you must supply the initial value when you declare them.
Creating a object
An object in java is a block of memory that contains a space to store all the instance variables. Creating an object is referred to as instantiating an object. The creating object to a class is two-step Process. 1. decleare a variable of class type. This variable does not define an object instead it is a simply a variable that can refer to an object. 2. physical copy of the object is created and assigned to that variable.
New operator
The object in java is created using the new operator. The new operator dynamically allocates memory for an object and returns a reference to it. This reference is stored in the variable declared. Example: Box mybox Mybox = new Box( ) / / declare a reference to an object of the class //allocate a box object
104
The first line declares mybox as a reference to an object of type box. After the line executes, mybox contains the value null, which indicates that it does not point to the object. The next line allocates an actual object and assigns a reference to mybox. Mybox holds the memory address of the actual box object. Both objects can be combined into one single statement. Box mybox = new Box( ); We can create any number of box objects Box mybox1= new Box( ); Box mybox2=new Box( ); When the above statement is executed each object has its own copy of the instance variables of its class. If any changes are made to the variables of one object, it will have no effect on variables of other.
Height Width
It is possible to create two or more references to the same object. Box b1 = new Box( ); Box b2 = new Box( ); b1=b2; B1 B2 Box object length
105
Here objectname is the name of the object, variablename is the name of the Instance variable inside the object that we wish to access, method name is the Method that we wish to call, and parameter list is a comma separated list of actual values that must match in type and number with the parameter list of the method name declared in the class. Example: For the class Box in the above example we can write the main method and access the methods of the class as follows.
class Boxarea {
public static void main(String args[ ]) { double v1,v2; Box b1= new Box( ); Box b2 = new Box( ); b1.width=2; b1.height=4; b1.length=8; b2.getdata(5,10,15); v1=b1.volume(); v2=b2.volume(); System.out.println("The volume1is = " +v1); System.out.println("The volume2 is= " +v2); } }
Constructors
The central player in object initialization is the constructor. In Java, constructors are similar to methods, but they are not methods. Like a method, a constructor has a set of parameters and a body of code. Unlike methods, however, constructors have no return type. Like methods, you can give access specifiers to constructors, but unlike methods, constructors with public, protected, or package access are not inherited by subclasses. (Also, instead of determining the ability to invoke a method, the access level of a constructor determines the ability to instantiate an object.)
106
In class definitions, constructor methods stand apart from other instance methods in two ways:
l l
Constructor-method names are the same as the name of the class. Constructor methods return new class instances; no return type is specified explicitly To define a zero-parameter constructor for the Box class, you would write the following:
following: No return type specified Constructor name is the same as class name public Box( ) { ... }
In the following program, the Box class definition includes a constructor method that assigns the value 10 to all the instance variables in box instances.
class box { double width; double height; double depth; public box( ) { width=10; height=10; depth=10; } double volume( ) {
return(width*height*depth); } }
Because it uses the new definition of the box class introduced, the following main method does not need to assign values to the instance variables:
107
Class boxvolume { // Define main: public static void main (String argv[ ]) { Box b = new Box( ); double vol; vol = b.volume( ); System.out.println(volume is + vol); } } Result volume is 1000.00 Now, suppose that you want to provide values for the length, width, and height instance variables when you create certain box instances. You should define a constructor with three parameters:
constructor with three parameters: class box { double width; double height; double depth; public box( ) width=10; height=10; depth=10; } public box(double a,double b,double c) width=a; height=b; depth=c; } double volume( ) { { {
108
return(width*height*depth);
} }
Note that the constructor for three parameters, like the one for zero parameters, is named for the class in which it appears. To tell Java to use the three-parameter constructor, blocking the involvement of the zero-parameter constructor, you modify the box creation statement:
Declare b to be a variable of class box Use argument list with three arguments
109
--- Result --The first box volume is 1000.00 The second box volume is 250.00
If you do not define any constructors, Java defines a do-nothing default constructor for you. The default constructor is a zero-parameter constructorThe this keyword: Sometimes a method will need to refer to the object that invoked it. To allow this java defines the this keyword. This can be used inside any method to refer to the current object. ,i.e .,this is always a reference to the object on which the method was invoked.
Example 1: Box(double a,double b,double c) { this.width=a; this.height=b; this.depth=c; } Example 2: public class Class2 { String name; int age; public Class2( ) { name = "Rahul"; age = 39; } public void printName( ) {
System.out.println( "The name of this object is " + name ); } } public class Class3 { S i
110
String name; int age; public Class3( String name, int age ) { this.name = name; this.age = age; } public void printName( ) {
Defining classes
The basic syntax for defining a class in Java is class class-name { data-declarations
111
constructors methods }
Example : Class Student { String name; int mark; String option; Student(String nm) { name=nm; } public void setMark(int m) { mark = m; } public int getMark( ) { return(mark); } public void chooseOption(String m) { option = m; } public String getOption( ) { return(option); } }//Student
112
113
From the main method we can call the add method which is in class add. The add method is selected form the four depending on the number and type of the parameter passed to the method. Ob.add(2,3) // calls the add method with two integer parameter Ob.add(2,3,4)//calls the add method with three integer parameters Ob.add(3.0,4.0)//calls the add method with two double type parameters Ob.add(3.0,4.0,5.0)//calls the add method with three double type paramethers.
114
System.out.println(The value is +x); } void show(int a,int b) { int c = a*b; System.out.println(The value is +c); } public static void main(String args[ ]) { Overload over = new Overload( ); over.show(50); over.show(60,70); } }
Output
The value is 50 The value is 4200
Defining a subclass
A subclass is defined as follows Class subclass extends superclass {
115
Variables declaration; Methods declaration; } The keyword extends signifies that the properties of superclassname are extended to the subclassname. The subclass will now contain its own variables and methods as well those of the superclass. This kind of situation occurs when we want to add some more properties to existing class without actually modifying it In the following example we have a base class called book which consists of name of the book, id of the book and a method to display. Further we want to add variable author name to the book with existing properties so we have created a derived class book1 in which we will add the variable author and a method to display the author. Now this derived class will contain the properties of the base class including its own property.
import java.io.*; //super class declaration class book { String name; int id; void showsuper( ) { System.out.println("the id and name of the book is :" +id+ " " } } class book1 extends book { String author; void showderived( ) { System.out.println("the author name is: +author); +name);
116
} } class simpleinhertence {
public static void main(String args[ ]) { book superob=new book( ); book1 subobj = new book1( ); superob.id=10; superob.name="java"; System.out.println("the contents of super object is"); superob.showsuper( ); System.out.println( ); subobj.id=20; subobj.name=c programming; subobj.author=Balaguruswamy; System.out.println(the contents of the subobj:); subobj.showsuper( ); subobj.showderived( ); } }
Result
The contents if super object is
117
The id and name of the book is: 10 java The contents of the subobj: The id and name of the book is : 20 c programming The autor name is: Swamy As you see, the subclass book1 includes all the members of its superclass, book. This is why subob can access the id and name and call showsuper. Even though book is a superclass of book1 it is also a completely independent stand-alone class. Being a superclass for a subclass does not mean that superclass cannot be used by itself. The general form of class declaration that inherits the a superclass is shown here: Class subclass-name extends superclass-name { body of the class }
Subclass constructors
A subclass can call constructor method defined by its superclass by use of the Following form of super Super(paramether_list); Here parameter_list specifies any parameters needed by the constructors in the superclass. Super( ) must always be the first statement executed inside a subclass constructors. To see how the super is used, consider our previous example class box . Now create a boxweight class which extends the box class with variable weight in it. Now define a constructor boxweight ,this constructor calls super( ) with parameters w,h,d this causes the box constructor to be called ,which initializes width,height and depth using these values. Boxweight no longer initializes these values itself. It only needs to initialize the value unique to it. ,i.e ,weight version of the boxweight class Class boxweight extends box { double weight; boxweight(double w,double h,double d,double m){ super(w,h,d); weight=m; } }
118
Method Overriding
In the class hierarchy, when a method in a subclass has the same name and type signature as method in the superclass, then the method in the subclass is said to override the method in superclass. class Book { //super class defined String name = JAVA PROGRAMMING ; int id = 34567; void show ( ) { System.out.println( Book name is +name); System.out.println( Book id is +id); } } Save this file as book.java and compile. This is our Base Class class Book1 extends Book { // This is the subclass String author = micheal janson; void show ( ) { System.out.println( Book name is +name); System.out.println( Book id is +id); System.out.println( The author name is +author); } public static void main(String args[ ] ) { Book1 x = new Book1( ); x.show(); } } Save this file as book1.java.This is our derived class. Compile and execute the derived file. You can see the three outputs. Note that the first two print statements in the derived class is inherited from book class (Base Class). We have not declared the variables in them in the derived class Methods in the derived class can have same name as that of the base class. If you are having one base class called book and two derived class called book1 and book2 and if you use same methods in all the three classes, then the last derived class method is executed although there are methods with similar names in all the former classes. This concept in Java is called as Method Overriding. If you want to display the details of base class and that of derived class in the above context, then super keyword is used in each derived classes after the method definition.
119
Class Attributes
Sometimes it is desirable to have a variable that is shared among all instances of a class. For Example this can be used as the basis for communication between instances or to keep track of the number of instaces that have been created We can achieve this effect by making the variable with the keyword static .such variable is sometimes called a class variable to distinguish it from a member of instance variable, which is not shared. Public class Count{ Private int serialNumber; Public static int counter=0; Public count(){ Counter++; seraialNumber=counter; } } in this example,every object that is created is assigned a unique serial number, starting at 1 and counting upwards.The variable counter is shared among all instances, so when the constructor of one object increments counter,the next object to be created recives the incremented value. A static variable is similar in some ways to global variable in other languages.The java programming language does not have global as such, but a static variable is a single variable accessible form any instance of a class. If static variable is not marked as private,you can access it from outside the class.To do this,you do not need an instance of a class,you can refer to it through the class name. Public class otherclass{ Public void incrementNumber() { Count.counter++; } }
120
Class Methods
Static method can be accessed without creating a instace of a particullar object.a method that is marked as static method using the keyword static which is shown in the following diagram. Public class Count{ Private int serialNumber; Public static int counter=0; Public static int getTotalCount() { return counter; } Public count(){ Counter++; seraialNumber=counter; } } We should access the methods that are static using the class name rather than an object reference, as follows: Public class TestCounter{ Public staic void main(String args[]) { System.out.println(Number of counter is + Count.getTotalCount()); Count count1=new Count(); System.out.println(Number of counter is + Count.getTotalCount()); } The output of the Test Counter program is: Number of counter is 0 Number of counter is 1
121
Final int size = 100; Final void showstatus( ) {} Making a method final ensures that the functionality defined in this method will never be altered in any way. Similarly, the value of a final variable can never be changed. Final variables, behave like class variables , and they do not take any space on individual objects of the class.
Final classes
Sometimes we may like to prevent a class being further subclassed for security reasons. A class that cannot be subclassed is called a final class. This is achieved in java using the keyword final as follows. Final class aclass {..} Final class bclass extends someclass {} Any attempt to inherit these classes will cause an error and the compiler will not allow it. Declaring a class final prevents any unwanted extensions to the class. It also allows the compiler to perform some optimizations when a method of final class is invoked.
Finalizer methods
We have seen that a constructor method is used to initialize an object when it is declared. this process is known as initialization. Similarly, java supports a concept called finalization, which is just opposite to initialization. We know that java run time is an automatic garbage collecting system. It automatically frees up the memory resources used by the objects. But objects may hold other non-object resources such as file descriptors or window system fonts. The garbage collector cannot free these resources. In order to free these resources we must use a finalizer method. This is similar to destructors in C++. The finalizer method is simply finalize ( ) and can be added to any class. Java calls that method whenever it is about to reclaim the space for that object. The finalize method should explicitly define the tasks to be performed.
122
abstract void draw ( ) ; . ..
When a class contains one or more abstract methods, it should also be declared abstract as shown in the example above. While using abstract classes, we must satisfy the following conditions: We cannot use abstract classes to instantiate objects directly. For example, Shape s =new shape ( ) ;
Is illegal because shape is an abstract class. The abstract methods of an abstract class must be defined in its subclass. We cannot declare abstract constructors or abstract static methods.
Access Modifiers
Access to variables and methods in Java classes is accomplished through access modifiers. Access modifiers define varying levels of access between class members and other objects. Access modifiers are declared immediately before the type of a member variable or the return type of a method. There are four access modifiers
l l l l
The default access modifier specifies that only classes in the same file or package have access to a classs variables and methods. There is no actual keyword for declaring the default access modifier; it is applied by default in the absence of any other modifier. For example, in our MotorMain program all the variables and methods in the MotorCycle class had default access because no access modifiers were specified. The class MotorMain could however see and use all these variables and methods because the two classes are part of the same file (and hence the same default package). The public access modifier specifies that class variables and methods are accessible to anyone, both inside and outside the class. This means that public class members have global visibility and can be accessed by any other object. For example: if you declared the variable named x as public int x = 20; , then the value of x will be visible to all the other classes of the same program. public int count; public Boolean isActive;
123
The protected access modifier specifies that class members are accessible only to methods in that class and subclasses (dont worry we deal with subclasses later) of that class. This is same, as Public but it will give more protection than the public. If Protected is used then all the methods and attributes of the base class will be available to all its derived classes Protected int count; Protected Boolean isActive; The private access modifier is the most restrictive; it specifies that class members are accessible only by the class in which they are defined. this means that no other class has access to private class members. For example: private int y = 100; means the value of y will be visible only to the class it is defined. If you try to access the variable in other classes then the compiler will return an error.
8.7 SUMMARY
In this chapter, we have discussed classes, objects and methods which are the basic components used in java programming we have discussed in detail
l l l l l
How to define a class How to create objects How to add methods to classes How to reuse a class and How to write application programs
Concepts discussed here provide the basics for writing both stand alone application programs and applets.
EXERCISES
1. 2. 3. 4. 5. 6. What is class? How does it accomplish data hiding? How do classes help us to organize our programs? What are objects? How are they created from a class? How is a method defined? When do we declare a member of a class static? What is a constructor? What are its special properties?
124
7. 8. 9. 10. How do we invoke a constructor?
What is inheritance and how does it help us create new classes quickly? Describe different forms of inheritance with examples. Design a class to represent a bank account. Include the following member: Data members
1 1 1 1
Name of the depositor Account Number Type of account Balance amount in the account
Methods
1 1 1 1
To assign initial values To deposit an amount To withdraw an amount after checking balance To display the name and balance
11.
Assume that a bank maintains two kinds of account for its customers, one called savings account and the other current account. The savings account provides compound interest and withdrawal facilities but no cheque book facility. The current account provides cheque book facility but no interest. Current account holders should also maintain a minimum balance and if the balance falls below this level, a service charge is imposed. Create a class Account that stores customer name, account number and the type of account. From this derive the classes Curr-acct and Sav-acct to make them more specific to their requirements. Include the necessary methods in order to achieve the following tasks: i. ii. iii. iv. v. Accept deposit from a customer and update the balance. Display the balance. Compute and deposit interest. Permit withdrawal and update the balance. Check for the minimum balance, impose penalty, if necessary and update the balance. Do not use any constructors. Use methods to initialize the class members.
Chapter 9
OBJECTIVES
A
1 1 1 1
What is an array in Java How arrays are used What is a string How to use string classes
9.0 INTRODUCTION
An array is a sequence of logically related data items. It is a kind of row made of boxes, with each box holding a value. The number associated with each box is the index of the item. Each box can be accessed by, first box, second box, third box, and so on, till the nth box. The first box, or the lowest bound of an array is always zero, that means, the first item in an array is always at position zero of that array. Position in an array is called index. So the third item in an array would be at index 2 (0, 1,2);
125
126
One-dimensional array is a data structure which allows a collective name to be given to a group of elements which all have the same type. An individual element of an array is identified by its own unique index (or subscript). The indices will be consecutive integers running from a start value to a finish value, (Fig 9.1).
An array element is one of the values within an array and is accessed by its position within the array In Java, arrays can be of a single type like integers, Strings, float, double and so on. For example, consider the following two statements. int array = new int [5] means array is assigned 5 memory locations in the computer (Fig. 9.2). int comp[ ] = {10,20,30}; means the variable comp is assigned the values 10,20,30 Reserve five storage locations as shown below
127
1 1
128
Diagrammatically this can be represented as follows:
points nowhere
0 1 2 3 4 5 6 7 8 9
The number of elements in the array must be specified by an integer constant or an integer expression. The numbering of the indices of an array commence at zero. Thus an n element array will have indices ranging from 0 to n-1. The elements of the array will be assigned the default value associated with the data type of the array elements.
In the example above the data type is numeric so the default value is zero and it is a ten element array so the subscripts run from 0 to 9. We illustrate how storage can be allocated and initialized to specific values by example. The following example declares and initializes an array which holds the number of days in each of the twelve months of the year. Int [ ] daysInMonth = {31,28,31,30,31,30.31,31,30,31,30,31}; This allocates space for a twelve element array called daysInMonth and initializes the elements in order so that the element with index 0 holds 31, the element with index 1 holds 28, etc. Note that the
129
function new is not required when initializing an array in this way. When an array is initialized like this its size is set to the number of values that are contained within the curly brackets. Thus the array daysInMonth has size 12. The effect of this declaration and initialization is illustrated in Fig. 9.4.
Alternatively allocation and initialization could have been separated from declaration as follows: Int [ ] daysInMonth; daysInMonth = new int[ ] {31,28,31,30,31,30.31,31,30,31,30,31};
type[ ] A;
Declares A as an array variable of type. No storage allocated for the elements of A. Reference variable for A holds null.
1
Declares A as an array variable of type and allocates storage to store size array elements. These elements are initialized to the default value for the type. The reference variable for A points to the allocated storage.
1
Declares A as an array variable and allocates storage of size equal to the number of values. This storage is initialized to the given values.
1
A = new type[size];
Allocates storage for the array A sufficient for size elements of type. Elements initialized to default values for type. A must have previously been declared as an array variable.
130
1
Allocates storage of size equal to the number of values and initializes it to the default values for type. A must have previously been declared as an array variable. String as an array: A string variable is, in reality, an array. So, if we have var myname = Rahul; then myname[0] has R, myname[1] has a, and so on. In a similar way, we can initialize every index position of an array. For instance: var myname = new Array(5); //In this way we declare an array. myname[0 ]= R; myname[1] = a; myname[2] = h; myname[3] = u; myname[4] = l; //It seems we have just filled till the index 4, but the dimension //can be any number, as long as you dont try to assign //a value to an index that does not exist.
//The following for(){} loop displays the array. for(n=0; n<5; n++) { System.out.println( myname[n]); System.out.println(); } }
131
Output
R a h u l
public static void main(String[ ] args) int[ ] anArray; anArray = new int[10];
// assign a value to each array element and print for (int i = 0; i < anArray.length; i++) anArray[i] = i; System.out.print(anArray[i] + " "); } {
132
System.out.println(); } } Output : 0 1 2 3 4 5 6 7 8 9 0
133
When a primitive variable is declared, memory space is allocated for it, however no value is assigned to that memory space until the variable is initialized. Similarly when a reference variable is declared memory space sufficient to hold a reference is allocated to it. This memory is assigned the value null to indicate that as yet there is no information associated with this reference variable. Only when the reference variable is initialized will space be allocated for the actual information associated with the variable and the reference be updated to reference this space.
The rectangular matrices have usually the following form: Int a [ ][ ]=new int [3][4]; This declaration specifies that the matrix created have 3 rows and 4 columns. The index number for columns and rows starts at 0. The elements from the first row are at the next positions (A [0][0], a [0][1], a [0][2] and a [0][3]) Elements from the second row are at the next positions: (A [1][0], a [1][1], a [1][2] and a [1][3].) and elements from the third row are at the next positions: (A [2][0], a [2][1], a [2][2] ski a [2][3].). To find out the no of rows in a matrix: M=a. length; To find out the length of the first row N1=a [0]. Length;
134
To find out the length of the second row: N2=a [1]. Length;
Two-dimensional arrays are objects. A variable such as myArray is a reference to a 2D array object. The declaration Int [ ][ ] my Array; Says that my Array can hold a reference to a 2D array of int. without any further initialization, it will start out holding null. The declaration int[ ][ ] myArray = new int[3][5] ; Says that myArray can hold a reference to a 2D array of int, creates an array object of 3 rows and 5 columns, and puts the reference in myArray. All the elements of the array are initialized to zero. The declaration int[ ][ ] myArray = { {0,0,0,0,0}, {0,0,0,0,0}, {0,0,0,0,0} }; does exactly the same thing as the previous declaration (and would not ordinarily be used.) The declaration int[ ][ ] myArray = { {8,1,2,2,9}, {1,9,4,0,3}, {0,3,0,0,7} }; Creates an array of the same dimensions (same number of rows and columns) as the previous array and initializes the elements to specific values.
135
One way to create row 0 is this: myArray[0] = new int[3] ; // 3. This creates a 1D array object and puts its reference in slot 0 of myArray. The elements of the 1D array are initialized to 0. A previously constructed 1D array can be assigned to a row: int[ ] x = {0, 2}; int[ ] y = {0, 1, 2, 3, 4} ; myArray[1] = x ; myArray[2] = y ; // 4.
136
2D Array of int
The following program creates a 2D array of int that implements the gradeTable example. Details about declaring and constructing 2D arrays will be explained later.
Row Col 0 99 0 90 1 88 2 61 3 93 4 50 5 43 6 gradeTable
1 42 91 61 89 73 65 98
2 74 72 74 82 75 92 78
3 83 88 89 98 78 87 56
4 100 95 96 93 99 94 99
class gradeExample { public static void main( String[ ] arg ) { // declare and construct a 2D array int[ ][ ] gradeTable = { {99, 42, 74, 83, 100},
137
{90, 91, 72, 88, 95}, {88, 61, 74, 89, 96}, {61, 89, 82, 98, 93}, {93, 73, 75, 78, 99}, {50, 65, 92, 87, 94}, {43, 98, 78, 56, 99} };
The subscripted variables are used in assignment statements and arithmetic expressions just like any variable:
138
gradeTable[ 0 ][ 1 ] = 33 ; // puts a 33 into row 0 column 1. gradeTable[ 3 ][ 4 ]++ ;
9.5.1. Constructors
l
The default constructor takes a single string constant as its only argument. String myString = new String( Hello World );
You may use the shorthand notation, familiar to many other programming languages, which invokes the same String() constructor. String myString = Hello World;
139
Example 2: class StringEx2 { public static void main(String[ ] args) { String name = "Java" System.out.println(name); } } Output : Java Strings in Java are objects. As with any object, we work with strings by means of reference variables. However, strings are a little unusual in that the compiler knows more about strings than other types of objects and allows us to do some things with strings that are not possible with other objects. One simple example of this is shown in the following code fragment:
1 .String str = Hello; 2 .System.out.println(str); //output the string In line 1 we are creating a new object, but we havent used the new operator. The reason for this is that the compiler automatically creates the necessary String objects to represent the string literals used in a program (like Hello here). What we have after line 1 is the usual situation with references to objects, which we can picture as shown in the following figure.
140
If we now execute the statement: str = Wells; we get the picture as shown in the Fig. 9.7.
The question is now: what happens to the original string (containing Hello)?. The answer is that it is now out of the reach of our program, as there is no longer any reference variable that refers to it. As such it is referred to as garbage: memory that our program was using to store an object but which is no longer required. Most languages that support dynamic memory allocation like this require that the programmer keeps track of the memory being used. Thus it is the programmers responsibility to ensure that the program deallocates the memory used by an object once it is no longer required. This is a notorious source of programming errors in many programming languages, not least C++. Fortunately for us, Java has a very powerful and useful feature called automatic garbage collection. The Java run-time system keeps track of the references to the objects that the program is using and will automatically reclaim any memory that is no longer being used by the program (such as that being used by the Hello object above). Another important fact to bear in mind with Java strings is that they are immutable. This means that the contents of the object cannot be changed after the object has been created. To put it another way: it is impossible to edit or modify a string object in Java. Of course, it is possible to make a String reference variable refer to another object with different contents, but the original object is never changed.
141
It returns true if the string contains the same characters in the same order and false Otherwise.
compareTo( )
Often, it is not enough to simply know whether two strings are identical. For sorting applications, we need to know which is less than, equalto, or greater than the next.The string method compareTo( ) serves this purpose. It has the general form int compareTo(String str) Value Meaning
the invoking string is less than str the invoking string is greater than str the two string are equal
Class equalsdemo { public static void main(String args[ ]) { String s1=Hello; String s2=Hello; String s3=bye; System.out.println("COMPARE STRINGS"); // The compareTo method System.out.println(s1 + equals + s2 + -> + s1.eqals(s2)); System.out.println(s1 + equals + s3 + -> + s1.eqals(s3)); // Using the compareTo method within an if-else statement if (name1.compareTo(name2)==0) System.out.println("the same"); else System.out.println("not the same"); } }
The difference between equals and == The equals method can be considered to perform a deep comparison of the value of an object, whereas the == operator performs a shallow comparison. The equals method compares what an object points to, rather than the pointer itself. The == operator compares whether two objects are exactly the
142
same object, meaning that they reference the same spot in memory, NOT that the values of the parameters of the object are the same. So if you declare String s1 = This is a String.; String s2 = s1; It is assured that (s1 == s2) is true, since s1 and s2 reference the same String at the same location in memory. However, if you had: String s1 = new String(This is a String.); String s2 = new String(This is a String.); It is assured that (s1 == s2) is NOT true, since you created two different Strings using the new operator, and they definitely do not reference the same object, even though the contents of the String are the same. The equals() method, on the other hand, does the operation you probably intend to do, comparing the contents of the two strings and seeing if they match. Usually you will want use the equals method. Class stringDemo { public static void main(String args[]) {
/* Compare two Strings */ String firstString = "Java programming"; String secondString = "Java programming";
/* Compare two Strings */ firstString = new String("Java programming"); secondString = new String("Java programming");
143
charAT( )
To extract a single character from the string. We can refer directly to an individual character via the charAt() method. It has the general form Char chatAt(int where) Here where is the index of the character that we want to obtain. ChatAt( ) returns the character at the specified location
String length
The length of a string is the number of characters that it contains. To obtain this value call a length method
int length(); class strCmp { public static void main (String args[ ]) String str = "Hello"; String str2 = "Java";
System.out.println (str.equals(str2)); // false System.out.println (str.compareTo(str2)); // a negative number, str is less than str2 System.out.println (str.charAt(0)); // H, i.e. char is position 0 System.out.println (str.length() + str2.length()); // 5 + 4 = 9 } }
i.e.
144
Concatenation of two strings
String manipulation is something we do quite often in our applications . One of the simplest methods to concatenate two Strings is by using the + operator. To append String s2 to s1 we simply use: s1 += s2 But Java provides more ways for concatenating Strings. The String class contains a instance method named concat(String s). To add a new String to a existing String we would code something like this: s1.concat(s2); public class Test { public static void main(String arg[ ]) { // defining two strings and printing them out String s1 = new String(sachin); String s2 = new String(tendulkar); System.out.println(First String: + s1); System.out.println(Second String: + s2); // adding the second string to the first and printing result s1 = s1.concat(s2); System.out.println(Concatenated: + s1); } } Output First String : Sachin Second String : Tendulkar Concatenated : Sachin Tendulkar
Conversions
l
toLowerCase( ) returns a newly minted string identical to the original, but with all upper case characters cast to lower case. toUpperCase( ) returns a newly minted string identical to the original, but with all lower case characters cast to upper case.
Replace method
The replace method is used to replace each occurrence of the first argument in a string with the second argument the general form of the replace method is
145
String replace(char original, char replacement) Here the original specifies the character to be replaced by character specified by replacement
Substring method
The subString method is used to create new instances of the class String from existing instances. The new string is specified by giving the required index range within the existing string string substring(int startIndex) This returns the sub string that starts at startIndex and runs to the end of the invoking string. string substring(int start Index, int endIndex) This returns the substring that starts at startindex and runs through endIndex-1;
Trim method
The trim method returns a copy of the invoking string from which any leading and trailing white space has been removed. It has the general form String trim ( ); class altStr{ public static void main (String args[ ]) String str = Hello; String str2 = Java; str = str.toUpperCase(); str2 = str2.toLowerCase(); System.out.println (str); // HELLO System.out.println (str2);// java str = str.concat(str2); // str now equals HELLO java System.out.println (str); str = str.trim(); // str now equals HELLOjava System.out.println (str); str = str.substring (5,str.length()); // str = java System.out.println (str); str = str.replace (a, i); // str = jivi System.out.println (str); } } {
In this chapter, two important java data structures namely arrays and strings were discussed we learnt arrays and their usage, and , strings and their usuage. Some examples to illustrate where these structures can be used was also highlighted.
EXERCISES
1. 2. 3. What is an array? Why are arrays easier to use compared to a bunch of related variables? Write a statement to declare and instantiate an array to hold marks obtained by students in different subjects in a class. Assume that there are up to 60 students in a class and there are 8 subjects. Find errors, if any, in the following code segments: int m; int x[ ] =int [10]; int [ ] y =int [11]; for (m=1;m<=10; ++m) x[m]=y[m]=m; x=y=new int[20]; for (m=0 ; m<10; ++m) system.out.println(x[m]) 5. An election is contested by 5 candidates. The candidates are numbered 1 to 5 and the voting is done by marking the candidate number on the ballot paper. Write a program to read the ballots and count the votes cast for each candidate using an array variable count. In case, a number read is outside the range 1 to 5, the ballot should be considered as a spoilt ballot and the program should also count the number of spoilt ballots. Two matrices that have the same number of rows and columns can be multiplied to produce a third matrix. Consider the following two matrices.
4.
6.
The product of A and B is a third matrix C of size b by n where each element of C is given by the following equation. Write a program that will read the values of elements of A and B and produce the product matrix C.
147
7. 8.
How does String class differ from the StringBuffer class? Explain about : 1. 2. Comparision of two strings Concatenation of two strings
9.
Chapter 10
Multithreading
OBJECTIVES
A
1 1 1
10.0 INTRODUCTION
It is nice if we can do one thing at a time and do it well. However, this is not the way the world works. For example, the human body performs a variety of operations in parallel or concurrently. Similarly, all of the senses seeing, touching, smelling, hearing etc., can occur concurrently. Computers, too perform operations concurrently. A computer can concurrently compile a program, print a file and receive e-mail over a network. Most programming languages do not help programmers to specify concurrent activities. They generally provide a simple set of control structures that allow programmers to perform one action at a time. Among popular, general purpose programming languages Java is unique in that it provides concurrency primitives. The programmer specifies that applications contain threads of execution. Each thread earmarks a portion of program that can be executed concurrently with other threads. This capability of Java language is called multithreading. This facility is not available in C and C++ on which Java is based.
148
Chapter 10 - Multithreading
Examples of concurrent programming: When programs download large files of audio or video clips from WWW, one need not wait until the entire clip is downloaded before starting the playback. He can put multiple threads to work. In C and C++, the responsibility of reclaiming dynamically allocated memory rests with the programmer. However, Java provides a garbage collector thread that reclaims dynamically allocated memory automatically.
A process is a program executing within its own address space. A thread is a single stream of execution within a process.
Thread is the smallest unit of dispatchable code and is a sequence of code executing within a process. Threads cannot execute on their own; they require a parent process to run. Within each process , there are a variety of threads executing. For example, Word may have a thread in the background automatically checking the spelling of what is being written, while another thread may be automatically saving changes to the document. Like Word, each application (process) can be running many threads that are performing a number of tasks. The significance here is that threads are always associated with a particular process.
Chapter 10 - Multithreading
Single threaded systems use an approach called an event loop with polling. In this model, a single thread of control runs in an infinite loop, polling a single event queue to decide what to do next. Once this polling mechanism returns with, say, a signal that a network file is ready to be read, then the event loop dispatches control to the appropriate event handler. Until this event handler returns nothing else can happen. This wastes CPU time. The benefit of Javas multithreading is that the main loop/polling mechanism is eliminated. One thread can pause without stopping other parts of the program. For example, the idle time created when a thread reads data from a network or waits for user input can be utilized elsewhere. When a thread blocks in a Java program, only the single thread that is blocked pauses. All other threads continue to run.
151
Active Thread
Dead
Killed Thread
Stop yield
A thread can voluntarily relinquish control When this happens all other threads are examined and the highest priority thread that is in runnable state is given to C.P.U.
152
l
Chapter 10 - Multithreading
A thread can be preempted by a higher priority thread. A lower priority thread that does not yield the processor is simply preempted. This is called preemptive multitasking.
It is the thread from which other child threads will be created It must be the last thread to finish execution. When the main thread stops, the program terminates.
153
A thread can also query for its own name in the same way: System.out.println(My name is + this.getName());
Chapter 10 - Multithreading
To create classes that make use of threads, you can extend the class Thread or implement the interface Runnable. Both yield the same result. By implementing Runnable, existing classes can be converted to threads without having to change the classes on which they are based.
Class MyThread extends Thread { } Now we have a new type of thread MyThread
155
} when we start the new thread, java calls the threads run() method.where all the action takes place.
Chapter 10 - Multithreading
We can create threads in two ways: one by using the extended Thread class and another by implementing the runnable interface. We have already discussed in detail how the thread class is used for creating and running the threads. In this section, we shall see how to make use of the Runnable interface to implement threads. The Runnable interface declares run() method that is required for implementing threads in our program. This is done as follows: 1. Declare the class as implementing the Runnable interface. 2. Implement the run() method. 3. Create a thread by defining an object that is instantiated form this runnable class as the target of the thread. 4. Call the threads start() method to run the thread Following program illustartrates the implementation of the above steps. In main method , we first create an instance of x and then pass this instance as the initial value of the object threadX(an object of Thread class).Whenever ,the new thread threadx starts up, its run() method calls the run() method of the target object supplied to it. Here the target object is runnable. Class x implemtns Runnable { public void run() { for(int i=1; I<=5 i++) { System.out.println(\t threadX: +I); } System.out.println(End of ThreadX); } }
157
X runnable = new X(); Thread threadX = new Thread(runnable); ThreadX.start(); System.out.println(End of main Thread); } } Output of the program End of the main Thread ThreadX: 1 ThreadX: 2 ThreadX: 3 ThreadX 4 ThreadX: 5
10.6 SYNCHRONIZATION
Multithreading introduces a synchronous behavior in programs. There is a need to enforce synchronicity when it is necessary. For example, if two threads are to communicate and share a data structure, there is a need to avoid conflict between them. That is, a thread must be prevented from writing data while the other thread is reading the data. To overcome this problem, Java implements a model of interprocess communication called monitor. The monitor is a control mechanism that can hold only one thread at a time. Once a thread enters a monitor, all other threads have to wait until that exits from the monitor.
10.7 MESSAGING
After we divide our program into separate threads, we need a method by which the threads communicate with each other. In Java, two or more threads can talk to each other, via calls to predefined methods that all objects have.
10.8 SUMMARY
A thread is a single line of execution within program. Multiple threads can run concurrently in a single
158
Chapter 10 - Multithreading
program. A thread is created either by subclass in thread class or implementing a runnable interface. Careful application of multithreading will improve the execution speed of java programs.
EXERCISES
1. 2. 3. 4. 5. What is a Thread? Distinguish between Multiprocessing and Multithreading? Describe the life cycle of a Thread? What is Synchronization? Why do we use it? How a thread is created?
159
Chapter 11
OBJECTIVES
A
1 1 1 1
Create a package Add more classes to a package Access contents of a package Use java system packages
11.0 INTRODUCTION
Packages are containers for classes that are used to keep the class name space compartmentalized. For example, a package allows us to create a class named list, which we can store in our own package without concern that it will collide with some other class named list stored elsewhere. Packages are stored in a hierarchical manner and are explicitly imported into new class definitions. Packages, a concept similar to class libraries in other languages helps in achieving the reusability. Packages are Javas way of grouping a variety of classes and/or interfaces together. The grouping is done according to functionality. By organizing the classes into packages, we get the following benefits. 1. Classes contained in packages of other programs can be reused.
159
160
2. Two classes in two different packages can have the same name. 3. Packages provide a way to hide classes. 4. Designing is separated from coding by use of packages. This is achieved by first designing classes and their relationship and then implementing the Java code needed for methods.
// class definition
Here the package name is first package. The class First class now a part of the package. The listing would be saved as a file called Firstclass.java. It is located in a directory named firstpackage. When the source file is compiled, Java will create a class file and store it in the same directory.
Package Packagename;
2. Define the class that is to be put in the package and declare it public. 3. Create a subdirectory under the directory where the main source file are stored.
161
4. Store the listing as the classname.java file in subdirectory. 5. Compile the file. This creates .class file in subdirectory. As stated earlier, Java also supports the concept of package hierarchy. Specifying multiple names in a package statement separated by periods does this. The general form of a multileveled package statement is shown here Package pkg1 [pkg2 [pkg3]]; For example, a package declared as Package java.awt.image; needs to be stored in java/awt/image, java/awt/image or java:awt:image on UNIX, windows or Macintosh file system.
162
Package package 1; Public class Class A; { Public void display A( ) { System.out.println(class A); } }
This source file should be named classA.Java. It is stored in subdirectory package1. This Java file is compiled. Resultant is classA.class. This will be stored in the same subdirectory. Now consider the listing import package1.classA; class packageTest1 { Public Static Void main(String args[ ] { class A object A = new class A( ); object A.displayA( ); } } The above is a simple program that imports the class.calssA from package1. The source file should be saved as PackageTest1.Java and then compiled. The source file and the compiled file should be saved in the directory of which package1 is a subdirectory. Now, the program can be run to obtain the results.
Subclasses in the same package Non subclasses in the same package Subclasses in different packages Classes that are neither in the same package nor subclass.
The three access specifiers private, public and protected provide a variety of ways to produce many levels of access required. Table No.11.1 sums up the interaction.
163
No modifier Yes Yes Yes No No Protected Yes Yes Yes Yes No Public Yes Yes Yes Yes Yes
Same class Same Package Subclass Same Package Non-Subclass Different Package Subclass Different Package Non-Subclass
Private Yes No No No No
We have discussed about classes and how they can be inherited by other class in chapeter 8. Java does not support multiple inheritence. ,i.e, classes in java canot have more than one superclass. However, most of the real life applications require the use of multiple inheritence where by a class inherits methods and properties from several distinct classes. Java provides an alternate approach called interfaces to support the concept of multiple inheritence. interfaces are syntactically similar to classes but they lack instance variables, and their methods are declared without any body. In practice, we can define interfaces which dont make assumptions about how they are implemented.once it is defined, any number of classes can implement an inferface. Also one class can implement any number of interfaces. An interface only defines a methods name, return type, and arguments. It does not include executable code or point to a particular method. Think of an interface as a template of structure.
Declaring an Interface
An interface is declared in much the same manner as a class, but instead uses the interface keyword instead of the class keyword: Interface InterfaceName { Variables decleration; Mehods decleration; } The interface body is declared between the curly braces. The body of an interface consists of declarations for variables and methods.
Modifiers
The same modifiers-public and default-available to classes can be applied to an interfaces declaration. The default is nonpublic, which means accessible by any member of a given package. Most interfaces are public because interfaces are the only means to share variable and method definitions between different packages. Here is an example of a public interface declaration: public interface AnInterface { ... //body of interface } Variables and methods declared inside an interface also have modifiers associated with them. However, the modifiers are limited to particular combinations for variables and methods.
165
Modifiers for variables are limited to one specific set: public static final. In other words, variables declared in interfaces can only function as constants. Public static final are the default modifiers. It is not necessary to declare the modifiers explicitly, but it makes the code more self-documenting. Trying to assign other modifiers such as protected results in a compile-time error. Here are examples of variable declarations: public static final float pie = 3.14159; public static final String = The quick brown fox; Modifiers for methods are limited to one specific set as public abstract, meaning that methods declared inside an interface can only be abstract. These are the default modifiers for methods. It is not necessary to declare them explicitly, but once again, it makes the code easier to read. Trying to assign other modifiers, such as protected, results in a compile-time error. Here are example interface method declarations: public abstract boolean isBlack(Color); public abstract boolean isBlack(String); public abstract StringBuffer promptForName(String); As you can see in this example, overloaded methods can be declared in an interface just as in a class. An entire interface based on these examples follows: public interface MyInterface { public static final int smtpSocket = 25; public static final float pie = 3.14159; public static final String = The quick brown fox; public abstract boolean isBlack(Color); public abstract boolean isBlack(String); public abstract StringBuffer promptForName(String); } Interfaces also can extend other interfaces, just as classes can extend other classes, using the extends keyword. In the following code, the interface AnInterface declares a variable named theAnswer: public interface AnInterface { public static final int theAnswer = 42; } public interface MyInterface extends AnInterface { public static final int smtpSocket = 25; public static final float pie = 3.14159;
166
public static final String = The quick brown fox; public abstract boolean isBlack(Color); public abstract boolean isBlack(String); public abstract StringBuffer promptForName(String); }
The interface MyInterface specifies that it extends AnInterface. This means that any classes that use MyInterface will have access to not only the variables and methods declared in MyInterface, but also those in AnInterface. You can also list multiple interfaces after the extends keyword. Multiple, possibly disparate, interfaces can be combined into a logical whole if desired, as in the following: public interface MyInterface extends Interface1, Interface2 { body of interface }
Implementing interfaces
Interfaces are used as uperclasses whose properties are inherited by classes. It is therefore necessary to create Class classname implements Interfacename { body of classname; } Here the class classname implements the interface interfacename.A more gerneral form of implementation may lool lilke this Class classname extends superclass implements interface1,interface2 { body of the classname } this shows that a class can extend another class while implementing interfaces When the class implements more than one interface,they are seperated by a comma. The implementation of interfaces can take various form as shown in the following example //interface Test.java interface Area
167
{ final static float pi=3.14F; float compute(float x, float y) } class Rectangle implements Area { pulbic float compute(float x,float y) { return(x*y); } } class circle implements Area { public float compute(float x, float y) { return(pi*x*x); } } class InterfaceTest { public staic void main(String args[] { Rectangle rect = new Rectangle(); Circle cir = new Circle(); Area area; area = rect System.out.println(Area of rectangle = + area.compute(10,20)); area = cir; System.out.println(Area of circle = + area.compute(10,0); } } //interface object
168
The output is as follows: Area of rectangle = 200 Area of circle = 314
11.8 SUMMARY
Java has several levels of hierarchy for code organization, the highest of which is the package. Packages are javas way of grouping a variety of classes and /or interfaces together. In this chapter, we learnt how to create a package , to add more classes to a package,to access the contents of the package,to use java packages and also about interfaces. Interfaces provide the facility of multiple inheritence required in real life applications.
EXERCISES
1. 2. 3. What is package? Write a procedure to create your own package. Define Interface. How multiple inheritance can be implemented using interfaces?
169
Chapter 12
Exception Handling
OBJECTIVES
A
1 1 1 1
Errors and types of errors in a program What exceptions are How to throw system exceptions How to catch and handle different types of exceptions
12.0 INTRODUCTION
We make mistakes while developing and typing a program. A mistake may lead to an error causing the program to produce unexpected results. An error may even cause the system to cause hence, it is important to detect and manage properly all the possible error conditions in a program so that the program will run properly during execution. There are two types of errors , namely,compile-time error and run-time errors compile time errors are all syntax errors detected and displayed by the java compiler. Whenever the compiler displays an error, it will not create the .class file.Hence it is necessary to fix all the errors before we can successfully compile and run the program. Most of the compile time errors are due to typing mistake. The most commom errors are,missing semicolons, missing /mismatch of brackets in classes and methods,wrong spelling of identifiers and keywords, missing double quotes in strings, use of undeclared variables, incompatible types in assignments /initialization and so on. BSIT 42 JAVA Programming
169
170
A program may compile successfully creating the .class file. However, it may not run properly. Such programs produce wrong results due to wrong logic or may terminate due to errors. Most common run time errors are dividing the interger by zero, accessing an element that is out of the bounds of the array, trying to cast an instance of a class to one of its subclasses, passing a parameter that is not in a valid range or value for a method,trying to illegally change the state of the thread etc., when these errors are encountered java generates an error message and aborts the program.
12.1 EXCEPTION
An exception is a run time error. Most of the computer languages do not support exception handling. Errors must be checked and handled manually. This is cumbersome and troublesome. Java provides the facility of exception handling and avoids the above problems. By this run time error management becomes easy. A Java exception is an object that describes an error condition that has occurred in a piece of code. When an error or an exceptional condition arises, an object representing that exception is created and is thrown in the method that caused the error. The method may handle the exception itself or pass it on. In this way, the exception is caught and processed. Exceptions thrown by Java relate to fundamental errors that violate the rules of the language. Five key words try, catch, throw, throws and finally are used to manage exception handling in Java. The programmer encloses in a try block the code that may generate an exception . The try block is immediately followed by a zero or more catch blocks. Each catch block specifies the type of exception it can catch and contains an exception handler. After the last catch block, an optional finally block provides code that always executes regardless of whether or not an exception occurs. If there are no catch blocks following a try block, the finally block is required. When an exception is thrown, program control leaves the try block and catch blocks are searched for an appropriate handler. If the type of thrown exception matches the parameter type in one of the catch blocks, the code for that catch block is executed. If no exception are thrown in the try block, the exception handlers for that block are skipped and the program resumes execution after the last catch block. If a finally block appears after the last catch block, it is executed regardless of whether or not an exception is thrown. A throws clause specifies the exceptions a method throws. An exceptions can be thrown from the statements in a method or from a method thrown from a method called directly or indirectly from the try block. The point at which throw is executed is called a throw point.
171
Object Throwable Exception IO Exception Arithmetic Exception Arrays store Exception Illegal argument Exception Index out of bound Exception Null pointer Exception Runtime Exception File not found End of file Exception Error
Exceptions are represented in Java by instances of the exception class.
Runtime exceptions (subclasses of the class RuntimeException) such as ArrayIndexOutofBounds, SecurityException, or NullPointerException. Other exceptions such as EOFException and MalformedURLException.
Runtime exceptions usually occur because of code that isnt very robust. An ArrayIndexOutofBounds exception, for example, should never be thrown if youre properly checking to make sure your code doesnt extend past the end of an array. NullPointerException exceptions wont happen if you dont try to reference the values of a variable that doesnt actually hold an object. If your program is causing runtime exceptions under any circumstances whatsoever, you should be fixing those problems before you even begin to deal with exception management. The final group of exceptions is the most interesting because these are the exceptions that indicate that something very strange and out of control is happening. EOFExceptions, for example, happen when youre reading from a file and the file ends before you expect it to. MalformedURLExceptions happen when a URL isnt in the right format (perhaps your user typed it wrong). This group includes exceptions that you yourself create to signal unusual cases that may occur in your own programs. Exceptions are arranged in a hierarchy like other classes, where the Exception superclasses are more general errors, and subclasses are more specific errors. This organization will become more important to you as you deal with exceptions in your own code.
172
Most of the exception classes are part of the java.lang package (including Throwable, Exception, and RuntimeException). But many of the other packages define other exceptions, and those exceptions are used throughout the class library. For example, the java.io package defines a general exception class called IOException, which is subclassed not only in the java.io package for input and output exceptions (EOFException, FileNotFoundException), but also in the java.net classes for networking exceptions such as MalFormedURLException
173
12.3.1 Throw
Understanding exception handling in Java requires that you learn some new terminology. The first concept you need to grasp is that of throwing an exception, Javas name for causing an exception to be generated. For example, say a method was written to read a file. If the method could not read the file because the file did not exist, this would generate an IOException. In Java terminology, it is said that the method threw an IOException.
12.3.2 Catch
The next term to learn in Java exception handling is catch. An exception catch is code that realizes the exception has occurred and deals with it appropriately. In Java terms, you say a thrown exception gets caught. In the case of the IOException thrown because of the nonexistent file, the catch statement writes an error message to the screen stating that the specified file does not exist. It then allows the user to try entering a different filename if the first was incorrect, or it may exit. In Java terminology, the IOException was caught.
12.3.3 Try
try is the Java exception-handling term that means a Java program is going to try to execute a block of code that might generate (throw) an exception. The try is a way of telling the compiler that some attempt will be made to deal with at least some of the exceptions generated by the block of code.
The finally statement is used to specify the action to take if none of the previous catch statements specifically deals with the situation. It is similar to the default part of a switch statement. finally is the big net that catches everything that falls out of the exception-handling statement.
175
statement. This is an important point to remember. It is an easy way to determine which block of code should be skipped if an error occurs.
176
or a compilation error will result. Because finally catches everything. Additional statements would never be executed in any case Solved EX1:
class Exc2 { public static void main(String args[]) { int d,a; try { d=0; a = 42/d; System.out.println("this will not be printed"); }catch(ArithmeticException e) { System.out.println("Division by zero"); } System.out.println("after the catch statement"); } }
This program generates the following output: Division by Zero. After Catch statement Notice that the call println() inside the try block is never executed. once an exception is thrown, program control transfers out of the try block into the catch block thus the line this will not be printed. is not displayed. Once the catch statement has executed, program control continues with the next line in the program following the entire try/catch mechanism.
177
While(i<4) { System.out.println(names[i]); i++; } } } normally program terminates with error message when an exception is thrown,after its loop has executed for four times. This program produces following output: Rahul Mohan Madan Java.lang.ArrayIndexOutOfBoundsException : 3 At array.main(array.java:9) The following example is a rewrite of the main() method from previous example.the exception generated in the eariler version is caught and the array index is reset, allowing the program to continue. Public class array{ Public static void main(String[] args){ int i = 0; string names[]={ Rahul , Mohan , Madan}; While(i<4) { try{ System.out.println(names[i]); }catch(ArrayIndexOutOfBoundsException e){ System.out.println(Re-setting the index value); i=-1; }finally{ System.out.println(this is always printed); }
178
i++; } } } Rahul this is always printed Mohan this is always printed Madan this is always printed Re-setting index value This is always printed
12.8 SUMMARY
We commit both sytactic and semantic errors while writing a program sytactic errors are detected during compile time. Some of the run time errors can be managed using exception handling. In this chapter, we have discussed what exceptions are, how to throw system exceptions, how to catch and handle different types of exceptions.
EXERCISES
1. 2. 3. 4. 5. What is an exception? How do we define a try block? How do we define a catch block? How many catch blocks can we use with one try block? What is a finally block? When and how is it used? Give a suitable example?
179
Chapter 13
Managing Input/Output
OBJECTIVE
A
1 1 1 1
Understand the Stream Classes Print( ) and Println( ) statements Reading of characters & strings Writing into the console output.
13.0 INTRODUCTION
As you know, all Java programs automatically import the java.lang package. This package defines a class called System, which encapsulates several aspects of the run-time environment. System.out refers to the standard output stream. By default, this is the console. System.in refers to standard input, which is the keyboard by default. System.err refers to the standard error stream, which also is the console by default. However, these streams may be redirected to any compatible I/O device. System.in is an object of type InputStream; System.out and System.err are objects of type PrintStream. These are byte streams, even though they typically are used to read and write characters from and to the console. As you will see, you can wrap these within character-based streams, if desired. BSIT 42 JAVA Programming
179
180
The preceding chapters have been using System.out in their examples. You can use System.err in much the same way. As explained in the next section, use of System.in is a little more complicated. In Java, console input is accomplished by reading from System.in. To obtain a character-based stream that is attached to the console, you wrap System.in in a BufferedReader object, to create a character stream. BufferedReader supports a buffered input stream. Its most commonly used constructor is shown here. BufferedReader(Reader inputReader) Here, inputReader is the stream that is linked to the instance of BufferedReader that is being created. Reader is an abstract class. One of its concrete subclasses is InputStreamReader, which converts bytes to characters. To obtain an InputStreamReader object that is linked to System.in, use the following constructor: InputStreamReader(InputStream inputStream) Because System.in refers to an object of type InputStream, it can be used for inputStream. Putting it all together, the following line of code creates a BufferedReader that is connected to the keyboard: BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); After this statement executes, br is a character-based stream that is linked to the console through System.in.
181
Screen Printer
Java Program
Keyboard
Mouse
A stream in Java is a path along which data flows (like a river or a pipe along which water flows). It has a source (of data) and a destination (for that data) as depicted in Fig. 13.2. Both the source and the destination may be physical devices or programs or other streams in the same program.
Stream
Destination
The concept of sending data from one stream to another (like one pipe feeding into another pipe) has made streams in Java a powerful tool for file processing. We can build a complex file processing sequence using a series of simple stream operations. This feature can be used to filter data along the pipelining of streams so that we obtain data in a desired format. For example, we can use one stream to get raw data in binary format and then use another stream to convert it to integers. Java streams are classified into two basic types, namely, input stream and output stream. An input stream extracts (i.e. reads) data from the source (file) and sends it to the program. Similarly, an output
182
stream takes data from the program and sends (i.e. writes) it to destination (file). Figure illustrates the use of input and output streams. The program connects and opens an input stream on the data source and then reads the data serially and writes data out serially. In both the cases, the program does not know the details of end points (i.e. source and destination).
Reads
Program
Destination
183
Each time that read( ) is called, it reads a character from the input stream and returns it as an integer value. It returns 1 when the end of the stream is encountered. As you can see, it can throw an IOException. The following program demonstrates read( ) by reading characters from the console until the user types a q:
Character Stream
Reader Classes
Writer Classes
Memory
File
Pipe
Memory
File
Pipe
184
// Use a BufferedReader to read characters from the console. Import java.io.*; Class BRRead { Public static void main(String args[ ] ) Throws IOException { char c; BufferedReader br = new BufferedReader (InputStreamReader(System.in)); System.out.printlner(Enter Characters, q to quit.); // read characters do { c= (char) br.read( ); System.out.println(c); }while (c != q); } } Here is a sample run: Enter characters, q, to quit. 123abcq 1 2 3 a b c q
This output may look a little different from what you expected, because System.in is line buffered, by default. This means that no input is actually passed to the program until you press ENTER. As you can guess, this does not make read( ) particularly valuable for interactive, console input.
185
// Read a string from console using a BufferedReader. Import java.io.*; Class BRReadLines { Public staic void main(String args[ ]) Throws IOException { // Create a BufferedReader using System.in BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str; System.out.println(Enter lines of text); System.out.println(Enter stop to quit); Do { Str = br.readLine( ); System.out.println(str); while (!str.equals(stop));
} } }
The next example creates a tiny text editor. It creates an array of String objects and then reads in lines of text, storing each line in the array. It will read up to 100 lines or until you enter stop. It uses a BufferedReader to read from the console.
// A tiny editor. import java.io.*; class TinyEdit { public staic void main(String args[ ]) throws IOException { // Create a BufferedReader using System.in BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str[ ] = new String[100]; System.out.println(Enter lines of text); System.out.println(Enter stop to quit); for (int i=0;i<100;i++) { str[ i ] = br.readline( ); if (str[ i ] .equals (stop)) break; }
186
System.out.println(\nHere is your file:); // display the lines for (int i=0;i<100;i++) { if (str[ i ] .equals (stop)) break; System.out.println(str[ I ]); } } } Here is a sample run: Enter lines of text. Enter stop to quit. This is line one. This is line two. Java makes working with strings easy. Just create String objects. Stop Here is your file: This is line one. This is line two. Java makes working with strings easy. Just create String objects.
187
//Demonstrate System.out.write( ).
class writedemo { public static void main(string args[ ]) { int b; b = a ; System.out.write(b); System.out.write(\n); } }
You will not often use write( ) to perform console output(lthough doing so might be useful in some situation), because print( ) and println( ) are substantially easier to use.
13.6 SUMMARY
In this chapter, we have discussed how to manage inputs and outputs. How to read characters, strings, and usage of print( ) and println( ) statements have been discussed. After going through this chapter, you will be able to 1 Read Character 1 Read Strings 1 Write Console Output
EXERCISES
1. 2. 3. 4. What is a file? Why do we require files to store data? What is a stream? How id the concept of streams used in Java? What are input and output streams? Explain them with illustrations? What is a stream class? How are the stream classes classified?
REFERENCES
1. 2. 3. 4. 5. 6 7 JAVATM- HOW TO PROGRAM, Deitel and Deital, Pearson Education Third Edition, 1999. JAVATM- 2, The Complete Reference, Patrick Naughton and Herbert Schildt, Tata Mc.Graw-Hill Third Edition, 1999. JAVATM- Programming Langauage, Sun Educational Services, Student Guides, April 2000. Programming with JAVA, Jogh R Hubbard, Mc.Graw-Hill. 1999 Programming with JAVA, E. Balaguruswamy Flanagan.D Java in a Nutshell,OReilly & Assosiates,1996 www.java.sun.com
mmm