Top Banner
Programming in Java
191

jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

May 21, 2020

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

Page 2: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Board of Studies

Prof. H. N. Verma Prof. M. K. GhadoliyaVice- Chancellor Director, Jaipur National University, Jaipur School of Distance Education and Learning Jaipur National University, JaipurDr. Rajendra Takale Prof. and Head AcademicsSBPIM, Pune

___________________________________________________________________________________________

Subject Expert Panel

Dr. Ramchandra G. Pawar Vaibhav BedarkarDirector, SIBACA, Lonavala Subject Matter ExpertPune

___________________________________________________________________________________________

Content Review Panel

Gaurav Modi Shubhada PawarSubject Matter Expert Subject Matter Expert

___________________________________________________________________________________________Copyright ©

This book contains the course content for Programming in Java.

First Edition 2014

Printed byUniversal Training Solutions Private Limited

Address05th Floor, I-Space, Bavdhan, Pune 411021.

All rights reserved. This book or any portion thereof may not, in any form or by any means including electronic or mechanical or photocopying or recording, be reproduced or distributed or transmitted or stored in a retrieval system or be broadcasted or transmitted.

___________________________________________________________________________________________

Page 3: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

I

Index

ContentI. ...................................................................... II

List of FiguresII. ........................................................ VII

List of TablesIII. ........................................................VIII

AbbreviationsIV. .........................................................IX

ApplicationV. ............................................................. 168

BibliographyVI. ......................................................... 176

Self Assessment AnswersVII. ................................... 178

Book at a Glance

Page 4: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

II

Contents

Chapter I ....................................................................................................................................................... 1Introduction to JAVA ................................................................................................................................... 1Aim ................................................................................................................................................................ 1Objectives ...................................................................................................................................................... 1Learning outcome .......................................................................................................................................... 11.1 Introduction to Coding Languages .......................................................................................................... 21.2 Concept of Java ........................................................................................................................................ 2 1.2.1 Origin of Java ........................................................................................................................... 2 1.2.2 Future Buzz in Coding ............................................................................................................. 41.3 A Virtual Machine .................................................................................................................................... 41.4 Java in Comparison to Other Languages ................................................................................................. 61.5 A Java Road Map ..................................................................................................................................... 8 1.5.1 The Past: Java 1.0 and Java 1.1................................................................................................ 8 1.5.2 The Present: Java 2 ................................................................................................................. 81.6 First Application....................................................................................................................................... 91.7 HelloJava1 ................................................................................................................................................ 91.8 Classes.....................................................................................................................................................111.9 main( ) Method ...................................................................................................................................... 121.10 Classes and Objects .............................................................................................................................. 131.11 Variables and Class Types .................................................................................................................... 131.12 Inheritance ............................................................................................................................................ 141.13 JComponent Class ................................................................................................................................ 141.14 Relationships and Finger Pointing ....................................................................................................... 151.15 Packages ............................................................................................................................................... 151.16 paintComponent( ) Method .................................................................................................................. 17Summary .................................................................................................................................................... 18References .................................................................................................................................................. 18Recommended Reading ............................................................................................................................ 18Self Assessment ........................................................................................................................................... 19

Chapter II ................................................................................................................................................... 21Object Oriented Programming ................................................................................................................ 21Aim .............................................................................................................................................................. 21Objectives .................................................................................................................................................... 21Learning outcome ........................................................................................................................................ 212.1 Introduction to OOP ............................................................................................................................... 222.2 Object Oriented Programming Concepts ............................................................................................... 232.3 Object Oriented Programming ............................................................................................................... 252.4 Programming Paradigms ........................................................................................................................ 262.5 Functional programming ........................................................................................................................ 262.6 Logic Programming ............................................................................................................................... 272.7 Object Orientation as a New Paradigm: The Big Picture ...................................................................... 272.8 Messages and Responsibilities ............................................................................................................... 282.9 Classes and Instances ............................................................................................................................. 292.10 Fundamentals of Objects and Classes .................................................................................................. 292.11 Objects and Classes .............................................................................................................................. 292.12 Encapsulation ....................................................................................................................................... 302.13 Messages .............................................................................................................................................. 312.14 Classes.................................................................................................................................................. 312.15 Types .................................................................................................................................................... 322.16 Introduction to Enums .......................................................................................................................... 332.17 Enums and for-each Loops .................................................................................................................. 35

Page 5: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

III

Summary .................................................................................................................................................... 37References .................................................................................................................................................. 37Recommended Reading ............................................................................................................................ 37Self Assessment ........................................................................................................................................... 38

Chapter III .................................................................................................................................................. 40Constants, Variables and Data Types ....................................................................................................... 40Aim .............................................................................................................................................................. 40Objectives ................................................................................................................................................... 40Learning outcome ....................................................................................................................................... 403.1 Introduction to Programming Language Basic .................................................................................... 413.2 Java Integers ........................................................................................................................................... 413.3 Java Floating Point Numbers ................................................................................................................. 423.4 Java Characters ...................................................................................................................................... 423.5 Java Boolean .......................................................................................................................................... 423.6 Data Types ............................................................................................................................................. 433.7 Primitive and non-primitive data types .................................................................................................. 443.8 Primitive Data Type ............................................................................................................................... 443.9 Operators Used in Java .......................................................................................................................... 46 3.9.1 Arithmetic Operators .............................................................................................................. 46 3.9.2 Relational Operators .............................................................................................................. 48 3.9.3 Logical Operators .................................................................................................................. 52 3.9.4 Assignment Operators ............................................................................................................ 53 3.9.5 Misc Operators ....................................................................................................................... 53 3.9.5.1 Conditional Operator (? : ) ...................................................................................... 53 3.9.5.2 instanceOf Operator ................................................................................................ 543.10 Precedence of Java Operators .............................................................................................................. 55Summary .................................................................................................................................................... 56References .................................................................................................................................................. 56Recommended Reading ............................................................................................................................ 56Self Assessment ........................................................................................................................................... 57

Chapter IV ................................................................................................................................................. 59Basic Syntax, Loop Control and Decision Making ................................................................................ 59Aim .............................................................................................................................................................. 59Objectives .................................................................................................................................................... 59Learning outcome ........................................................................................................................................ 594.1 Object and Classes ................................................................................................................................ 604.2 First Java Program ................................................................................................................................. 604.3 Basic Syntax ........................................................................................................................................... 614.4 Java Identifiers ....................................................................................................................................... 614.5 Java Modifiers ........................................................................................................................................ 614.6 Java Variables ......................................................................................................................................... 614.7 Java Keywords ....................................................................................................................................... 624.8 Comments in Java .................................................................................................................................. 624.9 Classes in Java ....................................................................................................................................... 644.10 Constructors ......................................................................................................................................... 654.11 Creating an Object ............................................................................................................................... 654.12 Accessing Instance Variables and Methods ......................................................................................... 664.13 Source file declaration rules ................................................................................................................. 674.14 Java Package ........................................................................................................................................ 684.15 Basic Data Types .................................................................................................................................. 684.16 Primitive Data Types ............................................................................................................................ 684.17 Java Variable Types .............................................................................................................................. 704.18 Java Access Modifiers .......................................................................................................................... 74

Page 6: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

IV

4.19 Private Access Modifier – private ........................................................................................................ 754.20 Public Access Modifier - Public .......................................................................................................... 754.21 Protected Access Modifier - Protected ................................................................................................. 754.22 Access Control and Inheritance ........................................................................................................... 764.23 Java Modifier Types ............................................................................................................................. 764.24 Access Control Modifiers .................................................................................................................... 774.25 Java Loops - for, while and do...while ................................................................................................. 774.26 Java Decision Making .......................................................................................................................... 82Summary .................................................................................................................................................... 87References .................................................................................................................................................. 87Recommended Reading ............................................................................................................................ 87Self Assessment ........................................................................................................................................... 88

Chapter V .................................................................................................................................................... 90Number Class ............................................................................................................................................. 90Aim ............................................................................................................................................................. 90Objectives .................................................................................................................................................... 90Learning outcome ....................................................................................................................................... 905.1 Introduction to Number Class ................................................................................................................ 915.2 Number Methods ................................................................................................................................... 92 5.2.1 Java - xxxValue() Methods .................................................................................................... 92 5.2.2 compareTo() ........................................................................................................................... 93 5.2.3 equals() ................................................................................................................................... 93 5.2.4 valueOf() ................................................................................................................................ 94 5.2.5 toString() ................................................................................................................................ 95 5.2.6 Java - parseInt() Method ........................................................................................................ 96 5.2.7 Java - abs() Method ................................................................................................................ 97 5.2.8 Java - ceil() Method ............................................................................................................... 98 5.2.9 Java - floor() Method ............................................................................................................. 99 5.2.10 Java - rint() Method ............................................................................................................. 99 5.2.11 Java - round() Method ........................................................................................................ 100 5.2.12 Java - min() Method ........................................................................................................... 101 5.2.13 Java - max() Method .......................................................................................................... 102 5.2.14 Java - exp() Method ........................................................................................................... 103 5.2.15 Java - log() Method ............................................................................................................ 103 5.2.16 Java - pow() Method .......................................................................................................... 104 5.2.17 Java - sqrt() Method ........................................................................................................... 105 5.2.18 Java - sin() Method ............................................................................................................ 105 5.2.19 Java - cos() Method ............................................................................................................ 106 5.2.20 Java - tan() Method ............................................................................................................ 107 5.2.21 Java - asin() Method .......................................................................................................... 107 5.2.22 Java - acos() Method .......................................................................................................... 108 5.2.23 Java - atan() Method .......................................................................................................... 109 5.2.24 Java - atan2() Method ........................................................................................................ 109 5.2.25 Java - toDegrees() Method ..................................................................................................110 5.2.26 Java-toRadians() .................................................................................................................111 5.2.27 Java-random() .....................................................................................................................1115.3 Number Methods ..................................................................................................................................112Summary ...................................................................................................................................................114References ..................................................................................................................................................114Recommended Reading ...........................................................................................................................114Self Assessment ..........................................................................................................................................115

Page 7: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

V

Chapter VI ................................................................................................................................................117Character Class, String and Array .........................................................................................................117Aim ............................................................................................................................................................117Objectives ..................................................................................................................................................117Learning outcome .......................................................................................................................................1176.1 Introduction to Character Class ............................................................................................................1186.2 Character Methods ................................................................................................................................118 6.2.1 isLetter() ................................................................................................................................118 6.2.2 isDigit() .................................................................................................................................119 6.2.3 isWhitespace() ......................................................................................................................119 6.2.4 isUpperCase() ...................................................................................................................... 120 6.2.5 isLowerCase() ...................................................................................................................... 121 6.2.6 toUpperCase() ...................................................................................................................... 122 6.2.7 toLowerCase() ..................................................................................................................... 122 6.2.8 toString() .............................................................................................................................. 1236.3 String Class .......................................................................................................................................... 1236.4 String Length ....................................................................................................................................... 1246.5 Concatenating Strings .......................................................................................................................... 1246.6 Creating Format Strings ....................................................................................................................... 1256.7 String Methods ..................................................................................................................................... 125 6.7.1 char charAt(int index) ......................................................................................................... 126 6.7.2 int compareTo(Object o) ..................................................................................................... 127 6.7.3 int compareTo(String anotherString) ................................................................................... 128 6.7.4 int compareToIgnoreCase(String str) .................................................................................. 129 6.7.5 String concat(String str) ....................................................................................................... 130 6.7.6 boolean contentEquals(StringBuffer sb) ............................................................................. 130 6.7.7 static String copyValueOf(char[] data) ............................................................................... 131 6.7.8 static String copyValueOf(char[] data, int offset, int count) ................................................ 132 6.7.9 boolean endsWith(String suffix) ......................................................................................... 133 6.7.10 boolean equals(Object anObject) ....................................................................................... 134 6.7.11 boolean equalsIgnoreCase(String anotherString) .............................................................. 135 6.7.12 byte getBytes() .................................................................................................................. 136 6.7.13 byte[] getBytes(String charsetName .................................................................................. 136 6.7.14 void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) ...................................... 137 6.7.15 int hashCode() .................................................................................................................... 138 6.7.16 int indexOf(int ch) ............................................................................................................ 139 6.7.17 int indexOf(int ch, int fromIndex) .................................................................................... 140 6.7.18 int indexOf(String str) ........................................................................................................ 141 6.7.19 int indexOf(String str, int fromIndex) ................................................................................ 143 6.7.20 String intern() ..................................................................................................................... 144Summary .................................................................................................................................................. 147References ................................................................................................................................................ 147Recommended Reading .......................................................................................................................... 147Self Assessment ......................................................................................................................................... 148

Chapter VII ............................................................................................................................................. 150Arrays and Files ...................................................................................................................................... 150Aim ............................................................................................................................................................ 150Objectives ................................................................................................................................................. 150Learning outcome ...................................................................................................................................... 1507.1 Introduction to Array ............................................................................................................................ 1517.2 Declaring Array Variables .................................................................................................................... 1517.3 Creating Arrays .................................................................................................................................... 1517.4 Processing Arrays ................................................................................................................................. 1527.5 foreach Loops ....................................................................................................................................... 153

Page 8: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

VI

7.6 Passing Arrays to Methods................................................................................................................... 1547.7 Arrays Class ......................................................................................................................................... 1557.8 Streams, Files and I/O .......................................................................................................................... 1557.9 Reading Characters from Console ....................................................................................................... 1557.10 Reading Strings from Console ........................................................................................................... 1567.11 Reading and Writing Files .................................................................................................................. 1587.12 FileInputStream .................................................................................................................................. 1597.13 ByteArrayInputStream ....................................................................................................................... 1607.14 DataInputStream ................................................................................................................................ 1617.15 File Navigation and I/O ..................................................................................................................... 1627.16 Directories in Java .............................................................................................................................. 162Summary .................................................................................................................................................. 165References ................................................................................................................................................. 165Recommended Reading .......................................................................................................................... 165Self Assessment ........................................................................................................................................ 166

Page 9: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

VII

List of Figures

Fig. 1.1 The Java Runtime Environment ....................................................................................................... 5Fig. 1.2 Programming languages compared .................................................................................................. 6Fig. 1.3 HelloJava1 application ................................................................................................................... 10Fig. 1.4 Part of the Java class hierarchy ...................................................................................................... 15Fig. 1.5 Some core Java packages ............................................................................................................... 16Fig. 2.1 Inheritance ..................................................................................................................................... 24Fig. 2.2 Object ............................................................................................................................................. 29Fig. 2.3 Messages ......................................................................................................................................... 30Fig. 5.1 Number Class ................................................................................................................................. 91Fig. 7.1 Array myList ................................................................................................................................. 152Fig. 7.2 Reading and writing files .............................................................................................................. 158

Page 10: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

VIII

List of Tables

Table 3.1 Integer Type ................................................................................................................................. 41Table 3.2 Floating point .............................................................................................................................. 42Table 3.3 Java Character .............................................................................................................................. 42Table 3.4 Arithmetic operators ..................................................................................................................... 46Table 3.5 Relational operators ..................................................................................................................... 48Table 3.6 Bitwise operators .......................................................................................................................... 50Table 3.7 Logical operators .......................................................................................................................... 52Table 3.8 Assignment Operators .................................................................................................................. 53Table 3.9 Precedence of Java operators ....................................................................................................... 55Table 4.1 Java keyword ............................................................................................................................... 62Table 4.2 Character representation .............................................................................................................. 70Table 5.1 Number methods .........................................................................................................................113Table 7.1 Array Class ................................................................................................................................. 155Table 7.2 Methods with Description of FileInputStream ........................................................................... 159Table 7.3 ByteArrayInputStream ............................................................................................................... 160Table 7.4 DataInputStream ........................................................................................................................ 161

Page 11: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

IX

Abbreviations

API - Application Programming InterfaceASCII - American Standard Code for Information InterchangeAWT - Abstract Windowing ToolkitCPU - Central Processing Unit FPU - Floating Point Unit GUI - Graphic User Interface HTML - Hypertext Markup LanguageI/O - Input/ Output JDBC - Java Database ConnectivityJDK - Java Development KitJFC - Java Foundation ClassesJNDI - Java Naming and Directory InterfaceJNDI - Java Naming and Directory InterfaceLDAP - Lightweight Directory Access ProtocoMUD - Multi-User DungeonOOP - Object Oriented Programming PAD - Personal Digital AssistantProlog - PROgramming in LOGgic RMI - Remote Method InvocationTV - Television

Page 12: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...
Page 13: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

1

Chapter I

Introduction to JAVA

Aim

The aim of this chapter is to:

understand the concept of coding language •

elaborate the concept of Java •

explain future buzz of coding •

describe the virtual machine •

Objectives

The objectives of this chapter are to:

evaluate various versions of java •

get an overview of java 2 •

evaluate important features of Java •

discussfirstapplicationofJAVA•

Learning outcome

At the end of this chapter, the students will be able to:

draw codes for java application •

evaluate different classes of Java •

learn concepts like object and inheritances •

Page 14: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

2

1.1 Introduction to Coding Languages The greatest challenges and most exciting opportunities for software developers today lie in harnessing the power of networks. Applications created today, whatever their intended scope or audience, will almost certainly be run on machines linked by a global network of computing resources. The increasing importance of networks is placing new demands on existing tools and fuelling the demand for a rapidly growing list of completely new kinds of applications.

We want software that works consistently, anywhere, on any platform and that plays well with other •applications. We want dynamic applications that take advantage of a connected world, capable of accessing disparate and •distributed information sources. We want truly distributed software that can be extended and upgraded seamlessly. •We want intelligent applications like autonomous agents that can roam the Net for us, ferreting out information •and serving as electronic emissaries. We know, to some extent, what we want. So why don’t we have it? The problem has been that the tools for •building these applications have fallen short.

The requirements of speed and portability have been, for the most part, mutually exclusive, and security has been largely ignored or misunderstood. There are truly portable languages, but they are mostly bulky, interpreted, and slow. These languages are popular as much for their high-level functionality as for their portability. And there are fast languages, but they usually provide speed by binding themselves to particular platforms, so they can meet the portability issue only halfway. There are even a few recent safe languages, but they are primarily offshoots of the portable languages and suffer from the same problems.

1.2 Concept of JavaThe Java™ programming language, developed at Sun Microsystems under the guidance of Net luminaries James •Gosling and Bill Joy, is designed to be a machine-independent programming language that is both safe enough to traverse networks and powerful enough to replace native executable code. Java addresses the issues raised here and may help us start building the kinds of applications we want.•Initially, most of the enthusiasm for Java centered on its capabilities for building embedded applications for the •World Wide Web; these applications are called applets.Applets could be independent programs in themselves, or sophisticated frontends to programs running on a •server. More recently, interest has shifted to other areas. With Java 2, Java has the most sophisticated toolkit for building •graphical user interfaces; this development has allowed Java to become a popular platform for developing traditional application software. Java has also become an important platform for server-side applications, using the servlet interface, and for •enterprise applications using technologies like Enterprise JavaBeans™. And Java is the platform of choice for modern distributed applications.This book shows you how to use Java to accomplish real programming tasks like building networked applications •and creating functional user interfaces. There’s still a chapter devoted to applets; they may become more important again when the Java 2 (and subsequent) versions of the Java platform are more widely distributed in web browsers.

1.2.1 Origin of Java

The seeds of Java were planted in 1990 by Sun Microsystems patriarch and chief researcher, Bill Joy. Since •Sun’s inception in the early 80s, it has steadily pushed one idea: "The network is the computer". At the time though, Sun was competing in a relatively small workstation market, while Microsoft was beginning •its domination of the more mainstream, Intel-based PC world.

Page 15: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

3

When Sun missed the boat on the PC revolution, Joy retreated to Aspen, Colorado, to work on advanced •research. He was committed to accomplish complex tasks with simple software, and founded the aptly named Sun Aspen •Smallworks. Of the original members of the small team of programmers assembled in Aspen, James Gosling is the one who •willberememberedasthefatherofJava.Goslingfirstmadeanameforhimselfintheearly80’sastheauthorofGoslingEmacs,thefirstversionofthepopularEmacseditorthatwaswritteninCandranunderUnix.GoslingEmacs became popular, but was soon eclipsed by a free version, GNU Emacs, written by Emacs’s original designer.Bythattime,GoslinghadmovedontodesignSun’sNeWSwindowsystem,whichbrieflycontendedwith the X Window System for control of the Unix graphical user interface (GUI) desktop in 1987.While some people would argue that NeWS was superior to X, NeWS lost out because Sun kept it proprietary •and didn’t publish source code, while the primary developers of X formed the X Consortium and took the opposite approach.Designing NeWS taught Gosling the power of integrating an expressive language with a networkaware •windowing GUI. It also taught Sun that the Internet programming community will refuse to accept proprietary standards, no •matter how good they may be.The seeds of Java’s remarkably permissive licensing scheme were sown by NeWS’s failure. •Gosling brought what he had learned to Bill Joy’s nascent Aspen project, and in 1992, work on the project led •to the founding of the Sun subsidiary, FirstPerson, Inc. Its mission was to lead Sun into the world of consumer electronics. •The FirstPerson team worked on developing software for information appliances, such as cellular phones and •personal digital assistants (PDAs). The goal was to enable the transfer of information and real-time applications over cheap infrared and packet-•based networks. Memoryandbandwidthlimitationsdictatedsmallandefficientcode.•The nature of the applications also demanded they be safe and robust. •Gosling and his teammates began programming in C++, but they soon found themselves confounded by a •language that was too complex, unwieldy, and insecure for the task. They decided to start from scratch, and Gosling began working on something he dubbed “C++ minus minus.”•With the foundering of the Apple Newton, it became apparent that the PDA’s ship had not yet come in, so Sun •shifted FirstPerson’s efforts to interactive TV (ITV). The programming language of choice for ITV set-top boxes was the near ancestor of Java, a language called •Oak. Even with its elegance and ability to provide safe interactivity, Oak could not salvage the lost cause of ITV. •Customers didn’t want it, and Sun soon abandoned the concept.•At that time, Joy and Gosling got together to decide on a new strategy for their language. •It was 1993, and the explosion of interest in the Internet, and the World Wide Web in particular, presented a •new opportunity. Oak was small, robust, architecture-independent, and object-oriented. •As it happens, these are also the requirements for a universal, network-savvy Programming language. •Sun quickly changed focus, and with a little retooling, Oak became Java. •

Page 16: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

4

1.2.2 Future Buzz in Coding

ItwouldnotbeoverdoingittosaythatJavahascaughtonlikewildfire.•Evenbeforeitsfirstofficialrelease,whileJavawasstillanon-product,nearlyeverymajor industryplayer•jumped on the Java bandwagon. Java license included Microsoft, Intel, IBM and virtually all major hardware and software vendors. (That’s not •to say that everything has been coming up roses. Even with all of this support Java has taken a lot of knocks andhadsomegrowingpainsduringitsfirstfewyears.)As we begin looking at the Java architecture, you’ll see that much of what is exciting about Java comes from •the self-contained, virtual machine environment in which Java applications run. Java has been carefully designed so that this supporting architecture can be implemented either in software, for •existing computer platforms, or in customized hardware, for new kinds of devices. Sun and other industry giants are producing fast Java chips and microprocessors tailored to run media-rich Java •applications. Hardware implementations of Java could power inexpensive network terminals, PDAs and other information •appliances to take advantage of transportable Java applications.Software implementations of Java are available now for portable computing devices like the popular Palm™ •PDA.Many people see Java as part of a trend toward cheap, Internet-based, “operating system-less” appliance that •will weave the Net into more and more consumer-related areas. Thefirstattemptsatmarketing“networkcomputers”asalternativestothestandardPChavenotgoneverywell.•(The combination of Windows and cheap PC hardware form a formidable barrier.) But the desktop is only one corner of the network. Only time will tell what people will do with Java, but it’s probably worth at least a passing thought that the •applet you write today might well be running on someone’s wristwatch tomorrow. If that seems too futuristic, remember that you can already get “smart cards” and “wearable” devices like rings •and dog tags that have Java interpreters embedded in them.Thesedevicesarecapableofdoingeverythingfromfinancialtransactions(Payingahotelbill)tounlockinga•door (the door to your hotel room) to rerouting phone calls (so your hotel room receives your business calls). The hardware is already here; it can’t be long before the rest of the software infrastructure begins to take •advantage of it. A Java wristwatch is not a silly notion.

1.3 A Virtual MachineJava is both a compiled and an interpreted language. •Java source code is turned into simple binary instructions, much like ordinary microprocessor machine code. •However,whereasCorC++sourceisrefinedtonativeinstructionsforaparticularmodelofprocessor,Javasource is compiled into universal format instructions for a virtual machine. Compiled Java byte-code, also called J-code, is executed by a Java runtime interpreter. •The runtime system performs all the normal activities of a real processor, but it does so in a safe, virtual •environment. It executes the stack-based instruction set and manages a storage heap. •It creates and manipulates primitive data types, and loads and invokes newly referenced blocks of code. •Mostimportantly,itdoesallthisinaccordancewithastrictlydefinedopenspecificationthatcanbeimplemented•by anyone who wants to produce a Java-compliant virtual machine. Together,thevirtualmachineandlanguagedefinitionprovideacompletespecification.Therearenofeatures•ofJavaleftundefinedorimplementation-dependent.Forexample,Javaspecifiesthesizesofallitsprimitivedata types, rather than leave it up to each implementation.

Page 17: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

5

The Java interpreter is relatively lightweight and small; it can be implemented in whatever form is desirable •for a particular platform. On most systems, the interpreter is written in a fast, natively compiled language like C or C++. •The interpreter can be run as a separate application, or it can be embedded in another piece of software, such •as a web browser. All of this means that Java code is implicitly portable. The same Java application byte-code can run on any •platform that provides a Java runtime environment, as shown in Figure 1.1. You don’t have to produce alternative versions of your application for different platforms, and you don’t have to distribute source code to end users.

Source Code

Java runtimeByte Code

Unix PC Macintosh

Fig. 1.1 The Java Runtime Environment

The fundamental unit of Java code is the class. •As in other object-oriented languages, classes are application components that hold executable code and data. •Compiled Java classes are distributed in a universal binary format that contains Java byte-code and other class •information. Classescanbemaintaineddiscretelyandstoredinfilesorarchivesonalocalsystemoronanetworkserver.•Classes are located and loaded dynamically at runtime, as they are needed by an application.•Inadditionto theplatform-specificruntimesystem,Javahasanumberoffundamentalclasses thatcontain•architecture-dependent methods. These native methods serve as the gateway between the Java virtual machine and the real world. They are implemented in a natively compiled language on the host platform. •Theyprovideaccesstoresourcessuchasthenetwork,thewindowingsystemandthehostfilesystem.•The rest of Java is written entirely in Java, and is therefore portable. This includes fundamental Java utilities like •the Java compiler and Sun’s HotJava web browser, which are also Java applications and are therefore available on all Java platforms.Historically, interpreters have been considered slow, but because the Java interpreter runs compiled byte-code, •Java is a relatively fast interpreted language. More importantly, Java has also been designed so that software implementations of the runtime system can •optimizetheirperformancebycompilingbyte-codetonativemachinecodeonthefly.Thisiscalledjust-in-time compilation. Sun claims that with just-in-time compilation, Java code can execute nearly as fast as native compiled code and •maintain its transportability and security.

Page 18: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

6

There is only one true performance hit that compiled Java code will always suffer for the sake of security array •bounds checking. But on the other hand, some of the basic design features of Java place more information in the hands of the •compiler, which allows for certain kinds of optimizations not possible in C or C++.The latest twist in compilation techniques is a new virtual machine that Sun calls HotSpot. •The problem with a traditional just-in-time compilation is that optimizing code takes time, and is extremely •important for good performance on modern computer hardware. So a just-in-time compiler can produce decent results, but can never afford to take the time necessary to do a •good job of optimization. HotSpot uses a trick called “adaptive compilation” to solve this problem. •If you look at what programs actually spend their time doing, it turns out that they spend almost all of their time •executing a relatively small part of the code again and again. The chunk of code that is executed repeatedly may only be a small percent of the total program, but its behaviour •determines the program’s overall performance.To take advantage of this fact, HotSpot starts out as a normal Java byte code interpreter, but with a difference: •itmeasures(profiles)thecodeasitisexecuting,toseewhatpartsarebeingexecutedrepeatedly.Once it knows which parts of the code are crucial to the performance, HotSpot compiles those sections and •only those sections into true machine code. Since it only compiles a small portion of the program into machine code, it can afford to take the time necessary to optimize those portions. The rest of the program may not need to be compiled at all-just interpreted-saving memory and time.•The technology for doing this is very complex, but the idea is essentially simple: optimize the parts of the •program that need to go fast, and don’t worry about the rest. Another advantage of using an adaptive compiler at runtime is that it can make novel kinds of optimizations •that a static (compile time only) compiler cannot dream of.

1.4 Java in Comparison to Other LanguagesJava is a new language, but it draws on many years of programming experience with other languages in its •choice of features. So a lot can be said in comparing and contrasting Java with other languages. •There are at least three pillars necessary to support a universal language for network programming today: •portability, speed, and security. Figure 1.2 shows how Java compares to other languages.

C/C++

SPEE

D

SPEE

D

SPEE

D

SEC

UR

ITY

SEC

UR

ITY

SEC

UR

ITY

SEC

UR

ITY

PORT

AB

ILIT

Y

PORT

AB

ILIT

Y

PORT

AB

ILIT

Y

PORT

AB

ILIT

Y

JAVA Smalltalk

Tcl

Fig. 1.2 Programming languages compared

Page 19: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

7

YoumayhaveheardthatJavaisalotlikeCorC++,butthat’sreallynottrue,exceptatasuperficiallevel.•WhenyoufirstlookatJavacode,you’llseethatthebasicsyntaxlooksalotlikeCorC++.Butthat’swhere•the similarities end. Java is by no means a direct descendant of C or a next-generation C++. •If you compare language features, you’ll see that Java actually has more in common with languages like •Smalltalk and Lisp. In fact, Java’s implementation is about as far from native C as you can imagine.•The surface-level similarities to C and C++ are worth noting, however. Java borrows heavily from C and •C++ syntax, so you’ll see lots of familiar language constructs, including an abundance of curly braces and semicolons. Java also subscribes to the C philosophy that a good language should be compact; in other words, it should •besufficientlysmallandregularsoaprogrammercanholdallthelanguage’scapabilitiesinhisorherheadatonce. Just as C is extensible with libraries, packages of Java classes can be added to the core language components.•C has been successful because it provides a reasonably featureful programming environment, with high •performance and an acceptable degree of portability. Java also tries to balance functionality, speed, and portability, but it does so in a very different way. •C trade’s functionality for portability; Java trades speed for portability. •Java also addresses security issues, while C doesn’t.•Java is an interpreted language, so it won’t be as fast as a compiled language like C. But Java is fast enough, •especially for interactive, network-based applications, where the application is often idle, waiting for the user to do something or waiting for data from the network. For situations where speed is critical, a Java implementation can optimize performance with just-in-time •compilation to byte-code, as previously discussed. Scripting languages like Perl, Python, Tcl/Tk and Wksh, are becoming very popular, and for good reason. •There’s no reason for which a scripting language could not be suitable for safe, networked applications (e.g., •Safe Tcl), but most scripting languages are not designed for serious, large scale programming. The attraction to scripting languages is that they are dynamic; they are powerful tools for rapid prototyping. •Some scripting languages, like awk and Perl, also provide powerful tools for text-processing tasks that more •general-purposelanguagesfindunwieldy.Scripting languages are also highly portable. •One problem with scripting languages, however, is that they are rather casual about program structure and data •typing. Most scripting languages (with a hesitant exception for Perl 5.0 and Python) are not object-oriented. •Theyalsohavevastlysimplifiedtypesystemsandgenerallydon’tprovideforsophisticatedscopingofvariables•and functions. These characteristics make them unsuitable for building large, modular applications.•Speed is another problem with scripting languages; the high-level, fully interpreted nature of these languages •often makes them quite slow. Javaofferssomeoftheessentialadvantagesofascriptinglanguage,alongwiththeaddedbenefitsofalower-•level language. Incremental development with object-oriented components, combined with Java’s simplicity, make it possible •to develop applications rapidly and change them easily, with a short concept-to implementation time. Java also comes with a large base of core classes for common tasks such as building GUIs and doing network •communications. But along with these features, Java has the scalability and software-engineering advantages of more static languages.

Page 20: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

8

It provides a safe structure on which to build higher-level networked tools and languages. However, don’t •confuse Java with JavaScript! JavaScript is an object-based scripting language being developed by Netscape and others. It serves as glue and an “in the document” language for dynamic, interactive HTML-based applications. •JavaScript draws its name from its intended integration with Java. •You can currently interact with Java applets embedded in HTML using JavaScript. •There have been a few portable implementations of JavaScript that would promote it to the level of a general •scripting language. As we have already said, Java is similar in design to languages like Smalltalk and Lisp.•However, these languages are currently used mostly as research vehicles, rather than for developing large-scale •systems. One reason is that they never developed a standard portable binding to operating system services, like the C •standard library or the Java core classes. Smalltalk is compiled to an interpreted byte-code format, and it can be dynamically compiled to native code •onthefly,justlikeJava.But Java improveson thedesignbyusingabyte-codeverifier to ensure thecorrectnessof compiled Java•code.ThisverifiergivesJavaaperformanceadvantageoverSmalltalkbecauseJavacoderequiresfewerruntime•checks.Java’sbyte-codeverifieralsohelpswithsecurityissues,somethingthatSmalltalkdoesn’taddress.Smalltalk is a mature language, though, and Java’s designers took lessons from many of its features. •

1.5 A Java Road MapWith everything that’s going on, it’s hard to keep track of what’s available now, what’s promised, and what has been around for some time. Here’s a road map that imposes some order on Java’s past, present, and future.

1.5.1 The Past: Java 1.0 and Java 1.1

Java 1.0 provided the basic framework for Java development: the language itself plus packages that let you •write applets and simple applications. AlthoughJava1.0isofficiallyobsolete,itwillbesometimebeforevendorscatchupwiththenewerreleases.•Java 1.1 superseded Java 1.0. It incorporated major improvements in the AWT package (Java’s original GUI •facility) and many new features. Java 1.1 remains important, because it is supported natively by both the Netscape Navigator and Microsoft •Internet Explorer browsers. For various political reasons, the future of the browser world is uncertain; to execute applets using any features •of Java 2, you need to use the Java plug-in, which allows Netscape and IE to execute Java 2 code.

1.5.2 The Present: Java 2

Java 2 was released in December 1998, providing many improvements and additions. •The most notable addition is Swing, which is a new user interface toolkit with capabilities far exceeding AWT’s. •(Swing, AWT, and some other packages are now called the JFC, or Java Foundation Classes.) Here’s a brief overview of the most important features of the core Java 2 API:

JDBC (Java Database Connectivity): � A general facility for interacting with databases. (Introduced with Java 1.1.)RMI (Remote Method Invocation): � Java’s distributed objects system. RMI lets you call methods on objects hosted by a server running somewhere else on the network. (Introduced with Java 1.1.)Java Security: � A facility for controlling access to system resources, combined with a uniform interface to cryptography. Java Security is the basis for signed classes, which were discussed earlier.

Page 21: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

9

JFC (Java Foundation Classes): � A catch-all for a number of new features, including the Swing user interface components; “pluggable look-and-feel,” which means the ability of the user interface to adapt itself to the “look-and-feel” of the platform you’re using; drag and drop; and accessibility, which means the ability to integrate with special software and hardware for people with disabilities.Java 2D: � Part of JFC; enables high-quality graphics, font manipulation, and printing. Internationalization: � The ability to write programs that adapt themselves to the language the user wants to use; the program automatically displays text in the appropriate language. (Introduced with Java 1.1.)

Thefollowingfeaturesaren’tpartofthecoreJava2definition;youmayhavetodownloadthemseparately.•Most of them are what Sun calls “standard extensions”:

JNDI (Java Naming and Directory Interface): � A very general service for looking up resources. JNDI unifiesaccesstodirectoryserviceslikeLDAP,Novell’sNDS,andothers.JavaMail: � A uniform API for writing email software.Java 3D: � A facility for developing applications with 3D graphics.Java Media: � Another catch-all that includes Java 2D, Java 3D, the Java Media Framework (a framework for coordinating the display of many different kinds of media), Java Speech (for speech recognition and synthesis), Java Sound (high-quality audio), Java TV (for interactive television and similar applications), and others.Java Servlets: � A facility that lets you write custom Internet servers. It is most frequently used to write web server applications, but it’s much more general.Java Cryptography: � Actual implementations of cryptographic algorithms. (This package was separated from Java Security for legal reasons.)JavaHelp: � A facility for writing helps systems and incorporating them in Java programs.Enterprise JavaBeans: � A component architecture for building distributed server-side applications.Jini: � An extremely interesting catch-all that is designed to enable massively distributed computing, including computing on common household appliances. In a few years, your stereo may be able to execute Java programs.Java Card: � A version of Java for very small (i.e., credit card-sized) devices, which have severe limitations on speed and memory.

1.6 First ApplicationBefore getting into the details of the Java language, let’s jump right into some working code. •In this chapter, we will build a little friendly application that illustrates a number of techniques we use throughout •the book. We will take this opportunity to introduce general features of the Java language and of Java applications. •This chapter also serves as a brief introduction to the object-oriented and multithreaded features of Java. •Iftheseconceptsarenewtoyou,youcantakecomfortintheknowledgethatencounteringthemforthefirst•time in Java should be a straightforward and pleasant experience. If you have worked with another object-oriented or multithreaded programming environment, clear your mind; •you will especially appreciate Java’s simplicity and elegance.

1.7 HelloJava1In the tradition of introductory programming texts, we begin with Java’s equivalent of the archetypal "Hello •World" application. In the spirit of our new world, we will call it HelloJava. •We will take four passes at this example (HelloJava1, HelloJava2, etc.), adding features and introducing new •concepts along the way. Here’s a minimalist version:•

Page 22: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

10

//file: HelloJava1.java

public class HelloJava1 extends javax.swing.JComponent {public static void main(String[] args) {javax.swing.JFrame f = new javax.swing.JFrame("HelloJava1");f.setSize(300, 300);f.getContentPane().add(new HelloJava1( ));f.setVisible(true);{public void paintComponent(java.awt.Graphics g){g.drawString("Hello, Java!", 125, 95);} }

PlacethistextinafilecalledHelloJava1.java.Nowcompilethissource:

% javac HelloJava1.java

ThisproducestheJavabyte-codebinaryclassfileHelloJava1.class.

YoucanruntheapplicationbystartingtheJavaruntimesystem,specifyingtheclassname(notthefilename)asanargument:

% java HelloJava1

(The name of the Java interpreter varies among implementations. Microsoft’s is named jview, not java.) You should seetheproclamationshowninFigure1.3.Nowcongratulateyourself:youhavewrittenyourfirstapplication!Takea moment to bask in the glow of your monitor.

Fig. 1.3 HelloJava1 application

Page 23: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

11

When you click on the window’s close box, the window goes away, but your program will still be running.•To stop the runtime system and return control to your command-line interpreter, type Ctrl-C or whatever key •sequence stops a running application on your platform. We will remedy this shortcoming in a later version of the example.•HelloJava1 may be a small program, but there is actually quite a bit going on behind the scenes. Those few •lines represent the tip of an iceberg. What lies under the surface are layers of functionality provided by the Java language and its foundation class libraries.

Salutations, Java!

There are many ways to say “Hello, Java!” The simplest command-line version of HelloJava looks like this:

public class HelloJavaCommandLine { public static void main(String[] args) {System.out.println("Hello, Java!");} }

Weighinginatjustfivelines,thisprogramusestheSystemclasstowritesometexttotheconsole.TheHelloJava examples in this chapter are a little lengthier; they are structured to show off Java’s user interfacetoolkit,Swing,andtoprovideaquickflythroughoftheJavalanguageandlibraries.

If we were not concerned about the tutorial, we could create a graphic example that’s just as pithy as the command-line version, using the JOptionPane class:

public class HelloJavaSimple { public static void main(String[] args) { javax.swing.JOptionPane.showMessageDialog (null, "Hello, Java!");} }

1.8 ClassesThepreviousexampledefinesaclassnamedHelloJava1.•Classes are the fundamental building blocks of most object-oriented languages. •A class in Java is very much like a class in C++, and somewhat like a struct in C.•It’s a group of data items, with associated functions that perform operations on this data. •Thedataitemsinaclassarecalledfieldsorvariables;thefunctionsarecalledmethods.•A class might represent something concrete, like a button on a screen or the information in a spreadsheet, or •it could be something more abstract, such as a sorting algorithm or possibly the sense of ennui in your MUD character. A hypothetical spreadsheet class might, for example, have variables that represent the values of its individual •cells and methods that perform operations on those cells, such as “clear a row” or “compute values.” Our HelloJava1 class contains an entire Java application. •

Page 24: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

12

Itholdstwogeneraltypesofvariablesandmethods:thoseweneedforourspecificapplication’stasksandsome•special predesignated ones we provide to interact with the outside world. The Java runtime system, in this case the java command-line tool, calls methods in HelloJava1 to pass us •information and prod us to perform actions. OursimpleHelloJava1classimplementstwoimportantmethods.Thefirst,main(),iscalledwhentheapplication•isfirststarted.Thesecondmethod,paintComponent(),iscalledbyJavawhenit’stimeforourapplicationtodraw itself on the screen.

1.9 main( ) MethodWhen you run our example, what really happens? The java command looks in the HelloJava1 class to see if it •contains a special method called main( ). If it does, this method is run. The main( ) method is simply an entry point for an application. •Itisapieceofcodethatyouwanttoberunwhentheapplicationfirststarts.•The main( ) method sets up a window (a JFrame) that will contain the visual output of the HelloJava1 class. •What really interests us here is not the main( ) method but the rest of the class.•We will go through several incarnations of this class, adding features and methods.•But the main( ) method will remain largely unchanged, keeping its basic function of creating a window that •holds the HelloJava example.Let us quickly walk through the main( ) method, just so you know what it does. First, main( ) creates a JFrame, •a window that will hold our example:

javax.swing.JFrame f = new javax.swing.JFrame(“HelloJava1”);

The new word in this line of code is tremendously important: javax.swing.JFrame ( just JFrame for short) is the name of a class that represents a window you can see on your screen. The class itself is just a template, like a building plan. The new keyword tells Java to allocate memory and initialize a new JFrame object.When framewindows are first created, they are very small.Our next task is to set the size to somethingreasonable:

f.setSize(300, 300);

Then we create our actual example and put it inside the frame window:

f.getContentPane().add(new HelloJava1( ));

Here, we’re actually creating a new HelloJava1 object and placing it inside the JFrame we just created.

f.setVisible(true);

main()’sfinal task is toshowtheframewindowanditscontents,whichotherwisewouldbe invisible.An•invisible window makes for a pretty boring application.That is the whole main( ) method. •As we progress through the examples in this chapter, it will remain mostly unchanged as the HelloJava class •evolves around it.

Page 25: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

13

1.10 Classes and ObjectsA class is a blueprint for a part of an application; it lists methods and variables that go into making up that •part. Many individual working copies of a given class can exist while an application is active. •These individual incarnations are called instances of the class, or objects. •Two instances of a given class may contain different data, but they always have the same methods.•As an example, consider a Button class. There is only one Button class, but an application can create many •different Button objects, each one an instance of the same class. Furthermore, two Button instances might contain different data, perhaps giving each a different appearance •and performing a different action. In this sense, a class can be considered a mold for making the object it represents: something like a cookie cutter •stamping out working instances of itself in the memory of the computer. The term object is very general and in some other contexts is used almost interchangeably with class. •Objects are the abstract entities all object-oriented languages refer to in one form or another. •We will use object as a generic term for an instance of a class. •We might, therefore, refer to an instance of the Button class as a Button, a Button object, or, indiscriminately, •as an object. The main( ) method in the previous example creates a single instance of the HelloJava1class and shows it in •an instance of the JFrame class. You could modify main( ) to create many instances of HelloJava1, perhaps each in a separate window.•

1.11 Variables and Class TypesInJava,everyclassdefinesanewtype(datatype).•A variable can be of this type and then hold instances of that class. •A variable could, for example, be of type Button and hold an instance of the Button class, or of type SpreadSheetCell •andholdaSpreadSheetCellobject,justasitcouldbeanyofthemorefamiliartypessuchasintorfloat.Ignoring the main( ) method for the moment, there is only one variable in our simple HelloJava example. It’s •found in the declaration of the paintComponent( ) method:

public void paintComponent(java.awt.Graphics g) {...}

Just like functions in C (and many other languages), a method in Java declares a list of variables that hold its •arguments,anditspecifiesthetypesofthosearguments.Our paintComponent( ) method takes one argument named (somewhat tersely) g, which is of type Graphics. •When the paintComponent( ) method is invoked, a Graphics object is assigned to g, which we use in the body •of the method. We will say more about paintComponent( ) and the Graphics class in a moment.•Butfirst,afewwordsaboutvariables.Wehavelooselyreferredtovariablesasholdingobjects.• The variables including class types may not contain many objects in reality as expected. The class type variables •act as objects references. A reference is a pointer to or a name for an object. •If you declare a class-type variable without assigning it to an object, it does not point to anything. •It is assigned the default value of null, meaning “no value.” •If you try to use a variable with a null value as if it were pointing to a real object, a runtime error •(NullPointerException) occurs.

Page 26: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

14

Wheredoyougetaninstanceofaclasstoassigntoavariableinthefirstplace?Theansweristhroughtheuse•of the new operator.

1.12 InheritanceJava classes are arranged in a parent-child hierarchy, in which the parent and child are known as the superclass •and subclass, respectively. In Java, every class has exactly one superclass (a single parent), but possibly many subclasses.•The only exception to this rule is the Object class, which sits atop the entire class hierarchy; it has no •superclass.The declaration of our class in the previous example uses the keyword extends to specify that HelloJava1 is a •subclass of the JComponent class:

public class HelloJava1 extends javax.swing.JComponent {...}

A subclass may be allowed to inherit some or all of the variables and methods of its superclass. •Through inheritance, the subclass can use those variables and methods as if it has declared them itself. •A subclass can add variables and methods of its own, and it can also override the meaning of inherited variables •and methods. When we use a subclass, overridden variables and methods are hidden (replaced) by the subclass’s own versions •of them. In this way, inheritance provides a powerful mechanism whereby a subclass can refine or extend its •superclass.Forexample,thehypotheticalspreadsheetclassmightbesubclassedtoproduceanewscientificspreadsheet•class with extra mathematical functions and special built-in constants. Inthiscase,thesourcecodeforthescientificspreadsheetmightdeclaremethodsfortheaddedmathematical•functions and variables for the special constants, but the new class automatically has all the variables and methods that constitute the normal functionality of a spreadsheet; they are inherited from the parent spreadsheet class. Thismeansthescientificspreadsheetmaintainsitsidentityasaspreadsheet,andwecanuseitanywherethe•simpler spreadsheet is used. Our HelloJava1 class is a subclass of the JComponent class and inherits many variables and methods not explicitly •declared in our source code. These members operate in the same way as the ones we add or override.

1.13 JComponent ClassThe JComponent class provides the framework for building user interface components (called controls or •widgets in other windowing systems). Particular components, such as buttons, labels, and list boxes, are implemented as subclasses of JComponent. •We override methods in such a subclass to implement the behaviour of our particular component. This may •soundrestrictive,asifwearelimitedtosomepredefinedsetofroutines,butthatisnotthecaseatall.Keep in mind that the methods we are talking about are means of interacting with the windowing system. •A realistic application might involve hundreds or even thousands of classes, with legions of methods and variables •and multiple threads of execution. The vast majority of these are related to the particulars of our job. •TheinheritedmethodsoftheJComponentclass,andofotherpredefinedclasses,serveasaframeworkonwhich•to hang code that handles certain types of events and performs special tasks.The paintComponent( ) method is an important method of the JComponent class; we override it to implement •the way our particular component displays itself on the screen.

Page 27: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

15

The default behaviour of paintComponent( ) doesn’t do any drawing at all; here, we were overriding •paintComponent( ) to do something interesting. We don’t override any of the other inherited members of JComponent because they provide basic functionality •and reasonable defaults for this (trivial) example. As HelloJava grows, we will delve deeper into the inherited members and use additional methods. •Wewillalsoaddsomeapplication-specificmethodsandvariablesfortheneedsofHelloJava.•

1.14 Relationships and Finger PointingWe can correctly refer to HelloJava1 as a JComponent because subclassing can be thought of as creating an “is a” •relationship, in which the subclass is a kind of its superclass. HelloJava1 is therefore a kind of JComponent. When we refer to a kind of object, we mean any instance of that object’s class or any of its subclasses. •Later, we will look more closely at the Java class hierarchy and see that JComponent is itself a subclass of the •Containerclass,whichisfurtherderivedfromaclasscalledComponent,andsoon,asshowninfiguregiven

Object

Component

Container

Window

Frame

JFram

HelloJava JButton

JComponent

Fig. 1.4 Part of the Java class hierarchy

In this sense, a HelloJava1 object is a kind of JComponent, which is a kind of Container, and each of these can •ultimately be considered to be a kind of Component. It is from these classes that HelloJava1 inherits its basic graphical user interface functionality and the ability to •have other graphical components embedded within it.Componentisasubclassofthetop-levelObjectclass,soalloftheseclassesdefinekindsofObjects.•EveryotherclassintheJavaAPIinheritsbehaviourfromObject,whichdefinesafewbasicmethods.•We will continue to use the word object (lowercase o) in a generic way to refer to an instance of any class; we •willuseObjecttoreferspecificallytothatclass.

1.15 PackagesIn our previous example, the JComponent class is referenced by its fully qualified name javax.swing.•JComponent:

public class HelloJava1 extends javax.swing.JComponent {...}

Theprefixontheclassnameidentifiesitasbelongingtothejavax.swingpackage.•Packages provide a means for organizing Java classes. •

Page 28: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

16

A package is a group of Java classes that are related by purpose or by application.•Classes in the same package have special access privileges with respect to one another and may be designed •to work together. Package names are hierarchical and are used somewhat like Internet domain and host names, to distinguish •groups of classes by organization and application. Classes may be dynamically loaded over networks from arbitrary locations; within this context, packages provide •a crude namespace of Java classes. javax.swingidentifiesaparticularpackagethatcontainsclassesrelatedtoSwing,Java2’sfancygraphicaluser•interface toolkit. javax.swing.JComponentidentifiesaspecificclass,theJComponentclass,withinthatpackage.•The java. hierarchy is special. Any package that begins with java is part of the core Java API and is available •on any platform that supports Java. While javax normally denotes a standard extension to the core platform, javax.swing is an exception it really •is part of the core API. Figure shown below illustrates some of the core Java packages, showing a representative class or two from •each.

JAVA

Long io Applet Net awtSwing

JAVAX

Image Peer

String File Applet URLGraphics

Component

JButton

JComponent

Colour Model

SocketAudioClipThread

Fig. 1.5 Some core Java packages

Some other notable core packages include:•java.lang � : Which contains fundamental classes needed by the Java language itselfjava.awt: � Which contains classes of the pre-Java 2 Abstract Window Toolkitjava.net: � Which contains the networking classes.

A few classes contain methods that are not written in Java, but are instead part of the native Java implementation •on a particular platform. These are the only classes that have to be ported to a new platform. •They form the basis for all interaction with the operating system. •All other classes are built on or around these and are completely platform-independent.•

Page 29: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

17

1.16 paintComponent( ) MethodThe source for our HelloJava1 class defines a method, paintComponent( ), that overrides the •paintComponent( ) method from the JComponent class:

public void paintComponent(java.awt.Graphics g) { g.drawString("Hello, Java!", 125, 95);}

The paintComponent( ) method is called when it is time for our example to draw itself on the screen. •It takes a single argument, a Graphics object, and does not return any type of value (void) to its caller.•Modifiersarekeywordsplacedbeforeclasses,variables,andmethodstoaltertheiraccessibility,behaviour,or•semantics. paintComponent( ) is declared as “public”, which means it can be invoked (called) by methods in classes other than HelloJava1. In this case, it is the Java windowing environment that is calling our paintComponent() method. •A method or variable declared as “private” is inaccessible from outside of its class.•The Graphics object, an instance of the Graphics class, represents a particular graphical drawing area. (It is also •called a graphics context.) It contains methods that can be used to draw in this area, and variables that represent characteristics such as •clipping or drawing modes. The particular Graphics object we are passed in the paintComponent ( ) method corresponds to our component’s •area of the screen.The Graphics class provides methods for rendering shapes, images, and text. •InHelloJava1,weinvokethedrawString()methodofourGraphicsobjecttoscrawlourmessageatthespecified•coordinates.As in C++, a method or variable of an object is accessed in a hierarchical way by appending a dot (.) and its •name to the object that holds it. We invoked the drawString( ) method of the Graphics object (referenced by our g variable) in this way:•

g.drawString("Hello, Java!", 125, 95);

Page 30: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

18

Summary The greatest challenges and most exciting opportunities for software developers today lie in harnessing the •power of networks. Applications created today, whatever their intended scope or audience, will almost certainly be run on machines •linked by a global network of computing resources. The increasing importance of networks is placing new demands on existing tools and fuelling the demand for •a rapidly growing list of completely new kinds of applications. The Java™ programming language, developed at Sun Microsystems under the guidance of Net luminaries James •Gosling and Bill Joy, is designed to be a machine-independent programming language that is both safe enough to traverse networks and powerful enough to replace native executable code. The seeds of Java were planted in 1990 by Sun Microsystems patriarch and chief researcher, Bill Joy. Since •Sun’s inception in the early ‘80s, it has steadily pushed one idea:”The network is the computer”. At the time though, Sun was competing in a relatively small workstation market, while Microsoft was beginning •its domination of the more mainstream, Intel-based PC world. When Sun missed the boat on the PC revolution, Joy retreated to Aspen, Colorado, to work on advanced •research. ItwouldnotbeoverdoingittosaythatJavahascaughtonlikewildfire.•Evenbeforeitsfirstofficialrelease,whileJavawasstillanon-product,nearlyeverymajor industryplayer•jumped on the Java bandwagon. Hardware implementations of Java could power inexpensive network terminals, PDAs, and other information •appliances, to take advantage of transportable Java applications.Software implementations of Java are available now for portable computing devices like the popular Palm™ •PDA.WhenyoufirstlookatJavacode,you’llseethatthebasicsyntaxlooksalotlikeCorC++.Butthat’swhere•the similarities end. Java is by no means a direct descendant of C or a next-generation C++. •Java also comes with a large base of core classes for common tasks such as building GUIs and doing network •communications. But along with these features, Java has the scalability and software-engineering advantages of more static languages. One reason is that they never developed a standard portable binding to operating system services, like the C •standard library or the Java core classes. Smalltalk is compiled to an interpreted byte-code format, and it can be dynamically compiled to native code •onthefly,justlikeJava.With everything that’s going on, it’s hard to keep track of what’s available now, what’s promised, and what has •been around for some time. Here’s a road map that imposes some order on Java’s past, present, and future.

References Y. Daniel Liang,2010. • Introduction to Java Programming. Prentice Hall. Stephen J. Chapman, 1999. • Introduction to Java. Prentice Hall. Y. Daniel Liang, 2004. Introduction to Java programming with JBuilder. Prentice Hall. •

Recommended Reading Nell B. Dale, Chip Weems, Mark R. Headington, 2002. • Introduction to Java and software design. Jones & Bartlett Learning. Kenneth A. Barclay, John Savage, W. John Savage, 2007. • Groovy programming: an introduction for Java developers. Morgan Kaufmann. David Flanagan, 2005.• Java in a nutshell. O'Reilly Media.

Page 31: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

19

Self AssessmentThe greatest challenges and most exciting opportunities for software developers today lie in harnessing the 1. power of _____________.

networksa. hubs b. systemsc. organization d.

_____________could be independent programs in themselves, or sophisticated frontends to programs running 2. on a server.

Appletsa. java scriptb. core java c. Appled.

Java has also become an important platform for _______________applications.3. server-surfacea. server-faceb. server-planec. server-sided.

The seeds of Java’s remarkably permissive licensing scheme were sown by _________failure. 4. NexS’sa. NeWS’sb. NeWW’sc. NeSS’sd.

The FirstPerson team worked on developing software for information appliances, such as cellular phones and 5. ________.

personal digital supporter.a. personal digital subordinates.b. personal digital assistants.c. personal digital leaders. d.

Memory and bandwidth limitations dictated ________code. 6. smallandefficienta. big and resourcefulb. undersized and professionalc. miniature and abled.

______was small, robust, architecture-independent, and object-oriented. 7. Ca. C++b. Javac. Oakd.

Page 32: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

20

Sun quickly changed focus, and with a little retooling, Oak became______. 8. C++a. C#b. .netc. Javad.

________included Microsoft, Intel, IBM, and virtually all major hardware and software vendors.9. Java leasea. Java recognizeb. Java licensec. Java sanctiond.

Java is both a ________language. 10. compiled and an interpreteda. amassed and an understandb. accumulated and an inferredc. collected and an construedd.

Page 33: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

21

Chapter II

Object Oriented Programming

Aim

The aim to this chapter is to:

elucidate the concept of OOP•

explain the theory of inheritance in Java •

elaborate the concept of abstraction •

explain polymorphism in Java •

Objectives

The objectives of this chapter are to:

get an overview of encapsulation used in Java•

explainthesignificanceofeventsinjava•

discuss programming paradigms in java •

elucidate functional programming•

Learning outcome

At the end of this chapter, the students will be able to:

understand the messages and responsibilities in Java •

describe objects and classes in java •

evaluate various types of the java •

Page 34: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

22

2.1 Introduction to OOPObject Oriented Programming, also known as OOP, is a computer science term which is used to describe a •computer application that is composed of multiple objects which are connected to each other. Traditionally, most computer programming languages were simply a group of functions or instructions. •With OOP, every object can handle data, get messages, and transfer messages to other objects. •The objects will all act as independent units in their own right, and they will be responsible for carrying out a •certain process. Becausetheobjectsarenotdependentoneachother,OOPisseenasbeingmoreflexiblethanoldermethods•of programming. It has become quite popular, and it is now used in a number of advanced software engineering projects. •Many programmers feel that object oriented programming is easier for beginners to learn than previous •programming methods. Becauseitiseasiertolearn,itcanalsobeanalyzedandmaintainedwithoutalargeamountofdifficulty.However,•there are some people that feel that OOP is more complicated than older programming methods. To understand object oriented programming, there are a few concepts you will need to become familiar with. •Thefirstconceptthatyouwillneedtolearniscalleda“class.”•Aclasscreatestheattributesofathing,anditwillalsodefinetheprocessesthatthethingcancarryout.For•example, a class called "cats" will have the attributes which are commonly found with cats, such as the ability to purr. A class will bring about modularity within the objected oriented computer application. Someone who is not a •programmershouldbeabletofindaclass.The reason for this is because the attributes of the class should be something that will make sense to them. •It is also important for the code of a class to be self contained to a certain degree. •When code is written with relevant names, it will be easier to understand. •Making sure the code is self-contained will allow one part of the application to be updated without needing to •change the other parts. It is this modularity that makes OOP an effective programming method. •It will also help the application solve the problems that it was designed for. •The next concept that you will want to become familiar with is an “object.” •Anobjectcanbedefinedasaspecificinstanceofaclass.•As an example, while the class Cats will provide all the attributes that are found in all cats, the “object” named •Betsyisaspecificcat.While it shares the same attributes which are found in all cats, it has fur with a unique colour. •In object oriented programming, a programmer would say that the object Betsy is a run-time instance of the •class Cats. A class may also be divided into sub-groups. •Certainvariationsofaclassmaynotbeaspecificobject.•The class Cats may have a sub-group which consists of multiple cat breeds. •For example, if Betsy were a Persian cat, it would be an instance of the Persian cat sub-group. •Every object within an OOP language will share some attributes with the parent class, but it will also have •unique attributes as well. The next concept that you will want to become familiar with is “method.” •Amethodmayalsobecalleda“message”andcanbedefinedastheabilitiesofanobject.•Because Betsy is a cat, Betsy can purr. Because of this, “purr” is a method that Betsy has.•

Page 35: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

23

Betsy may have a number of other methods. •When a method is used within an object oriented programming language, it will only affect a single object. This •is true even if the method is designed for the entire class.While all cats can purr, you will only need one cat to do it. •Methods can further be broken down into commands, call-backs, or queries. •A query will tell you about the state of the object, and a command will cause that object to carry out a task. •A call-back is a method that is composed of a part within an object. •The part will notify its parent that an event has taken place, and the object may need to react to the event.•

2.2 Object Oriented Programming ConceptsThree of the most basic concepts for object oriented programmings are Classes, Objects, and Methods. However, •there are a few more concepts that you will want to become familiar with.These are Inheritance, Abstraction, Polymorphism, Event, and Encapsulation.•In this article, it will be using the class Cats as an example. •

InheritanceInheritance will allow a sub-group to make a connection with the associates of its parent class. For example, •let's say the class Cats decides to create a method called purr() and a property named Colorfur. Asthenameimplies,apropertyisaspecificattributewhichisconnectedtoanobject.•Every sub-group will be able to inherit the associates, and this means the developer only needs to create the •code for them one time. The traits that are inherited by the sub-group can be changed. For example, the Persian cat class may choose to •make the Colorfur white for their default colour. In contrast, another cat breed may choose a different Colorfur trait. •It is also possible for the sub-group to add new associates. •IfaspecificcatClasssub-groupwantstosetadefaulteyecolour,thiscanbeinheritedaswell.•Some object oriented programming languages may also allow a class to inherit traits from multiple ancestors, •and this is called multiple inheritance. Some programs may not allow this. One object-oriented concept that helps objects work together is inheritance.•Inheritancedefinesrelationshipsamongclassesinanobject-orientedlanguage.•In the Java programming language, all classes descend from java.lang.Object and implement its methods.•The following diagram shows the class hierarchy as it descends from java.lang.Object for the classes in the •user interface example above. The java.lang.Object methods are also shown because they are inherited and implemented by all of its subclasses, •which is every class in the Java API libraries.java.lang.Objectdefinesthecoresetofbehavioursthatallclasseshaveincommon.•Asyoumovedownthehierarchy,eachclassaddsitsownsetofclass-specificfieldsandmethodstowhatit•inherits from its superclass or superclasses. Thejava.awt.swing.JFrameclassinheritsfieldsandmethodsfromjava.awt.Frame,whichinheritsfields,and•methodsfromjava.awt.Container,whichinheritsfieldsandmethodsfromjava.awt.Component,whichfinallyinheritsfromjava.lang.Object,andeachsubclassaddsitsownfieldsandmethodsasneeded.

Page 36: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

24

java.lang.String

java.awt.event.WindowAdapter

java.util.EventObject

java.awt.Component

java.awt.Container

java.awt.swing.JPanel

java.awt.swing.JLabel

java.awt.Window

java.awt.Frame java.awt.swing.JFrame

java.awt.AWTEvent

java.awt.WindowEvent

java.awt.ComponentEvent

java.lang.Objectclone ()equal ()finalise()getClass ()hashCode ()notify ()notifyAll ()Object ()toString ()wait ()wait (long timeout)wait (long timeout, int nanos)

Fig. 2.1 Inheritance

AbstractionThe next concept that you will want to be familiar with is called “abstraction.”•Abstractioncanbedefinedastheprocessinwhichanapplicationwillignorethecharacteristicsofasub-group•and work on a general level when it is needed. As an example, Betsy the cat may be treated as a cat when it is necessary, but she may also be processed as a •Felidae, which is a superclass of cat family.

Page 37: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

25

PolymorphismPolymorphism is an important concept of object oriented programming that you will want to become •familiar. Itcanbedefinedasabehaviourwhichisdependentontheclasstowhichitisconnected.•As an example, if a Cat is sent a command to speak, this may cause it to purr, while a dog will bark, or a lion •may roar.

EncapsulationAnyone who is interested in object oriented programming will also need to know encapsulation. •Encapsulation will allow a class to hide information from objects that may use the code. For example, the Cat •class will have a purr() method. A code will be written which will explain how the cat purrs.•Despite this, it is not necessary for Betsy the cat to know how she purrs.•Encapsulation makes it easier for the developer to change the code without having to change the code for •Betsy. When the structure of class is hidden, it is harder for it to be used in the wrong way. •Encapsulation will basically state which class is allowed to use the members of a certain object. This concept •makes it easier for programmers to deal with or avoid errors when developing a program. The members within OOP can be categorized as being protected, public, or private.•

EventThe last concept that you will want to become familiar with is called an event. •Aneventcansimplybedefinedasanythingthathappenstoanobject.•Generally, an event is something that will cause the object to react with a method.•Another term that advanced programmers may run into is called multiple inheritance.•It is a situation where a class is able to inherit traits from a number of different superclasses. •A multiple inheritance can create a number of perplexing situations. Because of this, there is debate in the •programmingcommunityaboutwhetheritisbeneficialorrisky.One example of a program which deals with multiple inheritances is Java. •It will permit a class to have interfaces which come from multiple parents, but it can only inherit methods from •a single parent. Other programming languages which use this approach are C# and Visual Basic. •It is important to understand the various concepts which are connected to object oriented programming. •Onceyouunderstandtheconcepts,youwillbeequippedtobeginlearningspecificOOPlanguages.•There are a number of popular object oriented programming languages that are being used, and one of the most •popular is Java.

2.3 Object Oriented ProgrammingObject-orientation is a set of tools and methods that enable software engineers to build reliable, user friendly, •maintainable,welldocumented,reusablesoftwaresystemsthatfulfillstherequirementsofitsusers.It is claimed that object-orientation provides software developers with new mind tools to use in solving a wide •variety of problems. Object-orientation provides a new view of computation. •A software system is seen as a community of objects that cooperate with each other by passing messages in •solving a problem.

Page 38: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

26

An object-oriented programming language provides support for the following object-oriented concepts:•Objects and Classes �Inheritance �Polymorphism �Dynamic binding �

2.4 Programming ParadigmsObject-oriented programming is one of several programming paradigms. •Otherprogrammingparadigmsincludetheimperativeprogrammingparadigm(asexemplifiedbylanguages•such as Pascal or C), the logic programming paradigm (Prolog), and the functional programming paradigm (exemplifiedbylanguagessuchasML,HaskellorLisp).Logic and functional languages are said to be declarative languages. •We use the word paradigm to mean “any example or model”. This usage of the word was popularised by the •science historian Thomas Kuhn. He used the term to describe a set of theories, standards and methods that together represent a way of organising knowledge a way of viewing the world. Thus a programming paradigm is a

. . . Way of conceptualising what it means to perform computation and how tasks to be carried out on a computer should be structured and organised. We can distinguish between two types of programming languages: •

Imperative languages �Declarative languages �

Imperative knowledge• describes how-to knowledge while declarative knowledge is what-is knowledge. Declarative program describes what something is like, rather than how to create it. This is a different approach from traditional imperative programming languages such as FORTRAN, and C, which require the programmer to specify an algorithm to be run. In short, imperative programs make the algorithm explicit and leave the goal implicit, while declarative programs •make the goal explicit and leave the algorithm implicit.Imperative languages require you to write down a step-by-step recipe specifying how something is to be •done. For example to calculate the factorial function in an imperative language we would write something like:•

public int factorial(int n) {int ans=1;for (int i = 2; i <= n; i++){ans = ans ∗ i;{return ans;{

Here, we give a procedure (a set of steps) that when followed will produce the answer.•

2.5 Functional programmingFunctional programming is a programming paradigm that treats computation as the evaluation of mathematical •functions. Functionalprogrammingemphasizesthedefinitionoffunctions,incontrasttoproceduralprogramming,which•emphasizes the execution of sequential commands. The following is the factorial function written in a functional language called • Lisp:

Page 39: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

27

(defun factorial (n)(if (<= n 1) 1 (∗ n (factorial (− n 1)))))

Noticethatitdefinesthefactorialfunctionratherthangivethestepstocalculateit.•Thefactorialofnisdefinedas1ifn<=1elseitisn• ∗factorial(n−1)

2.6 Logic ProgrammingProlog (PROgramming in LOGic) is the most widely available language in the logic programming paradigm. •It is based on the mathematical ideas of relations and logical inference. •Prolog is a declarative language meaning that rather than describing how to compute a solution, a program •consists of a data base of facts and logical relationships (rules) which describe the relationships which hold for the given application. Rather then running a program to obtain a solution, the user asks a question. •When asked a question, the run time system searches through the data base of facts and rules to determine (by •logical deduction) the answer. Logic programming was an attempt to make a programming language that enabled the expression of logic •insteadofcarefullyspecifiedinstructionsonthecomputer.In the logic programming language Prolog you supply a database of facts and rules; you can then perform •queriesonthedatabase.Thisisalsoanexampleofadeclarativestyleofprogrammingwherewestateordefinewhat we know. In the following example, we declare facts about some domain. •We can then query these facts we can ask, for example, are sally and tom siblings?•

sibling(X,Y):−parent(Z,X),parent(Z,Y).parent(X,Y):−father(X,Y).parent(X,Y):−mother(X,Y).mother(trude, sally).father(tom, sally).father(tom, erica).father(mike, tom).

The factorial function is written in prolog as two rules. Again, notice the declarative nature of the program.•

fac(0,1).fac(N,F):−N>0,MisN−1,fac(M,Fm),F is N ∗ Fm.

2.7 Object Orientation as a New Paradigm: The Big PictureIt is claimed that the problem-solving techniques used in object-oriented programming more closely models •the way humans solve day-to-day problems. So let’s consider how we solve an everyday problem: •

SupposeyouwantedtosendflowerstoafriendnamedRobinwholivesinanothercity. �Tosolvethisproblemyousimplywalktoyournearestfloristrunby,let’ssay,Fred. �

Page 40: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

28

YoutellFredthekindsofflowerstosendandtheaddresstowhichtheyshouldbedelivered. �Youcanbeassuredthattheflowerswillbedelivered. �Now, let’s examine the mechanisms used to solve your problem. �Youfirstfoundanappropriateagent(Fred,inthiscase)andyoupassedtothisagentamessagecontaining �a request.It is the responsibility of Fred to satisfy the request. �There is some method (an algorithm or set of operations) used by Fred to do this. �You do not need to know the particular methods used to satisfy the request such information are hidden �from view.Offcourse,youdonotwanttoknowthedetails,butoninvestigationyoumayfindthatFreddelivereda �slightlydifferentmessagetoanotherfloristinthecitywhereyourfriendRobinlives.Thatfloristthenpassesanothermessagetoasubordinatewhomakesthefloralarrangement.Theflowers,alongwithyetanothermessage,arepassedontoadeliverypersonandsoon.Thefloristsalso �haveinteractionswithwholesalerswho,inturn,hadinteractionswithflowergrowersandsoon.Thisleadstoourfirstconceptualpictureofobject-orientedprogramming: �An object-oriented program is structured as community of interacting agents called objects. Each object �has a role to play. Each object provides a service or performs an action that is used by other members of the community.

2.8 Messages and ResponsibilitiesMembers of an object-oriented community make requests of each other. The next important principle explains the use of messages to initiate action:

Action is initiated in object-oriented programming by the transmission of a message to an agent (an object) •responsible for the actions. The message encodes the request for an action and is accompanied by any additional information (arguments/•parameters) needed to carry out the request. The receiver is the object to whom the message is sent. •If the receiver accepts the message, it accepts responsibility to carry out the indicated action. •In response to a message, the receiver will perform some method to satisfy the request. •There are some important issues to point out here:•

The client sending the request need not know the means by which the request is carried out. In this we see �the principle of information hiding. Anotherprincipleimplicitinmessagepassingistheideaoffindingsomeoneelsetodotheworki.e.reusing �components that may have been written by someone else. The interpretation of the message is determined by thereceiverandcanvarywithdifferentreceivers.Forexample,ifyousentthemessage“deliverflowers”toafriend,shewillprobablyhaveunderstoodwhatwasrequiredandflowerswouldstillhavebeendeliveredbutthemethodsheusedwouldhavebeenverydifferentfromthatusedbytheflorist.In object-oriented programming, behaviour is described in terms of responsibilities. �Client’s requests for actions only indicate the desired outcome. The receivers are free to pursue any technique �that achieves the desired outcomes. Thinking in this way allows greater independence between objects. �Thus,objectshaveresponsibilitiesthattheyarewillingtofulfillonrequest. �The collection of responsibilities associated with an object is often called a protocol. �

Page 41: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

29

2.9 Classes and InstancesThe next important principle of object-oriented programming is•All objects are instances of a class. The method invoked by an object in response to a message is determined by the class of the receiver. All objects of a given class use the same method in response to similar messages.Fredisaninstanceofacategoryorclassofpeoplei.e.Fredisaninstanceofaclassofflorists.•Thetermfloristrepresentsaclassorcategoryofallflorists.•Fred is an object or instance of a class. •We interact with instances of a class but the class determines the behaviour of instances.•We can tell a lot about how Fred will behave by understanding how Florists behave. •Weknow,forexample,thatFred,likeallfloristscanarrangeanddeliverflowers.•In the real world there is this distinction between classes and objects. •Real-world objects share two characteristics. They all have state and behaviour. For example, dogs have state •(name, colour, breed, hungry) and behaviour (barking, fetching, wagging tail). Students have state (name, student number, courses they are registered for, gender) and behaviour (takes tests, •attend courses, write tests, party).

Methods (behaviour)

Variables (state)

Fig. 2.2 Object

2.10 Fundamentals of Objects and ClassesWe move now from the conceptual picture of objects and classes to a discussion of software classes and •objects. Objects are closely related to classes. •A class can contain variables and methods. •If an object is also a collection of variables and methods, how do they differ from classes?•

2.11 Objects and ClassesLet us discuss object and classes in detail:Objects

In object-oriented programming we create software objects that model real world objects.•Software objects are modelled after real-world objects in that they too have state and behaviour. •A software object maintains its state in one or more variables. •Avariableisanitemofdatanamedbyanidentifier.•A software object implements its behaviour with methods. •A method is a function associated with an object.•

Page 42: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

30

Definition: An object is a software bundle of variables and related methods. An object is also known as an instance. •An instance refers to a particular object. For example, Karuna’s bicycle is an instance of a bicycle it refers to •a particular bicycle.SandileZumaisaninstanceofaStudent.•The variables of an object are formally known as instance variables because they contain the state for a particular •object or instance. In a running program, there may be many instances of an object. For example, there may be many Student •objects. Each of these objects will have their own instance variables and each object may have different values stored in •their instance variables. For example, each Student object will have a different number stored in its StudentNumber variable.

2.12 EncapsulationObject diagrams show that an object’s variables make up the center, or nucleus, of the object. •Methods surround and hide the object’s nucleus from other objects in the program.•Packaging an object’s variables within the protective custody of its methods is called encapsulation.•

Message

Object B

Object A

Fig. 2.3 Messages

Encapsulating related variables and methods into a neat software bundle is a simple yet powerful idea that provides twobenefitstosoftwaredevelopers:

Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Also, an object can be easily passed around in the system. You can give your bicycle to someone else, and it will still work.

Information-hiding: An object has a public interface that other objects can use to communicate with it. The object can maintain private information and methods that can be changed at any time without affecting other objects that depend on it.

Page 43: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

31

2.13 MessagesSoftware objects interact and communicate with each other by sending messages to each other. •When object A wants object B to perform one of B’s methods, object A sends a message to object B. •The three parts for the message System.out.println {‘‘Hello World’’}; are:•

The object to which the message is addressed (System.out) �The name of the method to perform (println) �Any parameters needed by the method (“Hello World!”) �

2.14 ClassesIn object-oriented software, it’s possible to have many objects of the same kind that share characteristics: •rectangles, employee records, video clips and so on. A class is a software blueprint for objects. A class is used to manufacture or create objects. •The class declares the instance variables necessary to contain the state of every object.•The class would also declare and provide implementations for the instance methods necessary to operate on •the state of the object.

Definition: Aclassisablueprintthatdefinesthevariablesandthemethodscommontoallobjectsofacertainkind.

After you have created the class, you can create any number of objects from that class. •A class is a kind of factory for constructing objects. •The non-static parts of the class specify, or describe, what variables and methods the objects will contain. •This is part of the explanation of how objects differ from classes: Objects are created and destroyed as the •program runs, and there can be many objects with the same structure, if they are created using the same class.Aclassisastructurethatdefinesthedataandthemethodstoworkonthatdata.•When you write programs in the Java language, all program data is wrapped in a class, whether it is a class you •write or a class you use from the Java platform API libraries.TheExampleProgramclass from the simpleprogram in thefirst lessonofPart 1 is a programmer-written•class that uses the java.lang.System class from the Java platform API libraries to print a character string to the command line.

class ExampleProgram { public static void main(String[] args){ System.out.println("I'm a simple Program"); }}

ClassesintheJavaplatformAPIlibrariesdefineasetofobjectsthatshareacommonstructureandbehaviour.•Thejava.lang.Systemclassusedintheexampledefinessuchthingsasstandardinput,output,anderrorstreams,•and access to system properties. Incontrast,thejava.lang.Stringclassdefinescharacterstrings.•In the example, you do not see an explicit use of the String class, but in the Java language, a character string •can be used anywhere a method expects to receive a String object. During execution, the Java platform creates a String object from the character string passed to the System.•out.println call, but your program cannot call any of the String class methods because it did not instantiate the String object.

Page 44: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

32

If you want access to the String methods, you can rewrite the example program to create a String object as •follows. This way, you can call a method such as the String.concat method that adds text to the original string.•

class ExampleProgram { public static void main(String[] args){ String text = new String("I'm a simple Program "); System.out.println(text); String text2 = text.concat( "that uses classes and objects"); System.out.println(text2); }}

The output looks like this:I'm a simple Program I'm a simple Program that uses classes and objects

2.15 TypesJava,likemostprogramminglanguagesclassifiesvaluesandexpressionsintotypes.Forexample,String’sand•int’s are types. Atypebasicallyspecifiestheallowedvaluesandallowedoperationsonvaluesofthattype.•

Definition: A type is a set of values together with one or more operations that can be applied uniformly to all these values.

A type system basically gives meaning to collections of bits. •Because any value simply consists of a set of bits in a computer, the hardware makes no distinction between •memoryaddresses,instructioncode,characters,integersandfloating-pointnumbers.Types inform programs and programmers how they should treat those bits. •Forexampletheintegersareatypewithvaluesintherange−2,147,483,648to+2,147,483,647andvarious•allowed operations that include addition, subtraction, modulus etc.The use of types by a programming language has several advantages:•

SafetyUse of types may allow a compiler to detect meaningless or invalid code. For example, we can identify an expression”Hello, World” / 3 as invalid because one cannot divide a string literal by an integer. Strong typing offers more safety.

OptimizationStatic type-checking may provide useful information to a compiler. The compiler may then be able to generate moreefficientcode.

DocumentationTypes can serve as a form of documentation, since they can illustrate the intent of the programmer. For instance, timestamps may be a subtype of integers but if a programmer declares a method as returning a timestamp rather than merely an integer, this documents part of the meaning of the method.

Page 45: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

33

AbstractionTypes allow programmers to think about programs at a higher level, not bothering with low-level implementation. For example, programmers can think of strings as values instead of as a mere array of bytes.

There are fundamentally two types in JAVA: primitive types and objects types i.e. any variable you declare are •either declared to be one of the primitive types or an object type.int, double and char are the built-in, primitive types in JAVA. •The primitive types can be used in various combinations to create other, composite types.•Everytimewedefineaclass,weareactuallydefininganewtype.Forexample,theStudentclassdefinedabove•introduces a new type. We can now use this type like any other type: we can declare variables to be of this type and we can use it as •a type for parameters of methods.Before a variable can be used, it must be declared. •A declaration gives a variable a name, a type and an initial value for e.g. int x = 8 declares x to be of type int. •Allobjectsthatwedeclarealsohavetobeofaspecifiedtypethetypeofanobjectistheclassfromwhichitis•created. Thus, when we declare objects we state the type like so: •Student st = newStudent();. This statement declares the variable st to be of type Student. This statement creates •anewobjectofthespecifiedtypeandrunstheStudentconstructor.The constructor’s job is to properly initialize the object. •The String type is another example of an object type. •Student and String are composite types and give us the same advantages as the built-in types. •The ability to create our own types is a very powerful idea in modern languages. •When declaring variables, we can assign initial values. •If you do not specify initial values, the compiler automatically assigns one: Instance variables of numerical •type (int, double, etc.) are automatically initialized to zero; Boolean variables are initialized to false; and char variables, to the Unicode character with code number zero. The default initial value of object types is null.

2.16 Introduction to EnumsJAVAcomeswitheightbuilt-inprimitive typesanda largesetof types thataredefinedbyclassessuchas•String. Buteventhislargecollectionoftypesisnotsufficienttocoverallthepossiblesituationsthataprogrammer•might have to deal with. So, an essential part of JAVA, just like almost any other programming language, is the ability to create new •types. Forthemostpart,thisisdonebydefiningnewclasses.•Butwewilllookhereatoneparticularcase:theabilitytodefineenums(shortforenumeratedtypes).•Enums are a recent addition to Java. They were only added in Version 5.0. •Many programming languages have something similar. •Technically, an enum is considered to be a special kind of class. •Inthissection,wewilllookatenumsinasimplifiedform.•Inpractice,mostusesofenumswillonlyneedthesimplifiedformthatispresentedhere.•Anenumisatypethathasafixedlistofpossiblevalues,whichisspecifiedwhentheenumiscreated.•In some ways, an enum is similar to the Boolean data type, which has true and false as its only possible values. •However, Boolean is a primitive type, while an enum is not.Thedefinitionofanenumtypeshasthe(simplified)form:•

Page 46: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

34

enumenum−type−name{list−of−enum−values};

Thisdefinitioncannotbeinsideamethod.•You can place it outside the main() method of the program. •Theenum-type-namecanbeanysimpleidentifier.•Thisidentifierbecomesthenameoftheenumtype;inthesamewaythat“Boolean”isthenameoftheBoolean•type and “String” is the name of the String type. Eachvalueinthelist-of-enum-valuesmustbeasimpleidentifier,andtheidentifiersinthelistareseparatedby•commas.Forexample,hereisthedefinitionofanenumtypenamedSeasonwhosevaluesarethenamesofthefour seasons of the year:

enum Season { SPRING, SUMMER, AUTUMN, WINTER };

By convention, enum values are given names that are made up of upper case letters, but that is a style guideline •and not a syntax rule. Enum values are not variables. •Each value is a constant that always has the same value. •In fact, the possible values of an enum type are usually referred to as enum constants.•Note that the enum constants of type Season are considered to be “contained in” Season, which means-following •theconventionthatcompoundidentifiersareusedforthingsthatarecontainedinotherthings-thenamesthatyou actually use in your program to refer to them are Season.SPRING, Season.SUMMER, Season.AUTUMN, and Season.WINTER.Once an enum type has been created, it can be used to declare variables in exactly the same ways that other •types are used. For example, you can declare a variable named vacation of type Season with the statement:•

Season vacationAfter declaring the variable, you can assign a value to it using an assignment statement.•The value on the right-hand side of the assignment can be one of the enum constants of type Season. •Remember to use the full name of the constant, including “Season”! For example: vacation = Season.•SUMMER. You can print an enum value with the statement: System.out.print(vacation). The output value will be the name of the enum constant (without the “Season.”). In this case, the output would be “SUMMER”.Because an enum is technically a class, the enum values are technically objects. •As objects, they can contain methods. One of the methods in every enum value is ordinal(). •When used with an enum value it returns the ordinal number of the value in the list of values of the enum. •The ordinal number simply tells the position of the value in the list. •That is, Season.SPRING.ordinal() is the int value 0, Season.SUMMER.ordinal() is 1, while 2 is Season.•AUTUMN.ordinal(), and 3 is Season.WINTER.ordinal(). You can use the ordinal() method with a variable of type Season, such as vacation.ordinal() in our example.•Youshouldappreciateenumsasthefirstexampleofanimportantconcept:creatingnewtypes.•Here is an example that shows enums being used in a complete program:•

Page 47: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

35

public class EnumDemo {//Definetwoenumtypes−−definitionsgoOUTSIDEThemain()routine!enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SAT-URDAY }enum Month { JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC }

public static void main(String[] args) {Day tgif; / / Declar e a v a r i a b l e o f ty pe Day .Month libra; / / Declar e a v a r i a b l e o f ty pe Month .tgif = Day.FRIDAY; / / Assign a v alue o f ty pe Day to t g i f .libra = Month.OCT; / / Assign a v alue o f ty pe Month to l i b r a .System.out.print( "My s i gn i s l i br a , since I was born i n " );System.out.println(libra); / / Output v alue w i l l be : OCTSystem.out.print( " That ’ s the " );System.out.print( libra.ordinal() );System.out.println("−thmonthoftheyear.");System.out.println( " ( Counting from 0 , of course ! ) " );System.out.print( " I s n ’ t i t nice to get to " );System.out.println(tgif); / / Output v alue w i l l be : FRIDAYSystem.out.println( tgif + " i s the " + tgif.ordinal()+"−thdayoftheweek.");//CanconcatenateenumvaluesontoStrings!}

}

2.17 Enums and for-each LoopsJava 5.0 introduces a new “enhanced” form of the for loop that is designed to be convenient for processing •data structures. A data structure is a collection of data items, considered as a unit. For example, a list is a data structure that •consists simply of a sequence of items. The enhanced for loop makes it easy to apply the same processing to every element of a list or other data •structure. However,oneof theapplicationsof theenhanced for loop is toenum types,andsoweconsider itbriefly•here. The enhanced for loop can be used to perform the same processing on each of the enum constants that are the •possible values of an enumerated type. The syntax for doing this is:•

For (enum-type-name variable-name: enum-type-name. values ()) statementorfor(enum-type−namevariable−name:enum−type−name.values()){statements }

Page 48: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

36

If MyEnum is the name of any enumerated type, then MyEnum.values () is a method call that returns a list containing all of the values of the enum. (values () is a static member method in MyEnum and of any other enum.) For this enumerated type, the for loop would have the form:

for(MyEnumvariable−name:MyEnum.values()) statement

The intent of this is to execute the statement once for each of the possible values of the MyEnum type. •The variable-name is the loop control variable. •In the statement, it represents the enumerated type value that is currently being processed.•This variable should not be declared before the for loop; it is essentially being declared in the loop itself.•Togiveaconcreteexample,supposethatthefollowingenumeratedtypehasbeendefinedtorepresentthedays•of the week:

enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }

Then we could write:

for ( Day d : Day.values() ) {System.out.print( d );System.out.print( " i s day number " );System.out.println( d.ordinal() );{

Day.values() represents the list containing the seven constants that make up the enumerated type. •Thefirsttimethroughthisloop,thevalueofdwouldbethefirstenumeratedtypevalueDay.MONDAY,which•has ordinal number 0, so the output would be “MONDAY is day number0”. The second time through the loop, the value of d would be Day.TUESDAY, and so on through Day.SUNDAY. •The body of the loop is executed once for each item in the list Day.values(), with d taking on each of those •values in turn. The full output from this loop would be:•MONDAY is day number 0•TUESDAY is day number 1•WEDNESDAY is day number 2•THURSDAY is day number 3•FRIDAY is day number 4•SATURDAY is day number 5•SUNDAY is day number 6•Since the intent of the enhanced for loop is to do something “for each” item in a data structure, it is often called •a for-each loop. The syntax for this type of loop is unfortunate. •It would be better if it were written something like “foreach Day d in Day.values()”, which conveys the meaning •much better and is similar to the syntax used in other programming languages for similar types of loops. It is helpful to think of the colon (:) in the loop as meaning “in.”•

Page 49: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

37

Summary Object Oriented Programming, also known as OOP, is a computer science term which is used to describe a •computer application that is composed of multiple objects which are connected to each other. Traditionally, most computer programming languages were simply a group of functions or instructions. •With OOP, every object can handle data, get messages, and transfer messages to other objects. •Three of the most basic concepts for object oriented programmings are Classes, Objects, and Methods. However, •there are a few more concepts that you will want to become familiar with.Inheritance will allow a sub-group to make a connection with the associates of its parent class. For example, •lets say the class Cats decides to create a method called purr() and a property named Colorfur. Asthenameimplies,apropertyisaspecificattributewhichisconnectedtoanobject.•The next concept that you will want to be familiar with is called “abstraction.”•Abstractioncanbedefinedastheprocessinwhichanapplicationwillignorethecharacteristicsofasub-group•and work on a general level when it is needed. Polymorphism is an important concept of object oriented programming that you will want to become •familiar. Encapsulation will allow a class to hide information from objects that may use the code.•Aneventcansimplybedefinedasanythingthathappenstoanobject.•A multiple inheritance can create a number of perplexing situations. •Becauseofthis,thereisdebateintheprogrammingcommunityaboutwhetheritisbeneficialorrisky.•Object-orientation is a set of tools and methods that enable software engineers to build reliable, user friendly, •maintainable,welldocumented,reusablesoftwaresystemsthatfulfillstherequirementsofitsusers.It is claimed that object-orientation provides software developers with new mind tools to use in solving a wide •variety of problems. An object-oriented programming language provides support for the following object-oriented concepts:•

Objects and Classes �Inheritance �Polymorphism �Dynamic binding �

Object-oriented programming is one of several programming paradigms. •Otherprogrammingparadigmsincludetheimperativeprogrammingparadigm(asexemplifiedbylanguages•such as Pascal or C), the logic programming paradigm (Prolog), and the functional programming paradigm (exemplifiedbylanguagessuchasML,HaskellorLisp).

References C. Thomas Wu, 2009. • An Introduction to Object-Oriented Programming with Java. McGraw-Hill Higher Education. Andrew Mulholland, Glenn Murphy, 2003. • Java 1.4 Game Programming. Wordware Publishing. Wu Thomas, 2009. • An Into To Oop With Java, 4E. Tata McGraw-Hill.

Recommended Reading Cay S. Horstmann, Gary Cornell, 2001. • Core Java 2: Fundamentals. Prentice Hall PTR. Julie Anderson, Hervé Franceschi, 2008. • Java 6 illuminated: an active learning approach. Jones & Bartlett Learning. David Barnes, David J. Barnes, 2000. • Object-oriented programming with Java: an introduction. Prentice Hall.

Page 50: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

38

Self AssessmentWhat is the full form of OOP?1.

Object Organization Processa. Object Orbit Prob. Object Oriented Programmingc. Object Organic Programmed.

With OOP, every object can handle data, get messages, and transfer messages to other__________. 2. objectsa. program b. processc. subroutine d.

An_________canbedefinedasaspecificinstanceofaclass.3. objecta. program b. classc. method d.

Every object within an ___________language will share some attributes with the parent class, but it will also 4. have unique attributes as well.

C++a. OOPb. Cc. Java d.

A method may also be called a “_________”.5. Codea. memob. communicationc. messaged.

A ___________is a method that is composed of a part within an object. 6. call-backa. call-rearb. call inc. send outd.

Three of the most basic concepts for ______________are Classes, Objects, and Methods.7. coding a. programming b. object oriented programming’sc. Java d.

Page 51: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

39

One object-oriented concept that helps objects work together is_____________.8. inheritancea. heritageb. enhancementc. hashingd.

Inheritancedefinesrelationshipsamong_________inanobject-orientedlanguage.9. diagrams a. methodsb. classesc. object’sd.

____________can be defined as the process inwhich an applicationwill ignore the characteristics of a 10. sub-group and work on a general level when it is needed.

Inheritancea. Methodsb. Classesc. Abstractiond.

Page 52: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

40

Chapter III

Constants, Variables and Data Types

Aim

The aim of this chapter is to:

elucidate the concept of programming language•

explain the java’s data type integers•

evaluate ranges of different data types •

discussfloatingpointnumbers•

Objectives

The objectives of this chapter are to:

describe concept of java characters •

get an overview of Java Booleans •

evaluate primitive and non-primitive data types •

discuss various operators used in the java•

Learning outcome

At the end of this chapter, the students will be able to:

understand the arithmetic operators•

explain relational operators in while coding •

discusssignificanceofbitwiseoperators•

elaborate the logical operators•

Page 53: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

41

3.1 Introduction to Programming Language Basic A programming language is designed 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 containing a program. •These instructions are formed using certain symbols and words according to some rigid rules known as syntax •rules. Every program instruction must conform precisely to the syntax rules of the language. •Like any other language, Java has its own vocabulary and grammar. •JavaistermedasstronglytypedProgrammingwhichmeansthateveryvariablewhichisdefinedinanylinecode•ofjavaprogramminghastobeproperlywelldefinedandassignedadatatypeandthisagainmakesitpossiblefor java to maintain such complex robustness and security to the code and the data. Ifwebroadlycategorizeandclassifythesedatatypes,wecandefinethemaseightprimitivetypesofdatatypes.•Outofwhich,fourareintegertypes,twoarefloating-pointnumbertypes,oneisthecharactertypecharusedfor code units in the Unicode encoding scheme and one is a Boolean type for truth values.In most situations, the int type is the most practical. •If you want to represent the number of inhabitants of our planet, you'll need to resort to a long. •Thebyteandshorttypesaremainlyintendedforspecializedapplications,suchaslow-levelfilehandling,or•for large arrays when storage space is at a premium.Let us take these four categories in brief for our better understanding. •

3.2 Java IntegersIntegerscanbedefinedasbyte,short,int,andlong,whichareforwhole-Valuedsignednumbers.•The int type is the most practical. •If you want to represent the number of humans on earth you will need to resort to a long.•The byte and short types are mainly intended for specialized applications.•

Java Integer Types

Type Storage Requirement Range (Inclusive)

Int 4 Bytes -2,147,483,648 to 2,147,483, 647 (Just over 2 billion)

Short Bytes 2 -32,768 to 32,767

Long 8 Bytes -9,223,372,036,854, 775,808 to 9,223,372,036,854, 775,807

Byte 1 Bytes -128 to 127

Table 3.1 Integer Type

Page 54: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

42

3.3 Java Floating Point NumbersFloating-point numbers basically is used when we have the situation of getting our result or output in the form of decimalsandnotwholenumbersasmentionedincaseofIntegersDataTypes.Thisgroupthusincludesfloatanddouble.

Java Floating Types

Type Storage Requirement Range (Inclusive)

Double 64 bits 4.9e 324 to 1.8e+308

Float 32 bits 1.4e 045 to 3.4e+038

Table 3.2 Floating point

3.4 Java CharactersCharactershelpdefiningthechar,whichrepresentssymbolsinacharacterSet,likelettersandnumbers.

Character Escape SequencesEscape Sequence Description

\uXXXX Hexadecimal UNICODE Character (XXXX)\’ Single Quote \” Double Quote \\ Backslash \r Carriage Return \n Newline \f Form Feed \t Tab \b Backspace

Table 3.3 Java Character

3.5 Java BooleanBoolean data type is used to mention the variables which will only have the possibility of containing values either as True or False.

Java VariableThe variable is the basic unit of storage in a Java program. •You declare a variable by placing the type first, followed by the name of the variable.Here are some•examples:

double salary;double _salary;int holidays;int $holidays;long distanceFromMoonToEart;boolean done;

Page 55: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

43

Notice the semicolon at the end of each declaration. The semicolon is necessary because a declaration is a complete Javastatement.Inaddition,allvariableshaveascope,whichdefinestheirvisibility,andalifetime.Generalformof declaring variables:

typeidentifier[=value][,identifier[=value]...];

Wheretypeidentifiercouldbebyte,int,long,Boolean,char,short,float,doublevariablenamecannotstartwithnumeric character or special characters except “$” and “_”. For valid example please refer above variable names. Let us also see some invalid variable names:

double 1salary; // invalid variable namedouble %salary; // invalid variable nameint #holidays; // invalid variable name

After you declare a variable, you must explicitly initialize it by means of an assignment statement you can never usethevaluesofuninitializedvariables.Forexample,theJavacompilerflagsthefollowingsequenceofstatementsas an error.

byte z = 22;

Although the preceding examples have used only constants as initialisers, Java allows variables to be initialized dynamically, using any expression valid at the time the variable is declared.

floata=10.0ffloatb=3.4ffloati=a/b;

3.6 Data Types Whencomputerprogramsstoredatainvariables,eachvariablemustbeassignedaspecificdatatype.•Somecommondatatypesincludeintegers,floatingpointnumbers,characters,strings,andarrays.•Theymayalsobemorespecifictypes,suchasdates,timestamps,Booleanvalues,andvarchar(variablecharacter)•formats.Someprogramminglanguagesrequiretheprogrammertodefinethedatatypeofavariablebeforeassigningit•a value. Other languages can automatically assign a variable’s data type when the initial data is entered into the variable. •Forexample,ifthevariable“var1”iscreatedwiththevalue“1.25,”thevariablewouldbecreatedasafloatingpoint data type. If the variable is set to “Hello world!” the variable would be assigned a string data type.Most programming languages allow each variable to store a single data type.•Therefore, if the variable’s data type has already been set to an integer, assigning string data to the variable may •cause the data to be converted to an integer format.Data types are also used by database applications. •Thefieldswithinadatabaseoftenrequireaspecifictypeofdatatobeinput.Forexample,acompany’srecord•foranemployeemayuseastringdatatypefortheemployee’sfirstandlastname.The employee’s date of hire would be stored in a date format, while his or her salary may be stored as an •integer. By keeping the data type’s uniform across multiple records, database applications can easily search, sort, and •comparefieldsindifferentrecords.

Page 56: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

44

3.7 Primitive and non-primitive data typesAdatatypeisaclassificationofdata,whichcanstoreaspecifictypeofinformation.•Data types are primarily used in computer programming, in which variables are created to store data. •Each variable is assigned a data type that determines what type of data the variable may contain.•The term “data type” and “primitive data type” are often used interchangeably.•Primitivedata types arepredefined typesofdata,which are supportedby theprogramming language.For•example, integer, character, and string are all primitive data types. Programmers can use these data types when creating variables in their programs. For example, a programmer •maycreateavariablecalled“lastname”anddefineitasastringdatatype.The variable will then store data as a string of characters.•Non-primitive data types are not defined by the programming language, but are instead created by the•programmer. They are sometimes called “reference variables,” or “object references,” since they reference a memory location, •which stores the data. In the Java programming language, non-primitive data types are simply called “objects” because they are •created,ratherthanpredefined.While an object may contain any type of data, the information referenced by the object may still be stored as •a primitive data type.

3.8 Primitive Data TypeInteger

An integer is a whole number (not a fraction) that can be positive, negative, or zero. Therefore, the numbers 10, •0, -25, and 5,148 are all integers. Unlikefloatingpointnumbers,integerscannothavedecimalplaces.•Integers are a commonly used data type in computer programming. For example, whenever a number is being •incremented, such as within a “for loop” or “while loop,” an integer is used. Integers are also used to determine an item's location within an array.•When two integers are added, subtracted, or multiplied, the result is also an integer.•However, when one integer is divided into another, the result may be an integer or a fraction. For example, 6 •divided by 3 equals 2, which is an integer, but 6 divided by 4 equals 1.5, which contains a fraction. Decimal numbers may either be rounded or truncated to produce an integer result.•

Floating pointAsthenameimplies,floatingpointnumbersarenumbersthatcontainfloatingdecimalpoints.Forexample,the•numbers5.5,0.001,and-2,345.6789arefloatingpointnumbers.Numbers that do not have decimal places are called integers.•Computersrecognizerealnumbersthatcontainfractionsasfloatingpointnumbers.•Whenacalculationincludesafloatingpointnumber,itiscalleda“floatingpointcalculation.”•Oldercomputersusedtohaveaseparatefloatingpointunit(FPU)thathandledthesecalculations,butnowthe•FPU is typically built into the computer's CPU.

Page 57: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

45

TruncateTo truncate something is to shorten it or cut part of it off. •Incomputerscience,thetermisoftenusedinreferencetodatatypesorvariables,suchasfloatingpointnumbers•andstrings.Forexample,afunctionmaytruncatethedecimalportionofafloatingpointnumbertomakeitaninteger. If the number 3.875 is truncated, it becomes 3. Note that this is different than if the number had been rounded to the nearest integer, which would be 4. •Strings may also be truncated, which can be useful if a string exceeds the maximum character limit for a certain •application. Several programming languages use the function trunc() to truncate a variable. •

StringAstringisadatatypeusedinprogramming,suchasanintegerandfloatingpointunit,butisusedtorepresent•text rather than numbers. It is comprised of a set of characters that can also contain spaces and numbers. •For example, the word "hamburger" and the phrase “I ate 3 hamburgers” are both strings. Even “12345” could •beconsideredastring,ifspecifiedcorrectly.Typically,programmersmustenclosestringsinquotationmarksfor the data to recognized as a string and not a number or variable name.

For example, in the comparison:if (Option1 == Option2) then ...Option1 and Option2 may be variables containing integers, strings, or other data. •If the values are the same, the test returns a value of true, otherwise the result is false. •In the comparison: •if ("Option1" == "Option2") then ...Option1 and Option2 are being treated as strings. •Therefore, the test is comparing the words "Option1" and "Option2," which would return false. •The length of a string is often determined by using a null character.•

CharacterA character is any letter, number, space, punctuation mark or symbol that can be typed on a computer. •The word “computer,” for example, consists of eight characters. The phrase “Hi there.” takes up nine •characters. Each character requires one byte of space, so “computer” takes up 8 bytes. •ThelistofcharactersthatcanbetypedisdefinedbytheASCIIandextendedASCIIset.•Some of the symbols available are pretty strange and may even make you say, “That’s quite a character!”•

StringAstringisadatatypeusedinprogramming,suchasanintegerandfloatingpointunit,butisusedtorepresent•text rather than numbers. It is comprised of a set of characters that can also contain spaces and numbers. For example, the word "hamburger" •andthephrase"Iate3hamburgers"arebothstrings.Even"12345"couldbeconsideredastring,ifspecifiedcorrectly. Typically, programmers must enclose strings in quotation marks for the data to recognized as a string and not •a number or variable name. For example, in the comparison:if (Option1 == Option2) then ...Option1 and Option2 may be variables containing integers, strings, or other data.

Page 58: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

46

If the values are the same, the test returns a value of true, otherwise the result is false. In the comparison: if ("Option1" == "Option2") then ...Option1 and Option2 are being treated as strings. •Therefore the test is comparing the words "Option1" and "Option2," which would return false. •The length of a string is often determined by using a null character.•

3.9 Operators Used in JavaJava provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Arithmetic Operators•Relational Operators•Bitwise Operators•Logical Operators•Assignment Operators•Misc Operators•

3.9.1 Arithmetic Operators

Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. •The following table lists the arithmetic operators. •Assume integer variable A holds 10 and variable B holds 20 then•

Operator Description Example

+ Addition - Adds values on either side of the opera-tor A + B will give 30

- Subtraction - Subtracts right hand operand from left hand operand A - B will give -10

* Multiplication - Multiplies values on either side of the operator A * B will give 200

/ Division - Divides left hand operand by right hand operand B / A will give 2

% Modulus - Divides left hand operand by right hand operand and returns remainder B % A will give 0

++ Increment - Increase the value of operand by 1 B++ gives 21

-- Decrement - Decrease the value of operand by 1 B-- gives 19

Table 3.4 Arithmetic operators

The following simple example program demonstrates the arithmetic operators. Copy and paste following Java programinTest.javafileandcompileandrunthisprogram:

Page 59: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

47

class Test {public static void main(String args[]) { int a = 10; int b = 20; int c = 25; int d = 25; System.out.println("a + b = " + (a + b) ); System.out.println("a - b = " + (a - b) ); System.out.println("a * b = " + (a * b) ); System.out.println("b / a = " + (b / a) ); System.out.println("b % a = " + (b % a) ); System.out.println("c % a = " + (c % a) ); System.out.println("a++ = " + (a++) ); System.out.println("b-- = " + (a--) ); // Check the difference in d++ and ++d System.out.println("d++ = " + (d++) ); System.out.println("++d = " + (++d) );}}

Resulta + b = 30a - b = -10a * b = 200b / a = 2b % a = 0c % a = 5a++ = 10b-- = 11d++ = 25 ++d = 27

Page 60: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

48

3.9.2 Relational OperatorsThere are following relational operators supported by Java language. Assume variable A holds 10 and variable B holds 20 then:

Operator Description Example

== Checks if the values of two operands are equal or not, if yes then condition becomes true. (A == B) is not true.

!=Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.

(A != B) is true.

>Checks if the value of left operand is greater than the value of right operand, if yes then con-dition becomes true.

(A>B)isnottrue.

<Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.

(A < B) is true.

>=Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.

(A>=B)isnottrue.

<=Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.

(A <= B) is true.

Table 3.5 Relational operators

The following simple example program demonstrates the relational operators. Copy and paste following Java programinTest.javafileandcompileandrunthisprogram.:

Page 61: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

49

class Test {public static void main(String args[]) { int a = 10; int b = 20; System.out.println("a == b = " + (a == b) ); System.out.println("a != b = " + (a != b) );System.out.println("a>b="+(a>b)); System.out.println("a < b = " + (a < b) );System.out.println("b>=a="+(b>=a)); System.out.println("b <= a = " + (b <= a) );}}

Result:a == b = falsea != b = truea>b=falsea < b = trueb>=a=true b <= a = false

Bitwise operatorsJavadefinesseveralbitwiseoperatorswhichcanbeapplied to the integer types, long, int, short,char,and•byte.Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b= 13; Now in binary •format they will be as follows:a = 0011 1100b = 0000 1101------------------a&b = 0000 1100a|b = 0011 1101a^b = 0011 0001~a = 1100 0011

The following table lists the bitwise operators. Assume integer variable A holds 60 and variable B holds 13 then:

Operator Description Example

& Binary AND Operator copies a bit to the result if it exists in both operands.

(A & B) will give 12 which is 0000 1100

| Binary OR Operator copies a bit if it exists in eat-her operand.

(A | B) will give 61 which is 0011 1101

^ Binary XOR Operator copies the bit if it is set in one operand but not both.

(A ^ B) will give 49 which is 0011 0001

Page 62: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

50

~ Binary Ones Complement Operator is unary and hastheeffectof'flipping'bits.

(~A ) will give -60 which is 1100 0011

<<Binary Left Shift Operator. The left operands value ismovedleftbythenumberofbitsspecifiedbytheright operand.

A << 2 will give 240 which is 1111 0000

>>Binary Right Shift Operator. The left operands value is moved right by the number of bits speci-fiedbytherightoperand.

A>>2willgive15whichis1111

>>>

Shiftrightzerofilloperator.Theleftoperandsvalue is moved right by the number of bits speci-fiedbytherightoperandandshiftedvaluesarefilledupwithzeros.

A>>>2willgive15whichis0000 1111

Table 3.6 Bitwise operators

The following simple example program demonstrates the bitwise operators. Copy and paste following Java program inTest.javafileandcompileandrunthisprogram:

Page 63: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

51

class Test {public static void main(String args[]) { int a = 60; /* 60 = 0011 1100 */ int b = 13; /* 13 = 0000 1101 */ int c = 0;

c = a & b; /* 12 = 0000 1100 */ System.out.println("a & b = " + c );

c = a | b; /* 61 = 0011 1101 */ System.out.println("a | b = " + c );

c = a ^ b; /* 49 = 0011 0001 */ System.out.println("a ^ b = " + c );

c = ~a; /*-61 = 1100 0011 */ System.out.println("~a = " + c );

c = a << 2; /* 240 = 1111 0000 */ System.out.println("a << 2 = " + c );

c=a>>2;/*215=1111*/System.out.println("a>>2="+c);

c=a>>>2;/*215=00001111*/System.out.println("a>>>2="+c);}}

Result a & b = 12a | b = 61a ^ b = 49~a = -61a << 2 = 240a>>15a>>>15

Page 64: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

52

3.9.3 Logical OperatorsThe following table lists the logical operators. Assume boolean variables A holds true and variable B holds false then:

Operator Description Example

&& Called Logical AND operator. If both the oper-ands are non zero then condition becomes true. (A && B) is false.

||Called Logical OR Operator. If any of the two operands are non zero then condition becomes true.

(A || B) is true.

!

Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.

!(A && B) is true

Table 3.7 Logical operators

The following simple example program demonstrates the logical operators. Copy and paste following Java program inTest.javafileandcompileandrunthisprogram:

class Test {

public static void main(String args[])

{ int a = true;

int b = false;

System.out.println("a && b = " + (a&&b) ); System.out.println("a || b = " + (a||b) ); System.out.println("!(a && b) = " + !(a && b) );}}

Resulta && b = falsea || b = true!(a && b) = true

Page 65: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

53

3.9.4 Assignment OperatorsThere are following assignment operators supported by Java language:

Operator Description Example

= Simple assignment operator, Assigns values from right side operands to left side operand

C = A + B will assignee value of A + B into C

+= Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand

C += A is equivalent to C = C + A

-= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand

C -= A is equivalent to C = C - A

*= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand

C *= A is equivalent to C = C * A

/= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand

C /= A is equivalent to C = C / A

%= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand

C %= A is equivalent to C = C % A

<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2

>>= Right shift AND assignment operator C>>=2issameasC=C>>2

&= Bitwise AND assignment operator C &= 2 is same as C = C & 2

^= bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^ 2

|= bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 2

Table 3.8 Assignment Operators

3.9.5 Misc OperatorsThere are few other operators supported by Java Language.

3.9.5.1 Conditional Operator (? : )

Conditional operator is also known as the ternary operator. •This operator consists of three operands and is used to evaluate Boolean expressions. •The goal of the operator is to decide which value should be assigned to the variable. •The operator is written as•

variable x = (expression) ? value if true : value if false

Page 66: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

54

Following is the example:

public class Test { public static void main(String args[]){ int a , b; a = 10; b = (a == 1) ? 20: 30; System.out.println( "Value of b is : " + b );

b = (a == 10) ? 20: 30; System.out.println( "Value of b is : " + b ); }}

This would produce following result:Value of b is : 30Value of b is : 20

3.9.5.2 instanceOf OperatorThis operator is used only for object reference variables. The operator checks whether the object is of a particular type (class type or interface type). instanceOf operator is written as

( Object reference variable ) instanceOf (class/interface type)

If the object referred by the variable on the left side of the operator passes the IS-A check for the class/interface type on the right side then the result will be true. Following is the example:

String name = = 'James';boolean result = s instanceOf String; // This will return true since name is type of String

This operator will still return true if the object being compared is the assignment compatible with the type on the right. Following is one more example:

class Vehicle {}

public class Car extends Vehicle { public static void main(String args[]){ Vehicle a = new Car(); boolean result = a instanceof Car; System.out.println( result); }}

This would produce following result:

true

Page 67: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

55

3.10 Precedence of Java OperatorsOperator precedence determines the grouping of terms in an expression. This affects how an expression is •evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator:For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher precedence than + so it •firstgetmultipliedwith3*2andthenaddsinto7.Here operators with the highest precedence appear at the top of the table; those with the lowest appear at the •bottom.Withinanexpression,higherprecedenceoperatorswillbeevaluatedfirst.

Category Operator Associativity

Postfix () [] . (dot operator) Left to Right

Unary ++ - - ! ~ Right to Left

Multiplicative * / % Left to Right

Additive + - Left to Right

Shift >>>>><< Left to Right

Relational >>=<<= Left to Right

Equality == != Left to Right

Bitwise AND & Left to Right

Bitwise XOR ^ Left to Right

Bitwise OR | Left to Right

Logical AND && Left to Right

Logical OR || Left to Right

Conditional ?: Right to Left

Assignment =+=-=*=/=%=>>=<<=&=^=|= Right to left

Comma , Left to Right

Table 3.9 Precedence of Java operators

Page 68: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

56

Summary A programming language is designed 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 containing a program. •These instructions are formed using certain symbols and words according to some rigid rules known as syntax •rules.Ifwebroadlycategorizeandclassifythesedatatypes,wecandefinethemaseightprimitivetypesofdatatypes•available;fourofthembeingintegertypes,twobeingfloating-pointnumbertypes,onebeingthecharactertypechar used for code units in the Unicode encoding scheme and one being a Boolean type for truth values.Integerscanbedefinedasbyte,short,int,andlong,whichareforwhole-Valuedsignednumbers.•Floating-point numbers basically is used when we have the situation of getting our result or output in the form •of decimals and not whole numbers as mentioned in case of Integers Data Types.Boolean data type is used to mention the variables which will only have the possibility of containing values •either as True or False.The variable is the basic unit of storage in a Java program. •Whencomputerprogramsstoredatainvariables,eachvariablemustbeassignedaspecificdatatype.•Somecommondatatypesincludeintegers,floatingpointnumbers,characters,strings,andarrays.•Most programming languages allow each variable to store a single data type.•Therefore, if the variable’s data type has already been set to an integer, assigning string data to the variable may •cause the data to be converted to an integer format.Adatatypeisaclassificationofdata,whichcanstoreaspecifictypeofinformation.•Data types are primarily used in computer programming, in which variables are created to store data. •Non-primitive data types are not defined by the programming language, but are instead created by the•programmer. They are sometimes called “reference variables,” or “object references,” since they reference a memory location, •which stores the data. An integer is a whole number (not a fraction) that can be positive, negative, or zero. Therefore, the numbers 10, •0,-25,and5,148areallintegers.Unlikefloatingpointnumbers,integerscannothavedecimalplaces.Numbers that do not have decimal places are called integers.•Computersrecognizerealnumbersthatcontainfractionsasfloatingpointnumbers.•

References Balagurusamy, 2009. • Programming With Java 4E. Tata McGraw-Hill. Balagurusamy, 2006.• Programming With Java:A Primer 3E. Tata McGraw-HillDoug Lowe, Barry Burd, 2007. • Java all-in-one desk reference for dummies. Dummies.

Recommended Reading Julie Anderson, Hervé Franceschi, 2008. • Java 6 illuminated: an active learning approach. Jones & Bartlett Learning. E. Reed Doke, Bill C. Hardgrave, 1999. • Java for the COBOL programmer. Cambridge University Press. R. Nageswara Rao/kogent Solutions,2008. • Core Java: An Integrated Approach. Dreamtech Press.

Page 69: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

57

Self AssessmentA programming language is designed to process certain kinds of data consisting of numbers, characters and 1. strings and to provide useful output known as_______.

data a. informationb. program c. code d.

Instructions are formed using certain symbols and words according to some rigid rules known as_________.2. coding rule a. syntax rulesb. semi-code rule c. symbol rule d.

Ifwebroadlycategorizeandclassifythesedatatypeswecandefinethemas________primitivetypesofdata3. types available to us in Java.

eighta. nine b. seven c. ten d.

___________canbedefinedasbyte,short,int,andlong,whichareforwhole-Valuedsignednumbers.4. floatingpointa. character b. Integersc. double d.

The variable is the basic unit of ___________in a Java program. 5. carrier a. empty space b. storagec. room d.

Whencomputerprogramsstoredatainvariables,eachvariablemustbeassignedaspecific___________.6. value a. space b. name c. data typed.

Which of the following sentences are true?7. Primitivedatatypesarepredefinedtypesofdataa. Primitive data types are unchangeable types of datab. Primitive data types are external types of datac. Primitive data types are ineffective types of datad.

Page 70: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

58

Which of the following sentences are true?8. Non-primitive data types are not separate by the programming language.a. Non-primitive data types are not clear by the programming language.b. Non-primitive data types are not amorphous by the programming language.c. Non-primitivedatatypesarenotdefinedbytheprogramminglanguage.d.

__________are a commonly used data type in computer programming. 9. charactera. string b. Integersc. floatingd.

______________numbersarenumbersthatcontainfloatingdecimalpoints.10. Floating pointa. Integer b. Characterc. String d.

Page 71: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

59

Chapter IV

Basic Syntax, Loop Control and Decision Making

Aim

The aim of this chapter is to:

enlighten the concept of the object and classes in detail •

discussfirstjavaprogram•

enrich the basic syntax of java •

getanoverviewofjavaidentifiers•

Objectives

The objectives of this chapter are to:

elucidatetheconceptofJavaModifiers•

explain java’s keywords•

explain the comments in java •

evaluate features of Java Objectives of this chapter are: •

Learning outcome

At the end of this chapter, the students will be able to:

draw various program with results for different classes •

evaluate different variable types•

understand different constructors used in Java Program •

Page 72: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

60

4.1 Object and Classes WhenweconsideraJavaprogramitcanbedefinedasacollectionofobjectsthatcommunicateviainvokingeachothersmethods.Letusnowbrieflylookintowhatdoclass,object,methodsandinstantvariablesmean.

ObjectObjects have states and behaviours. Example: A dog has states-colour, name, breed as well as behaviours -wagging, barking, and eating. An object is an instance of a class.

Class Aclasscanbedefinedasatemplate/blueprintthatdescribethebehaviors/statesthatobjectofitstypesupport.

MethodsA method is basically behaviour. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.

Instant VariablesEach object has its unique set of instant variables. An object.s state is created by the values assigned to these instant variables.

4.2 First Java ProgramLet us look at a simple code that would print the words Hello World.

public class MyFirstJavaProgram{

/*Thisismyfirstjavaprogram. * This will print 'Hello World' as the output */

public static void main(String []args){ System.out.println("Hello World"); // prints Hello World }}

ResultC:>javacMyFirstJavaProgram.javaC:>javaMyFirstJavaProgram Hello World

Let’slookathowtosavethefile,compileandruntheprogram.Pleasefollowthestepsgivenbelow:•Open notepad and add the code as above.•Savethefileas:MyFirstJavaProgram.java.•Open a command prompt window and go o the directory where you saved the class. Assume its C:\.•Type ’javac MyFirstJavaProgram.java’ and press enter to compile your code. If there are no errors in your code •the command prompt will take you to the next line.( Assumption : The path variable is set).Now type ' java MyFirstJavaProgram ' to run your program.•You will be able to see ' Hello World ' printed on the window.•

Page 73: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

61

4.3 Basic SyntaxAbout Java programs, it is very important to keep in mind the following points.

Case sensitivity JavaiscasesensitivewhichmeansidentifierHelloandhellowouldhavedifferentmeaninginJava.

Class namesForallclassnamesthefirstlettershouldbeinUpperCase.

IfseveralwordsareusedtoformanameoftheclasseachinnerwordsfirstlettershouldbeinUpperCase.Exampleclass MyFirstJavaClass

Method namesAll method names should start with a Lower Case letter. If several words are used to form the name ofthemethod,theneachinnerword'sfirstlettershouldbeinUpperCase.ExamplepublicvoidmyMethodName ()

Program file nameNameoftheprogramfileshouldexactlymatchtheclassname.Whensavingthefileyoushouldsaveitusingtheclassname(Rememberjavaiscasesensitive)andappend'.java'totheendofthename.(ifthefilenameandtheclass name do not match your program will not compile). Example: Assume “MyFirstJavaProgram” is the class name.Thenthefileshouldbesavedas“MyFirstJavaProgram.java”

public static void main(String args[])Java program processing starts from the main() method which is a mandatory part of every java program..

4.4 Java IdentifiersAlljavacomponentsrequirenames.Namesusedforclasses,variablesandmethodsarecalledidentifiers.•Injavathereareseveralpointstorememberaboutidentifiers.Theyareasfollows:•

Allidentifiersshouldbeginwithaletter(AtoZoratoz),currencycharacter($)oranunderscore(-). �Afterthefirstcharacteridentifierscanhaveanycombinationofcharacters. �Akeywordcannotbeusedasanidentifier. �Mostimportantlyidentifiersarecasesensitive. �Examplesoflegalidentifiers:age,$salary,_value,__1_value. �Examplesofillegalidentifiers:123abc,-salary. �

4.5 Java ModifiersLikeotherlanguagesitispossibletomodifyclasses,methodsetcbyusingmodifiers.Therearetwocategoriesofmodifiers.

Access modifiers• : default, public , protected, privateNon-access modifiers• :final,abstract,strictfp

Wewillbelookingintomoredetailsaboutmodifiersinthenextsection.

4.6 Java VariablesWe would see following type of variables in Java:

Local Variables•Class Variables (Static Variables)•Instance Variables (Non static variables)•

Page 74: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

62

4.7 Java KeywordsThe following list shows the reserved words in Java. These reserved words may not be used as constant or variable oranyotheridentifiernames.

abstract assert boolean break

byte case catch char

class const continue default

do double else enum

extends final finally float

for goto if implements

import instanceof int interface

long native new package

private protected public return

short static strictfp super

switch synchronised this throw

throws transient try void

volatile while

Table 4.1 Java keyword 4.8 Comments in Java

Java supports single line and multi-line comments very similar to c and c++.•All characters available inside any comment are ignored by Java compiler.•

public class MyFirstJavaProgram{

/*Thisismyfirstjavaprogram. * This will print 'Hello World' as the output * This is an example of multi-line comments. public static void main(String []args){ // This is an example of single line comment /* This is also an example of single line comment. */ System.out.println("Hello World"); }}

Page 75: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

63

Using Blank LinesA line containing only whitespace, possibly with a comment, is known as a blank line, and Java totally ignores it.

InheritanceIn java classes can be derived from classes. •Basically if you need to create a new class and here is already a class that has some of the code you require, •then it is possible to derive your new class from the already existing code.Thisconceptallowsyoutoreusethefieldsandmethodsoftheexistingclasswithouthavingtorewritethe•code in a new class. In this scenario the existing class is called the super class and the derived class is called the subclass.•

InterfacesInJavalanguageaninterfacecanbedefinedasacontractbetweenobjectsonhowtocommunicatewitheach•other. Interfaces play a vital role when it comes to the concept of inheritance. •Aninterfacedefinesthemethods,aderivingclass(subclass)shoulduse.Buttheimplementationofthemethods•is totally up to the subclass.Java is an Object Oriented Language. As a language that has the Object Oriented feature Java supports the •following fundamental concepts:

Polymorphism �Inheritance �Encapsulation �Abstraction �Classes �Objects �Instance �Method �Message Parsing �

Object Objects have states and behaviours. Example: A dog has states-colour, name, breed as well as behaviours -wagging, barking, and eating. An object is an instance of a class.

ClassAclasscanbedefinedasatemplate/blueprintthatdescribethebehaviours/statesthatobjectofitstypesupport.

Objects in JavaLetusnowlookdeepintowhatareobjects.Ifweconsiderthereal-worldwecanfindmanyobjectsaroundus,•Cars, Dogs, Humans etc. All these objects have a state and behaviour.If we consider a dog then its state is name, breed, colour, and the behaviour is barking, wagging, running.•If you compare the software object with a real world object, they have very similar characteristics.•Softwareobjectsalsohaveastateandbehaviour.Asoftwareobject'sstateisstoredinfieldsandbehaviouris•shown via methods.So in software development methods operate on the internal state of an object and the object-to-object •communication is done via methods.

Page 76: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

64

4.9 Classes in JavaA class is a blue print from which individual objects are created. A sample of a class is given below

public class Dog{ String breed; int age; String colour;

void barking(){ } void hungry(){

} void sleeping(){

}

}

A class can contain any of the following variable types.

Local variables Variablesdefinedinsidemethods,constructorsorblocksarecalledlocalvariables.•The variable will be declared and initialised within the method and the variable will be destroyed when the •method has completed.

Instance variables Instance variables are variables within a class but outside any method. •These variables are instantiated when the class is loaded. •Instance variables can be accessed from inside any method, constructor or blocks of that particular class.•

Class variablesClass variables are variables declared with in a class, outside any method, with the static keyword.

A class can have any number of methods to access the value of various kinds of methods. In the above example, barking (), hungry () and sleeping () are variables. Below mentioned are some of the important topics that need to be discussed when looking into classes of the Java Language.

Page 77: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

65

4.10 ConstructorsWhen discussing about classes one of the most important sub topic would be constructors. •Every class has a constructor. •If we do not explicitly write a constructor for a class the java compiler builds a default constructor for that •class.Each time a new object is created at least one constructor will be invoked. •The main rule of constructors is that they should have the same name as the class. •A class can have more than one constructor.•Example of a constructor is given below:•

class Puppy

{

public puppy(){

}

public puppy(String name){ // This constructor has one parameter, name. }}

4.11 Creating an ObjectAs mentioned previously a class provides the blueprints for objects. So basically an object is created from a •class. In java the new key word is used to create new objects.There are three steps when creating an object from a class:•

Declaration A variable declaration with a variable name with an object type.

Instantiation The 'new' key word is used to create the object.

Initialization The “new” keyword is followed by a call o a constructor. This call initialises the new object. Example of creating an object is given below:

Page 78: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

66

class Puppy

{

public Puppy(String name)

{ // This constructor has one parameter, name. System.out.println("Passed Name is :" + name ); } public static void main(String []args){

// Following statement would create an object myPuppy Puppy myPuppy = new Puppy( "tommy" );

} }

Result

Passed Name is :tommy

4.12 Accessing Instance Variables and MethodsInstancevariablesandmethodsareaccessedviacreatedobjects.Toaccessaninstancevariablethefullyqualifiedpath should be as follows:

/* First create an object */

ObjectReference = new Constructor();

/* Now call a variable as follows */ObjectReference.variableName;

/* Now you can call a class method as follows */ObjectReference.MethodName();

ExampleThis example explains how to access instance variables and methods of a class

Page 79: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

67

class Puppy{ int puppyAge;

public Puppy(String name){ // This constructor has one parameter, name. System.out.println("Passed Name is :" + name ); } public setAge( int age ){ puppyAge = age; }

public getAge( ){ System.out.println("Puppy's age is :" + puppyAge ); return puppyAge; } public static void main(String []args){ /* Object creation */ Puppy myPuppy = new Puppy( "tommy" );

/* Call class method to set puppy's age */ myPuppy.setAge( 2 );

/* Call another class method to get puppy's age */ myPuppy.getAge( );

/* You can access instance variable as follows as well */ System.out.println("Variable Value :" + myPuppy.puppyAge ); }}

If we compile and run the above program then it would produce following result:

Passed Name is :tommyPuppy's age is :2Variable Value :2

4.13 Source file declaration rulesAsthelastpartofthissectionletsusnowlookintothesourcefiledeclarationrules.Theserulesareessentialwhendeclaringclasses,importstatementsandpackagestatementsinasourcefile.

Therecanbeonlyonepublicclasspersourcefile.•Asourcefilecanhavemultiplenonpublicclasses.•Thepublicclassnameshouldbethenameofthesourcefileaswellwhichshouldbeappendedby.javaattheend.•Forexample:Theclassnameis.publicclassEmployee{}ThenthesourcefileshouldbeasEmployee.java.Iftheclassisdefinedinsideapackage,thenthepackagestatementshouldbethefirststatementinthesource•file.If import statements are present then they must be written between the package statement and the class declaration. •Iftherearenopackagestatementsthentheimportstatementshouldbethefirstlineinthesourcefile.Importandpackagestatementswillimplytoalltheclassespresentinthesourcefile.Itisnotpossibletodeclare•differentimportand/orpackagestatementstodifferentclassesinthesourcefile.

Page 80: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

68

Classeshaveseveralaccesslevelsandtherearedifferenttypesofclasses;abstractclasses,finalclassesetc.•Apart from the above mentioned types of classes, Java also has some special classes called Inner classes and •Anonymous classes.

4.14 Java PackageIn simple it is a way of categorizing the classes and interfaces. When developing applications in Java, hundreds of classes and interfaces will be written, therefore categorizing these classes is a must as well as makes life much easier.

Import statementsInjavaifafullyqualifiedname,whichincludesthepackageandtheclassname,isgiventhenthecompilercan•easily locate the source code or classes. Importstatementisawayofgivingtheproperlocationforthecompilertofindthatparticularclass.•For example following line would ask compiler to load all the classes available in directory java_installation/•java/io

import java.io.*;

4.15 Basic Data TypesVariables are nothing but reserved memory locations to store values. This means that when you create a variable •you reserve some space in memory.Based on the data type of a variable, the operating system allocates memory and decides what can be stored in •the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or characters in these variables.There are two data types available in Java•

Primitive data types �Reference/object data types �

4.16 Primitive Data TypesThere are eight primitive data types supported by Java. •Primitivedatatypesarepredefinedbythelanguageandnamedbyakeyword.•Let us now look into detail about the eight primitive data types.•

ByteByte data type is a 8-bit signed two.s complement integer.•Minimum value is -128 (-2^7). Maximum value is 127 (inclusive)(2^7 -1) and default value is 0•Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is four times smaller •than an int. Example : byte a = 100 , byte b = -50

ShortShort data type is a 16-bit signed two's complement integer.•Minimum value is -32,768 (-2^15). Maximum value is 32,767(inclusive) (2^15 -1). Short data type can also be •used to save memory as byte data type. A short is 2 times smaller than an intDefault value is 0. Example : short s= 10000 , short r = -20000•

Page 81: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

69

LongLong data type is a 64-bit signed two’s complement integer.•Minimum value is -9,223,372,036,854,775,808.(-2^63). Maximum value is 9,223,372,036,854,775,807 •(inclusive). (2^63 -1). This type is used when a wider range than int is needed.Default value is 0L. Example : int a = 100000L, int b = -200000L•

FloatFloatdatatypeisasingle-precision32-bitIEEE754floatingpoint.•Floatismainlyusedtosavememoryinlargearraysoffloatingpointnumbers.•Default value is 0.0f.•Floatdatatypeisneverusedforprecisevaluessuchascurrency.Example:floatf1=234.5f•

DoubleDoubledatatypeisadouble-precision64-bitIEEE754floatingpoint.•This data type is generally used as the default data type for decimal values. Generally the default choice.•Double data type should never be used for precise values such as currency.•Default value is 0.0d. Example : double d1 = 123.4•

BooleanBoolean data type represents one bit of information.•There are only two possible values: true and false.•Thisdatatypeisusedforsimpleflagsthattracktrue/falseconditions.•Default value is false. Example : boolean one = true•

CharChar data type is a single 16-bit Unicode character.•Minimum value is '\u0000' (or 0).•Maximum value is '\uffff' (or 65,535 inclusive).•Char data type is used to store any character. Example . char letterA ='A'•

Reference data typesReferencevariablesarecreatedusingdefinedconstructorsoftheclasses.Theyareusedtoaccessobjects.These•variablesaredeclaredtobeofaspecifictypethatcannotbechanged.Forexample,Employee,Puppyetc.Class objects and various types of array variables come under reference data type.•Default value of any reference variable is null.•A reference variable can be used to refer to any object of the declared type or any compatible type. Example : •Animal animal = new Animal(“giraffe”);

Java literalsAliteralisasourcecoderepresentationofafixedvalue.Theyarerepresenteddirectlyinthecodewithoutany•computation.Literals can be assigned to any primitive type variable. For example:•

byte a = 68;char a = 'A'

Page 82: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

70

Byte, int, long, and short can be expressed in decimal (base 10),hexadecimal(base 16) or octal(base 8) number •systems as well.Prefix0isusedtoindicateoctalandprefix0xindicateshexadecimalwhenusingthesenumbersystemsfor•literals. For example:

int decimal = 100;int octal = 0144;int hexa = 0x64;

StringliteralsinJavaarespecifiedliketheyareinmostotherlanguagesbyenclosingasequenceofcharacters•between a pair of double quotes. Examples of string literals are:

"Hello World""two\nlines""\"This is in quotes\""

String and char types of literals can contain any Unicode characters. For example:

char a = '\u0001';String a = "\u0001";

Java language supports few special escape sequences for String and char literals as well. They are:

Notation Character Represented \n Newline (0x0a)\r Carriage return (0x0c) \f Backspace (0x08)\b Space (0x20)\s Tab\t Double Quote \” Single Quote \\ Backslash \ddd Octal Character (ddd)\uxxx Hexadecimal UNICODE character(XXXX)

Table 4.2 Character representation

4.17 Java Variable TypesIn Java, all variables must be declared before they can be used. The basic form of a variable declaration is shown here:

typeidentifier[=value][,identifier[=value]...];

The type is one of Java’s data types. •Theidentifieristhenameofthevariable.•Todeclaremorethanonevariableofthespecifiedtype,useacomma-separatedlist.•Here are several examples of variable declarations of various types.•Note that some include an initialization.•

Page 83: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

71

int a, b, c; // declares three ints, a, b, and c.int d = 3, e, f = 5; // declares three more ints, initializing // d and f.byte z = 22; // initializes z.double pi = 3.14159; // declares an approximation of pi.char x = 'x'; // the variable x has the value ‘x’.

There are three kinds of variables in Java:•Local variables �Instance variables �Class/static variables �

Local variablesLocal variables are declared in methods, constructors, or blocks.•Local variables are created when the method, constructor or block is entered and the variable will be destroyed •once it exits the method, constructor or block.Accessmodifierscannotbeusedforlocalvariables.•Local variables are visible only within the declared method, constructor or block.•Local variables are implemented at stack level internally.•There is no default value for local variables so local variables should be declared and an initial value should •beassignedbeforethefirstuse.Example:Hereageisalocalvariable.ThisisdefinedinsidepupAge()methodand its scope is limited to this method only.

public class Test{ public void pupAge(){ int age = 0; age = age + 7; System.out.println("Puppy age is : " + age) } public static void main(String args[]){ Test test = new Test(); Test.pupAge(); }}

Result:

Puppy age is: 7

Page 84: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

72

Example: Following example uses age without initializing it, so it would give an error at the time of compilation.

public class Test{ public void pupAge(){ int age; age = age + 7; System.out.println("Puppy age is : " + age) } public static void main(String args[]){ Test test = new Test(); Test.pupAge(); }}

Result

This would produce following error while compiling it:

Test.java:4:variable number might not have been initializedage = age + 7; ^1 error

Instance variablesInstance variables are declared in a class, but outside a method, constructor or any block.•When a space is allocated for an object in the heap a slot for each instance variable value is created.•Instance variables are created when an object is created with the use of the key word 'new' and destroyed when •the object is destroyed.Instance variables hold values that must be referenced by more than one method, constructor or block, or essential •parts of an object.s state that must be present through out the class.Instance variables can be declared in class level before or after use.•Accessmodifierscanbegivenforinstancevariables.•The instance variables are visible for all methods, constructors and block in the class. Normally it is recommended •to make these variables private (access level).However visibility for subclasses can be given for these variables withtheuseofaccessmodifiers.Instance variables have default values. For numbers the default value is 0, for Booleans it is false and for object •references it is null. Values can be assigned during the declaration or within the constructor.Instance variables can be accessed directly by calling the variable name inside the class. However within static •methods and different class (when instance variables are given accessibility) the should be called using the fully qualifiedname.ObjectReference.VariableName.

Page 85: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

73

Example

import java.io.*;

class Employee{ // this instance variable is visible for any child class. public String name; // salary variable is visible in Employee class only. private double salary; // The name variable is assigned in the constructor. public Employee (String empName){ name = empName; }

// The salary variable is assigned a value. public void setSalary(double empSal){ salary = empSal; } // This method prints the employee details. public void printEmp(){ System.out.println("name : " + name ); System.out.println("salary :" + salary); }

public static void main(String args[]){ Employee empOne = new Employee("Ransika"); empOne.setSalary(1000); empOne.printEmp(); }}This would produce following result:

name : Ransikasalary :1000.0

Class/static variablesClass variables also known as static variables are declared with the static keyword in a class, but outside a •method, constructor or a block.There would only be one copy of each class variable per class, regardless of how many objects are created •from it.Static variables are rarely used other than being declared as constants. •Constantsarevariablesthataredeclaredaspublic/private,finalandstatic.•Constant variables never change from their initial value.•Static variables are stored in static memory. •Itisraretousestaticvariablesotherthandeclaredfinalandusedaseitherpublicorprivateconstants.•Static variables are created when the program starts and destroyed when the program stops.•Visibility is similar to instance variables. However, most static variables are declared public since they must •be available for users of the class.

Page 86: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

74

Default values are same as instance variables. •For numbers the default value is 0, for Booleans it is false and for object references it is null.•Values can be assigned during the declaration or within the constructor. •Additionally values can be assigned in special static initialiser’s blocks.•Static variables can be accessed by calling with the class name. ClassName.VariableName.•Whendeclaringclassvariablesaspublicstaticfinal,thenvariablesnames(constants)areallinuppercase.•Ifthestaticvariablesarenotpublicandfinalthenamingsyntaxisthesameasinstanceandlocalvariables.•

import java.io.*;

class Employee{ // salary variable is a private static variable private static double salary;

// DEPARTMENT is a constantpublicstaticfinalStringDEPARTMENT="Development";

public static void main(String args[]){ salary = 1000; System.out.println(DEPARTMENT+"average salary:"+salary); }}

This would produce following result:

Development average salary:1000

4.18 Java Access ModifiersJavaprovidesanumberofaccessmodifierstosetaccesslevelsforclasses,variables,methodsandconstructors.The four access levels are:

Visibletothepackage.thedefault.Nomodifiersareneeded.•Visible to the class only (private).•Visible to the world (public).•Visible to the package and all subclasses (protected).•

Default Access Modifier - No keywordDefaultaccessmodifiermeanswedonotexplicitlydeclareanaccessmodifierforaclass,field,methodetc.•Avariableormethoddeclaredwithoutanyaccesscontrolmodifierisavailabletoanyotherclassinthesame•package.Thedefaultmodifiercannotbeusedformethods,fieldsinaninterface.Example:Variablesandmethodscanbedeclaredwithoutanymodifiers,asinthefollowingexamples:•

String version = "1.5.1";

boolean processOrder() { return true;}

Page 87: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

75

4.19 Private Access Modifier – privateMethods, Variables and Constructors that are declared private can only be accessed within the declared class •itself.Privateaccessmodifieristhemostrestrictiveaccesslevel.Classandinterfacescannotbeprivate.•Variables that are declared private can be accessed outside the class if public getter methods are present in the •class.Usingtheprivatemodifieristhemainwaythatanobjectencapsulatesitselfandhidesdatafromtheoutside•world.Example: The following class uses private access control:•

class Logger { private String format; public String getFormat() { return this.format; } public void setFormat(String format) { this.format = format; }}

Here, the format variable of the Logger class is private, so there's no way for other classes to retrieve or set its •value directly.Sotomakethisvariableavailabletotheoutsideworld,wedefinedtwopublicmethods:getFormat(),which•returns the value of format, and setFormat(String), which sets its value.

4.20 Public Access Modifier - PublicA class, method, constructor, interface etc declared public can be accessed from any other class. Therefore •fields,methods,blocksdeclaredinsideapublicclasscanbeaccessedfromanyclassbelongingtotheJavaUniverse.However if the public class we are trying to access is in a different package, then the public class still need to •be imported.Because of class inheritance, all public methods and variables of a class are inherited by its subclasses.•Example: The following function uses public access control:•

public static void main(String[] arguments) { // ...}

The main() method of an application has to be public. Otherwise, it could not be called by a Java interpreter •(such as java) to run the class.

4.21 Protected Access Modifier - ProtectedVariables, methods and constructors which are declared protected in a superclass can be accessed only by the •subclasses in other package or any class within the package of the protected members' class.Theprotectedaccessmodifiercannotbeappliedtoclassandinterfaces.Methods,fieldscanbedeclaredprotected,•howevermethodsandfieldsinainterfacecannotbedeclaredprotected.Protected access gives the subclass a chance to use the helper method or variable, while preventing a nonrelated •class from trying to use it.

Page 88: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

76

Example: The following parent class uses protected access control, to allow its child class override openSpeaker() •method:

class AudioPlayer { protected boolean openSpeaker(Speaker sp) { // implementation details }}

class StreamingAudioPlayer { boolean openSpeaker(Speaker sp) { // implementation details }}

HereifwedefineopenSpeaker()methodasprivatethenitwouldnotbeaccessiblefromanyotherclassother•than AudioPlayer. Ifwedefineitaspublicthenitwouldbecomeaccessibletoalltheoutsideworld.•Butourintensionistoexposethismethodtoitssubclassonly,thatswhyweusedprotectedmodifier.•

4.22 Access Control and InheritanceThe following rules for inherited methods are enforced:•Methods declared public in a superclass also must be public in all subclasses.•Methods declared protected in a superclass must either be protected or public in subclasses; they cannot be •private.Methodsdeclaredwithoutaccesscontrol(nomodifierwasused)canbedeclaredmoreprivateinsubclasses.•Methods declared private are not inherited at all, so there is no rule for them.•

4.23 Java Modifier TypesModifiersarekeywordsthatyouaddtothosedefinitionstochangetheirmeanings.•TheJavalanguagehasawidevarietyofmodifiers,includingthefollowing:•

JavaAccessModifiers �NonAccessModifiers �

Touseamodifier,youincludeitskeywordinthedefinitionofaclass,method,orvariable.•

public class className { // ...}private boolean myFlag;

staticfinaldoubleweeks=9.5;

protectedstaticfinalintBOXWIDTH=42;

public static void main(String[] arguments) { // body of method}

Themodifierprecedestherestofthestatement,asinthefollowingexamples(Italicones):•

Page 89: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

77

4.24 Access Control ModifiersJavaprovidesanumberofaccessmodifierstosetaccesslevelsforclasses,variables,methodsandconstructors.The four access levels are:

Visibletothepackage.thedefault.Nomodifiersareneeded.•Visible to the class only (private).•Visible to the world (public).•Visible to the package and all subclasses (protected).•

Non Access ModifiersJavaprovidesanumberofnon-accessmodifierstoachievemuchotherfunctionality.

Thestaticmodifierforcreatingclassmethodsandvariables•Thefinalmodifierforfinalizingtheimplementationsofclasses,methods,andvariables.•Theabstractmodifierforcreatingabstractclassesandmethods.•Thesynchronisedandvolatilemodifiers,whichareusedforthreads.•

4.25 Java Loops - for, while and do...whileThere may be a situation when we need to execute a block of code several number of times, and is often referred •to as a loop.Javahasveryflexiblethreeloopingmechanisms.Youcanuseoneofthefollowingthreeloops:•

while Loop �do...while Loop �for Loop �

As of java 5 the enhanced for loop was introduced. This is mainly used for Arrays.•

The while LoopA while loop is a control structure that allows you to repeat a task a certain number of times.Syntax: The syntax of a while loop is:

while(Boolean_expression){ //Statements}

When executing, if the boolean_expression result is true then the actions inside the loop will be executed. This •will continue as long as the expression result is true.Here key point of the while loop is that the loop might not ever run. •Whentheexpressionistestedandtheresultisfalse,theloopbodywillbeskippedandthefirststatementafter•the while loop will be executed.

Page 90: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

78

public class Test { public static void main(String args[]){ int x= 10;

while( x < 20 ){ System.out.print("value of x : " + x ); x++; System.out.print("\n"); } }}This would produce following result:

value of x : 10value of x : 11value of x : 12value of x : 13value of x : 14value of x : 15value of x : 16value of x : 17value of x : 18value of x : 19

The do...while LoopA do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one •time.Syntax: The syntax of a do...while loop is:•

do{ //Statements}while(Boolean_expression);

Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute once •before the Boolean is tested.IftheBooleanexpressionistrue,theflowofcontroljumpsbackuptodo,andthestatementsintheloopexecute•again. This process repeats until the Boolean expression is false.

Page 91: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

79

public class Test { public static void main(String args[]){ int x= 10;

do{ System.out.print("value of x : " + x ); x++; System.out.print("\n"); }while( x < 20 ); }}This would produce following result:

value of x : 10value of x : 11value of x : 12value of x : 13value of x : 14value of x : 15value of x : 16value of x : 17value of x : 18value of x : 19

The for LoopAforloopisarepetitioncontrolstructurethatallowsyoutoefficientlywritealoopthatneedstoexecutea•specificnumberoftimes.A for loop is useful when you know how many times a task is to be repeated.•Syntax: The syntax of a for loop is:•

for(initialization; Boolean_expression; update){ //Statements}

Hereistheflowofcontrolinaforloop:•Theinitializationstepisexecutedfirst,andonlyonce.Thisstepallowsyoutodeclareandinitialiseanyloop �control variables. You are not required to put a statement here, as long as a semicolon appears.

Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the �bodyoftheloopdoesnotexecuteandflowofcontroljumpstothenextstatementpasttheforloop.Afterthebodyoftheforloopexecutes,theflowofcontroljumpsbackuptotheupdatestatement.This �statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the Boolean expression.The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats itself �(body of loop, then update step, then Boolean expression). After the Boolean expression is false, the for loop terminates.

Page 92: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

80

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

for(int x = 10; x < 20; x = x+1){ System.out.print("value of x : " + x ); System.out.print("\n"); } }}This would produce following result:

value of x : 10value of x : 11value of x : 12value of x : 13value of x : 14value of x : 15value of x : 16value of x : 17value of x : 18value of x : 19

Enhanced for loop in JavaAs of java 5 the enhanced for loop was introduced. This is mainly used for Arrays.•Syntax: The syntax of enhanced for loop is:•

for(declaration : expression){ //Statements}

Declaration: The newly declared block variable, which is of a type compatible with the elements of the array you are accessing. The variable will be available within the for block and its value would be the same as the current array element.

Expression : This evaluate to the array you need to loop through. The expression can be an array variable or method call that returns an array.

Page 93: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

81

Example:

public class Test { public static void main(String args[]){ int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ){ System.out.print( x ); System.out.print(","); } System.out.print("\n"); String [] names ={"James", "Larry", "Tom", "Lacy"}; for( String name : names ) { System.out.print( name ); System.out.print(","); } }}This would produce following result:

10,20,30,40,50,James,Larry,Tom,Lacy,

The break keyword:The break keyword is used to stop the entire loop. The break keyword must be used inside any loop or a switch •statement.The break keyword will stop the execution of the innermost loop and start executing the next line of code after •the block.Syntax: The syntax of a break is a single statement inside any loop:•

break;

Example

public class Test { public static void main(String args[]){ int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ){ if( x == 30 ){ break; } System.out.print( x ); System.out.print("\n"); } }}This would produce following result:

1020

Page 94: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

82

The continue keyword:The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump •to the next iteration of the loop.Inaforloop,thecontinuekeywordcausesflowofcontroltoimmediatelyjumptotheupdatestatement.•Inawhileloopordo/whileloop,flowofcontrolimmediatelyjumpstotheBooleanexpression.•Syntax: The syntax of a continue is a single statement inside any loop:•

continue;

Example

public class Test { public static void main(String args[]){ int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ){ if( x == 30 ){ continue; } System.out.print( x ); System.out.print("\n"); } }}This would produce following result:

10204050

4.26 Java Decision MakingThere are two types of decision making statements in Java. They are:

if statements•switch statements•

The if statement: An if statement consists of a Boolean expression followed by one or more statements.

Syntax: The syntax of an if statement is:

if(Boolean_expression){ //Statements will execute if the Boolean expression is true}

If the boolean expression evaluates to true then the block of code inside the if statement will be executed. If not the firstsetofcodeaftertheendoftheifstatement(aftertheclosingcurlybrace)willbeexecuted.

Page 95: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

83

public class Test { public static void main(String args[]){ int x = 10;

if( x < 20 ){ System.out.print("This is if statement"); } }}

This would produce following result:

This is if statement

The if...else statement:An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.Syntax: The syntax of a if...else is:

if(Boolean_expression){ //Executes when the Boolean expression is true}else{ //Executes when the Boolean expression is false}

Example

public class Test { public static void main(String args[]){ int x = 30;

if( x < 20 ){ System.out.print("This is if statement"); }else{ System.out.print("This is else statement"); } }}This would produce following result:

This is else statement

The if...else if...else statementAn if statement can be followed by an optional else if...else statement, which is very usefull to test various •conditions using single if...else if statement.When using if , else if , else statements there are few points to keep in mind.•An if can have zero or one else's and it must come after any else if's.•An if can have zero to many else if's and they must come before the else.•Once an else if succeeds, none of he remaining else if's or else's will be tested.•Syntax: The syntax of a if...else is:•

Page 96: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

84

if(Boolean_expression 1){ //Executes when the Boolean expression 1 is true}else if(Boolean_expression 2){ //Executes when the Boolean expression 2 is true}else if(Boolean_expression 3){ //Executes when the Boolean expression 3 is true}else { //Executes when the none of the above condition is true.}

Example:

public class Test { public static void main(String args[]){ int x = 30;

if( x == 10 ){ System.out.print("Value of X is 10"); }else if( x == 20 ){ System.out.print("Value of X is 20"); }else if( x == 30 ){ System.out.print("Value of X is 30"); }else{ System.out.print("This is else statement"); } }}This would produce following result:

Value of X is 30

Nested if...else Statement:It is always legal to nest if-else statements, which means you can use one if or else if statement inside another •if or else if statement.Syntax: The syntax for a nested if...else is as follows:•

if(Boolean_expression 1){ //Executes when the Boolean expression 1 is true if(Boolean_expression 2){ //Executes when the Boolean expression 2 is true }}

You can nest else if...else in the similar way as we have nested if statement.

Page 97: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

85

Example:

public class Test { public static void main(String args[]){ int x = 30; int y = 10;

if( x == 30 ){ if( y == 10 ){ System.out.print("X = 30 and Y = 10"); } }}This would produce following result:

X = 30 and Y = 10

The switch statement:A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, •and the variable being switched on is checked for each case.Syntax: The syntax of enhanced for loop is:•

switch(expression){ case value : //Statements break; //optional case value : //Statements break; //optional //You can have any number of case statements. default : //Optional //Statements}

The following rules apply to a switch statement:The variable used in a switch statement can only be a byte, short, int, or char.•You can have any number of case statements within a switch. Each case is followed by the value to be compared •to and a colon.The value for a case must be the same data type as the variable in the switch, and it must be a constant or a •literal.When the variable being switched on is equal to a case, the statements following that case will execute until a •break statement is reached.Whenabreakstatementisreached,theswitchterminates,andtheflowofcontroljumpstothenextlinefollowing•the switch statement.Noteverycaseneedstocontainabreak.Ifnobreakappears,theflowofcontrolwillfallthroughtosubsequent•cases until a break is reached.A switch statement can have an optional default case, which must appear at the end of the switch. The default •case can be used for performing a task when none of the cases is true. No break is needed in the default case.

Page 98: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

86

Example

public class Test { public static void main(String args[]){ char grade = args[0].charAt(0);

switch(grade) { case 'A' : System.out.println("Excellent!"); break; case 'B' : case 'C' : System.out.println("Well done"); break; case 'D' : System.out.println("You passed"); case 'F' : System.out.println("Better try again"); break; default : System.out.println("Invalid grade"); } System.out.println("Your grade is " + grade); }}Compile and run above program using various command line arguments. This would produce following result:

$ java Test aInvalid gradeYour grade is a a$ java Test AExcellent!Your grade is a A$ java Test CWell doneYour grade is a C$

Page 99: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

87

Summary WhenweconsideraJavaprogramitcanbedefinedasacollectionofobjectsthatcommunicateviainvoking•each others methods.Objects have states and behaviours. Example: A dog has states-colour, name, breed as well as behaviours •-wagging, barking, and eating. An object is an instance of a class.Aclass can be defined as a template/blue print that describe the behaviors/states that object of its type•support.A method is basically behaviour. A class can contain many methods. It is in methods where the logics are written, •data is manipulated and all the actions are executed.Each object has its unique set of instant variables. An object .s state is created by the values assigned to these •instant variables.JavaiscasesensitivewhichmeansidentifierHelloandhellowouldhavedifferentmeaninginJava.•ForallclassnamesthefirstlettershouldbeinUpperCase.•All method names should start with a lower case letter. If several words are used to form the name of the method, •theneachinnerword'sfirstlettershouldbeinUpperCase.ExamplepublicvoidmyMethodName()Nameoftheprogramfileshouldexactlymatchtheclassname.Whensavingthefileyoushouldsaveitusing•the class name (Remember java is case sensitive) and append '.java' to the end of the name.Java program processing starts from the main() method which is a mandatory part of every java program..•Alljavacomponentsrequirenames.Namesusedforclasses,variablesandmethodsarecalledidentifiers.•

Allidentifiersshouldbeginwithaletter(AtoZoratoz),currencycharacter($)oranunderscore(-). �Afterthefirstcharacteridentifierscanhaveanycombinationofcharacters. �Akeywordcannotbeusedasanidentifier. �

Mostimportantlyidentifiersarecasesensitive.•Java supports single line and multi-line comments very similar to c and c++.•All characters available inside any comment are ignored by Java compiler.•Basically if you need to create a new class and here is already a class that has some of the code you require, •then it is possible to derive your new class from the already existing code.

References Richard F. Raposa, 2009. • SCJP Sun certified programmer for Java platform, SE6 study guide. John Wiley and Sons. Powell, 2004. • Java Script: The Complete Reference. Tata McGraw-Hill. Jim Knowlton, 2008. • Python: create-modify-reuse. John Wiley and Sons

Recommended Reading Balagurusamy, 2009. • Programming With Java 4E. Tata McGraw-Hill. Mary Campione, Kathy Walrath, Alison Huml, 2001. • The Java tutorial: a short course on the basics. Addison-Wesley. Arulkumaran Kumaraswamipillai, Sivayini Arulkumaran,2007. • Java/J2EE Job Interview Companion. Lulu.com.

Page 100: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

88

Self AssessmentWhenweconsideraJavaprogramitcanbedefinedasa___________thatcommunicateviainvokingeach1. others methods.

collection of objectsa. collection of valuesb. collection of data c. collection of programd.

Objects have_______________.2. conditions and characteristics a. states and behavioursb. positions and placesc. system and security d.

A__________canbedefinedasatemplate/blueprintthatdescribethebehaviors/statesthatobjectofitstype3. support.

classa. object b. states c. behaviours d.

All java components require__________.4. data a. namesb. variable c. classes d.

Names used for classes, variables and methods are called__________.5. dataa. effectors b. identifiersc. informerd.

A__________cannotbeusedasanidentifier.6. values a. characterb. string c. keywordd.

Java supports single line and multi-line comments very similar to________.7. oracle and phpa. asp and .net b. .c and c#c. c and c++d.

Page 101: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

89

A line containing only whitespace, possibly with a comment, is known as a ________. 8. blank linea. white line b. space c. blank d.

___________play a vital role when it comes to the concept of inheritance. 9. Interfacesa. Interiors b. Inputs c. Insertionsd.

Variablesdefinedinsidemethods,constructorsorblocksarecalled________________.10. restricted variablesa. local variablesb. global variables c. narrow variablesd.

Page 102: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

90

Chapter V

Number Class

Aim

The aim of this chapter is to:

enlighten the concept of number class •

enrich the concept of number methods •

elucidate the commands used for comparing •

explain the command used for equal•

Objectives

The objectives of this chapter are to:

elaborate the concept toString()•

evaluate different methods used in Java •

explainmethodsusedtofindequal•

elucidate the method used to evaluate logarithm arguments •

Learning outcome

At the end of this chapter, the students will be able to:

evaluate method for drawing square root of any number •

enrich method for trigonometry •

draw a programs to understand the various arithmetic’s methods •

Page 103: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

91

5.1 Introduction to Number ClassNormally, when we work with Numbers, we use primitive data types such as byte, int, long, double etc.•

Example:int i = 5000;floatgpa=13.65; byte mask = 0xaf;

However in development we come across situations were we need to use objects instead of primitive data •types. In-order to achieve this Java provides wrapper classes for each primitive data type.•All the wrapper classes (Integer, Long, Byte, Double, Float, Short) are subclasses of the abstract class •Number.

Number

Byte

Integer Short Long

Double Float

Fig. 5.1 Number Class

This wrapping is taken care of by the compiler. •This process is called boxing. •So when a primitive is used when an object is required the compiler boxes the primitive type in its wrapper •class. Similarly the compiler unboxes the object to a primitive as well. •The Number is part of the java.lang package. Here is an example of boxing and unboxing:•

public class Test{ public static void main(String args[]){ Integer x = 5; // boxes int to an Integer object x = x + 10; // unboxes the Integer to a int System.out.println(x); }}This would produce following result:

5

When x is assigned integer values, the compiler boxes the integer because x is integer objects. Later, x is unboxed •so that they can be added as integers.

Page 104: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

92

5.2 Number MethodsHere is the list of the instance methods that all the subclasses of the Number class implement:

5.2.1 Java - xxxValue() MethodsConverts the value of the Number object to the xxx data type and returned it.

DescriptionThe method converts the value of the Number Object that invokes the method to the primitive data type that is returned from the method.Syntax: Here is a separate method for each primitive data type:

byte byteValue()short shortValue()int intValue()long longValue()floatfloatValue()double doubleValue()

ParametersHere is the detail of parameters:

NA•

Return valueThese method returns the primitive data type that is given in the signature.•

Example

public class Test{ public static void main(String args[]){ Integer x = 5; // Returns byte primitive data type System.out.println( x.byteValue() );

// Returns double primitive data type System.out.println(x.doubleValue());

// Returns long primitive data type System.out.println( x.longValue() ); }}This produces following result:

55.05

Page 105: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

93

5.2.2 compareTo()CompareTo() compares the Number object to the argument.

DescriptionThe method compares the Number object that invoked the method to the argument. It is possible to compare •Byte,Long,Integer etc.However two different types cannot be compared, Both the argument and the Number object invoking the •method should be of same type.

Syntax

public int compareTo( NumberSubClass referenceName )

ParametersHere is the detail of parametersreferenceName could be a Byte, Double, Integer, Float, Long or Short.

Return ValueIf the Integer is equal to the argument then 0 is returned.•If the Integer is less than the argument then -1 is returned.•If the Integer is greater than the argument then 1 is returned.•

Example

public class Test{ public static void main(String args[]){ Integer x = 5; System.out.println(x.compareTo(3)); System.out.println(x.compareTo(5)); System.out.println(x.compareTo(8)); }}This produces following result:

10-1

5.2.3 equals()Equals() command determines whether the number object is equal to the argument.

DescriptionThe method determines whether the Number Object that invokes the method is equal to the argument.

Syntax

public boolean equals(Object o)

ParametersHere is the detail of parameters:

Object O is Any object.

Page 106: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

94

Return valueThe methods return True if the argument is not null and is an object of the same type and with the same numeric value. There are some extra requirements for Double and Float objects that are described in the Java API documentation.

Example

public class Test{ public static void main(String args[]){ Integer x = 5; Integer y = 10; Integer z =5; Short a = 5;

System.out.println(x.equals(y)); System.out.println(x.equals(z)); System.out.println(x.equals(a)); }}This produces following result:

falsetruefalse

5.2.4 valueOf()Valueof() returns an Integer object holding the value of the specified primitive.

The valueOf method returns the relevant Number Object holding the value of the argument passed. The argument •can be a primitive data type, String etc.This method is a static method. The method can take two arguments, where one is a String and the other is a •radix.

SyntaxAll the variant of this method are given below.

static Integer valueOf(int i)static Integer valueOf(String s)static Integer valueOf(String s, int radix)

ParametersHere is the detail of parameters:

int:• An int for which Integer representation would be returned.String s:• A String for which Integer representation would be returned.int radix:• This would be used to decide the value of returned Integer based on passed String.

Return value valueOf(int i):• ThisreturnsanIntegerobjectholdingthevalueofthespecifiedprimitive.valueOf(String s):• ThisreturnsanIntegerobjectholdingthevalueofthespecifiedstringrepresentation.valueOf(String s, int radix):• ThisreturnsanIntegerobjectholdingtheintegervalueofthespecifiedstringrepresentation, parsed with the value of radix.

Page 107: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

95

Example

public class Test{ public static void main(String args[]){ Integer x =Integer.valueOf(9); Double c = Double.valueOf(5); Float a = Float.valueOf("80");

Integer b = Integer.valueOf("444",16);

System.out.println(x); System.out.println(c); System.out.println(a); System.out.println(b); }}This produces following result:

95.080.01092

5.2.5 toString()toString()returnsaStringobjectrepresentingthevalueofspecifiedintorInteger.

The method is used to get a String object representing the value of the Number Object.•If the method takes a primitive data type as an argument then the String object representing the primitive data •type value is return.IfthemethodtakestwoargumentsthenaStringrepresentationofthefirstargumentintheradixspecifiedby•the second argument will be returned.

SyntaxAll the variant of this method are given below.

String toString()static String toString(int i)

ParametersHere is the detail of parameters:int: An int for which string representation would be returned.

Return valuetoString():• This returns a String object representing the value of this Integer.toString(int i):• ThisreturnsaStringobjectrepresentingthespecifiedinteger.

Page 108: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

96

Example

public class Test{ public static void main(String args[]){ Integer x = 5;

System.out.println(x.toString()); System.out.println(Integer.toString(12)); }}

This produces following result:

512

5.2.6 Java - parseInt() MethodDescription:This method is used to get the primitive data type of a certain String. parseXxx() is a static method and can have one argument or two.

Syntax: All the variant of this method are given below:

static int parseInt(String s)static int parseInt(String s, int radix)

ParametersHere is the detail of parameters

String s :• This is a string representation of decimal.int radix : • This would be used to convert String s into integer.

Return Value parseInt(String s):• This returns an integer (decimal only).parseInt(int i):• This returns an integer, given a string representation of decimal, binary, octal, or hexadecimal (radix equals 10, 2, 8, or 16 respectively) numbers as input.

Page 109: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

97

Example:

public class Test{ public static void main(String args[]){ int x =Integer.parseInt("9"); double c = Double.parseDouble("5"); int b = Integer.parseInt("444",16);

System.out.println(x); System.out.println(c); System.out.println(b); }}This produces following result:

95.01092

5.2.7 Java - abs() MethodThemethodgivestheabsolutevalueoftheargument.Theargumentcanbeint,float,long,double,short,byte.

Syntax:All the variant of this method are given below:

double abs(double d)floatabs(floatf)int abs(int i)long abs(long lng)

Parameters: Here is the detail of parameters:

Any primitive data type•

Return value: Returns the absolute value of the argument

Page 110: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

98

Example

public class Test{ public static void main(String args[]){ Integer a = -8; double d = -100;floatf=-90;

System.out.println(Math.abs(a)); System.out.println(Math.abs(d)); System.out.println(Math.abs(f)); }}This produces following result:

8100.080.0

5.2.8 Java - ceil() MethodReturns the smallest integer that is greater than or equal to the argument. Returned as a double.The method ceil gives the smallest integer that is greater than or equal to the argument.

Syntax: This method has following variants:

double ceil(double d)doubleceil(floatf)

Parameters:Here is the detail of parameters:

Adoubleorfloatprimitivedatatype•

Return Value:Returns the smallest integer that is greater than or equal to the argument. Returned as a double.•

Example

public class Test{ public static void main(String args[]){ double d = -100.675;floatf=-90;

System.out.println(Math.ceil(d)); System.out.println(Math.ceil(f)); System.out.println(Math.floor(d));System.out.println(Math.floor(f)); }}This produces following result:

-100.0-90.0-101.0-90.0

Page 111: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

99

5.2.9 Java - floor() MethodReturns the largest integer that is less than or equal to the argument. Returned as a double.Themethodfloorgivesthelargestintegerthatislessthanorequaltotheargument.

Syntax: This method has following variants:

doublefloor(doubled)doublefloor(floatf)

ParametersHere is the detail of parameters:

Adoubleorfloatprimitivedatatype•

Return Value Returns the largest integer that is less than or equal to the argument. Returned as a double.

Example

public class Test{ public static void main(String args[]){ double d = -100.675;floatf=-90; System.out.println(Math.floor(d));System.out.println(Math.floor(f));

System.out.println(Math.ceil(d)); System.out.println(Math.ceil(f)); }}This produces following result:

-101.0-90.0-100.0-90.0

5.2.10 Java - rint() MethodReturns the integer that is closest in value to the argument. Returned as a double.The method rint returns the integer that is closest in value to the argument.

Syntax:

double rint(double d)

Parameters:Here is the detail of parameters:

A double primitive data type•

Page 112: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

100

Return Value:Returns the integer that is closest in value to the argument. Returned as a double.Example

public class Test{ public static void main(String args[]){ double d = 100.675; double e = 100.500; double f = 100.200;

System.out.println(Math.rint(d)); System.out.println(Math.rint(e)); System.out.println(Math.rint(f)); }}This produces following result:

101.0100.0100.0

5.2.11 Java - round() MethodReturns the closest long or int, as indicated by the method’s return type, to the argument.

Description The method round returns the closest long or int, as given by the methods return type.

SyntaxThis method has following variants

long round(double d)intround(floatf)

ParametersHere is the detail of parameters:

Adoubleorfloatprimitivedatatype•

Return value Returns the closest long or int, as indicated by the method's return type, to the argument.

Page 113: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

101

Example

public class Test{ public static void main(String args[]){ double d = 100.675; double e = 100.500;floatf=100;floatg=90f;

System.out.println(Math.round(d)); System.out.println(Math.round(e)); System.out.println(Math.round(f)); System.out.println(Math.round(g)); }}This produces following result:

10110110090

5.2.12 Java - min() MethodReturns the smaller of the two arguments.

DescriptionThemethodgivesthesmallerofthetwoarguments.Theargumentcanbeint,float,long,double.

SyntaxThis method has following variants

double min(double arg1, double arg2)floatmin(floatarg1,floatarg2)int min(int arg1, int arg2)long min(long arg1, long arg2)

ParametersHere is the detail of parameters:

A primitive data types•

Return value Returns the smaller of the two arguments.

Page 114: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

102

Example

public class Test{ public static void main(String args[]){ System.out.println(Math.min(12.123, 12.456)); System.out.println(Math.min(23.12, 23.0)); }}This produces following result:

12.12323.0

5.2.13 Java - max() MethodReturns the larger of the two arguments.Themethodgivesthemaximumofthetwoarguments.Theargumentcanbeint,float,long,double.

SyntaxThis method has following variants:

double max(double arg1, double arg2)floatmax(floatarg1,floatarg2)int max(int arg1, int arg2)long max(long arg1, long arg2)

ParametersHere is the detail of parameters

A primitive data types•

Return value Returns the maximum of the two arguments.

Example

public class Test{ public static void main(String args[]){ System.out.println(Math.max(12.123, 12.456)); System.out.println(Math.max(23.12, 23.0)); }}This produces following result:

12.45623.12

Page 115: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

103

5.2.14 Java - exp() MethodReturns the base of the natural logarithms, e, to the power of the argument.

DescriptionThe method returns the base of the natural logarithms, e, to the power of the argument.

Syntax

double exp(double d)

ParametersHere is the detail of parameters:

A primitive data types•

Return value Returns the base of the natural logarithms, e, to the power of the argument.

Example

public class Test{ public static void main(String args[]){ double x = 11.635; double y = 2.76;

System.out.printf("The value of e is %.4f%n", Math.E); System.out.printf("exp(%.3f) is %.3f%n", x, Math.exp(x)); }}

This produces following result:

The value of e is 2.7183exp(11.635) is 112983.831

5.2.15 Java - log() MethodReturns the natural logarithm of the argument.

DescriptionThe method returns the natural logarithm of the argument.

Syntaxdouble log(double d)

ParametersHere is the detail of parameters:

A primitive data types•

Return value Returns the natural logarithm of the argument.

Page 116: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

104

Example

public class Test{ public static void main(String args[]){ double x = 11.635; double y = 2.76;

System.out.printf("The value of e is %.4f%n", Math.E);\ System.out.printf("log(%.3f) is %.3f%n", x, Math.log(x));

}}This produces following result:

The value of e is 2.7183log(11.635) is 2.454

5.2.16 Java - pow() MethodReturnsthevalueofthefirstargumentraisedtothepowerofthesecondargumentThemethodreturnsthevalueofthefirstargumentraisedtothepowerofthesecondargument.

Syntax

double pow(double base, double exponent)

ParametersHere is the detail of parameters:

A primitive data types•

Return value Returnsthevalueofthefirstargumentraisedtothepowerofthesecondargument.•

Example

public class Test{ public static void main(String args[]){ double x = 11.635; double y = 2.76;

System.out.printf("The value of e is %.4f%n", Math.E); System.out.printf("pow(%.3f, %.3f) is %.3f%n", x, y, Math.pow(x, y));

}}This produces following result:

The value of e is 2.7183pow(11.635, 2.760) is 874.008

Page 117: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

105

5.2.17 Java - sqrt() MethodReturns the square root of the argument.The method returns the square root of the argument.

Syntax

double sqrt(double d)

ParametersHere is the detail of parameters

A primitive data types•

Return value Returns the square root of the argument.

Example

public class Test{ public static void main(String args[]){ double x = 11.635; double y = 2.76;

System.out.printf("The value of e is %.4f%n", Math.E); System.out.printf("sqrt(%.3f) is %.3f%n", x, Math.sqrt(x));

}}This produces following result:

The value of e is 2.7183sqrt(11.635) is 3.411

5.2.18 Java - sin() MethodReturnsthesineofthespecifieddoublevalue.Themethodreturnsthesineofthespecifieddoublevalue.

Syntax

double sin(double d)

ParametersHere is the detail of parameters

A double data types•

Return value Returnsthesineofthespecifieddoublevalue.

Page 118: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

106

Example

public class Test{ public static void main(String args[]){ double degrees = 45.0; double radians = Math.toRadians(degrees);

System.out.format("The value of pi is %.4f%n", Math.PI); System.out.format("The sine of %.1f degrees is %.4f%n", degrees, Math.sin(radians));

}}

This produces following result

The value of pi is 3.1416The sine of 45.0 degrees is 0.7071

5.2.19 Java - cos() MethodReturnsthecosineofthespecifieddoublevalue.Themethodreturnsthecosineofthespecifieddoublevalue.

Syntax

double cos(double d)

ParametersHere is the detail of parameters:

A double data types•

Return value Returnsthecosineofthespecifieddoublevalue.

Example

public class Test{ public static void main(String args[]){ double degrees = 45.0; double radians = Math.toRadians(degrees);

System.out.format("The value of pi is %.4f%n", Math.PI); System.out.format("The cosine of %.1f degrees is %.4f%n", degrees, Math.cos(radians));

}}This produces following result:

The value of pi is 3.1416The cosine of 45.0 degrees is 0.7071

Page 119: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

107

5.2.20 Java - tan() MethodReturnsthetangentofthespecifieddoublevalue.Themethodreturnsthetangentofthespecifieddoublevalue.

Syntax

double tan(double d)

ParametersHere is the detail of parameters:

A double data types•

Return value Returnsthetangentofthespecifieddoublevalue.

Example

public class Test{ public static void main(String args[]){ double degrees = 45.0; double radians = Math.toRadians(degrees);

System.out.format("The value of pi is %.4f%n", Math.PI); System.out.format("The tangent of %.1f degrees is %.4f%n", degrees, Math.tan(radians));

}}This produces following result:

The value of pi is 3.1416The tangent of 45.0 degrees is 1.0000

5.2.21 Java - asin() MethodReturnsthearcsineofthespecifieddoublevalue.Themethodreturnsthearcsineofthespecifieddoublevalue.

Syntax

double asin(double d)

ParametersHere is the detail of parameters:

A double data types•

Return value Returnsthearcsineofthespecifieddoublevalue.

Page 120: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

108

Example

public class Test{ public static void main(String args[]){ double degrees = 45.0; double radians = Math.toRadians(degrees);

System.out.format("The value of pi is %.4f%n", Math.PI); System.out.format("The arcsine of %.4f is %.4f degrees %n", Math.sin(radians), Math.toDegrees(Math.asin(Math.sin(radians))));

}}

This produces following result:

The value of pi is 3.1416The arcsine of 0.7071 is 45.0000 degrees

5.2.22 Java - acos() MethodReturnsthearccosineofthespecifieddoublevalue.Themethodreturnsthearccosineofthespecifieddoublevalue.

Syntaxdouble acos(double d)

ParametersHere is the detail of parameters

A double data types•

Return value Returnsthearccosineofthespecifieddoublevalue.

Example

public class Test{ public static void main(String args[]){ double degrees = 45.0; double radians = Math.toRadians(degrees);

System.out.format("The value of pi is %.4f%n", Math.PI); System.out.format("The arccosine of %.4f is %.4f degrees %n", Math.cos(radians), Math.toDegrees(Math.acos(Math.sin(radians)))); }}

This produces following result

The value of pi is 3.1416The arccosine of 0.7071 is 45.0000 degrees

Page 121: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

109

5.2.23 Java - atan() MethodReturnsthearctangentofthespecifieddoublevalue.Themethodreturnsthearctangentofthespecifieddoublevalue.

Syntax

double atan(double d)

ParametersHere is the detail of parameters

A double data types•

Return value Returnsthearctangentofthespecifieddoublevalue.

Example

public class Test{ public static void main(String args[]){ double degrees = 45.0; double radians = Math.toRadians(degrees); System.out.format("The value of pi is %.4f%n", Math.PI); System.out.format("The arctangent of %.4f is %.4f degrees %n", Math.cos(radians), Math.toDegrees(Math.atan(Math.sin(radians)))); }}This produces following result:

The value of pi is 3.1416The arctangent of 1.0000 is 45.0000 degrees

5.2.24 Java - atan2() MethodConverts rectangular coordinates (x, y) to polar coordinate (r, theta) and returns theta.The method Converts rectangular coordinates (x, y) to polar coordinate (r, theta) and returns theta.

Syntax

double atan2(double y, double x)

ParametersHere is the detail of parameters

X and Y co-ordinates in double data types•

Return value Returns theta from polar coordinate (r, theta)

Page 122: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

110

Example

public class Test{ public static void main(String args[]){ double x = 45.0; double y = 30.0;

System.out.println( Math.atan2(x, y) ); }}This produces following result:

0.982793723247329

5.2.25 Java - toDegrees() MethodConverts the argument to degreesThe method converts the argument value to degrees.

Syntax

double toDegrees(double d)

ParametersHere is the detail of parameters:

A double data type.•

Return value Return value is a double

Example

public class Test{ public static void main(String args[]){ double x = 45.0; double y = 30.0;

System.out.println( Math.toDegrees(x) ); System.out.println( Math.toDegrees(y) ); }}This produces following result

2578.31007808870441718.8733853924698

Page 123: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

111

5.2.26 Java-toRadians()Converts the argument to radians.

DescriptionThe method converts the argument value to radians.

Syntax

double toRadians(double d)

ParametersHere is the detail of parameters:

A double data type.•

Return Value Return value is a double

Example

public class Test{ public static void main(String args[]){ double x = 45.0; double y = 30.0;

System.out.println( Math.toRadians(x) ); System.out.println( Math.toRadians(y) ); }}This produces following result:

0.78539816339744830.5235987755982988

5.2.27 Java-random()Returns a random number.The method is used o generate a random number between 0.0 and 1.0. The range is: 0.0 =< Math.random < 1.0. Different ranges can be achieved by using arithmetic.

Syntax

static double random()

ParametersHere is the detail of parameters:

NA•

Return value Return value is a double

Page 124: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

112

Example

public class Test{ public static void main(String args[]){ System.out.println( Math.random() ); System.out.println( Math.random() ); }}This produces following result:

0.167639450614516570.400551253762343

5.3 Number MethodsHere is the list of the instance methods that all the subclasses of the Number class implement:

Methods with Description

xxxValue()Converts the value of this Number object to the xxx data type and returned it.

compareTo()Compares this Number object to the argument.

equals()Determines whether this number object is equal to the argument.

valueOf()ReturnsanIntegerobjectholdingthevalueofthespecifiedprimitive.

toString()ReturnsaStringobjectrepresentingthevalueofspecifiedintorInteger.

parseInt()This method is used to get the primitive data type of a certain String.

abs()Returns the absolute value of the argument.

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

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

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

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

min()Returns the smaller of the two arguments.

max()Returns the larger of the two arguments.

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

Page 125: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

113

log()Returns the natural logarithm of the argument.

pow()Returnsthevalueofthefirstargumentraisedtothepowerofthesecondargument.

sqrt()Returns the square root of the argument.

sin()Returnsthesineofthespecifieddoublevalue.

cos()Returnsthecosineofthespecifieddoublevalue.

tan()Returnsthetangentofthespecifieddoublevalue.

asin()Returnsthearcsineofthespecifieddoublevalue.

acos()Returnsthearccosineofthespecifieddoublevalue.

atan()Returnsthearctangentofthespecifieddoublevalue.

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

toDegrees()Converts the argument to degrees

toRadians()Converts the argument to radians.

random()Returns a random number.

Table 5.1 Number methods

Page 126: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

114

Summary Normally, when we work with Numbers, we use primitive data types such as byte, int, long, double etc.•All the wrapper classes (Integer, Long, Byte, Double, Float, Short) are subclasses of the abstract •class Number.When x is assigned integer values, the compiler boxes the integer because x is integer objects.•An XXX Values method converts the value of this Number object to the xxx data type and returned it.•xxxValue(): Converts the value of this Number object to the xxx data type and returned it.•compareTo(): Compares this Number object to the argument.•equals(): Determines whether this number object is equal to the argument.•valueOf():ReturnsanIntegerobjectholdingthevalueofthespecifiedprimitive.•toString():ReturnsaStringobjectrepresentingthevalueofspecifiedintorInteger.•parseInt(): This method is used to get the primitive data type of a certain String.•abs(): Returns the absolute value of the argument.•ceil(): Returns the smallest integer that is greater than or equal to the argument. Returned as a double.•floor():Returnsthelargestintegerthatislessthanorequaltotheargument.Returnedasadouble.•rint(): Returns the integer that is closest in value to the argument. Returned as a double.•round(): Returns the closest long or int, as indicated by the method's return type, to the argument.•min(): Returns the smaller of the two arguments.•max(): Returns the larger of the two arguments.•exp(): Returns the base of the natural logarithms, (e) to the power of the argument.•log(): Returns the natural logarithm of the argument.•pow():Returnsthevalueofthefirstargumentraisedtothepowerofthesecondargument.•sqrt(): Returns the square root of the argument.•sin():Returnsthesineofthespecifieddoublevalue.•cos():Returnsthecosineofthespecifieddoublevalue.•tan():Returnsthetangentofthespecifieddoublevalue.•asin():Returnsthearcsineofthespecifieddoublevalue.•acos():Returnsthearccosineofthespecifieddoublevalue.•atan():Returnsthearctangentofthespecifieddoublevalue.•atan2(): Converts rectangular coordinates (x, y) to polar coordinate (r, theta) and returns theta.•toDegrees(): Converts the argument to degrees•toRadians(): Converts the argument to radians.•random(): Returns a random number.•

ReferencesMary Campione, Kathy Walrath, Alison Huml, 2001.• The Java tutorial: a short course on the basics. Addison-Wesley. Y. Daniel Liang, 2010. • Introduction to Java Programming. Prentice Hall. Eckel, 2006. • Thinking Java. Pearson Education India.

Recommended Reading Arnold, 2000. • The Java Programming language. Pearson Education India. David Flanagan, 2005. • Java in a nutshell. O'Reilly Media, Inc.Mark Grand, Jonathan Knudsen, 1997. • Java fundamental classes reference. O'Reilly.

Page 127: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

115

Self Assessment__________ 1. converts the value of the Number object to the xxx data type and returned it.

X3value()a. XX Value()b. XXX valuec. XXXValue()d.

Which of the following sentences is true?2. Compare() compares the Number object to the argument.a. CompareToo() compares the Number object to the argument.b. CompareTo() compares the Number object to the argument.c. ToCompare() compares the Number object to the argument.d.

The method compares the Number object that invoked the method to the___________.3. argumenta. tussleb. disputec. spatd.

Which of the following sentences is true?4. If the Integer is equal to the argument then 1 is returned.a. If the Integer is equal to the argument then 0 is returned.b. If the Integer is equal to the argument then -1 is returned.c. If the Integer is equal to the argument then 0.1 is returned. d.

If the Integer is __________the argument then -1 is returned.5. less thana. equal to b. greater than c. negative d.

If the Integer is __________the argument then 1 is returned. 6. less thana. equal to b. greater than c. Positive d.

________command determines whether the number object is equal to the argument.7. Same()a. Identical()b. Equals()c. Similar()d.

Page 128: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

116

Valueof()returnsan______________objectholdingthevalueofthespecifiedprimitive.8. Integera. floatingb. string c. characterd.

____________returnsaStringobjectrepresentingthevalueofspecifiedintorInteger.9. String()a. btoString()b. ToString()c. Stringto()d.

_________is a string representation of decimal.10. String sa. String Tb. String Sc. String ssd.

Page 129: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

117

Chapter VI

Character Class, String and Array

Aim

The aim of this chapter is to:

explain the concept of character class•

draw programs for character class •

get an overview character methods•

draw programs for character methods •

Objectives

The objectives of this chapter are to:

describe methods used to convert uppercase character to lower case •

explain methods used to convert lower case character to upper case •

evaluate character strings methods •

elaborate strings class used in Java •

Learning outcome

At the end of this chapter, the students will be able to:

understand commands used to compare strings •

recognise strings commands used to calculate string length•

enlist the command used in string operation•

Page 130: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

118

6.1 Introduction to Character ClassNormally, when we work with characters, we use primitive data types char.

Example

char ch = ‘a’;// Unicode for uppercase Greek omega characterchar uniChar = ‘\u039A’; // an array of charschar[] charArray ={ ‘a’, ‘b’, ‘c’, ‘d’, ‘e’ };

However, in development we come across situations where we need to use objects instead of primitive data •types.In-order to achieve this Java provides wrapper classes Character for primitive data type char.•The Character class offers a number of useful class (i.e., static) methods for manipulating characters. •You can create a Character object with the Character constructor:•

Character ch = new Character(‘a’);

The Java compiler will also create a Character object for you under some circumstances. For example, if you •pass a primitive char into a method that expects an object, the compiler automatically converts the char to a Character for you. This feature is called autoboxing or unboxing, if the conversion goes the other way.

// Here following primitive char ‘a’// is boxed into the Character object chCharacter ch = ‘a’;

// Here primitive ‘x’ is boxed for method test,// return is unboxed to char ‘c’char c = test(‘x’);

A character preceded by a backslash (\) is an escape sequence and has special meaning to the compiler.•The newline character (\n) has been used frequently in this tutorial in System.out.println() statements to advance •to the next line after the string is printed.

6.2 Character MethodsHere is the list of the important instance methods that all the subclasses of the Character class implement

6.2.1 isLetter()isLetterdetermineswhetherthespecifiedcharvalueisaletter.

Themethoddetermineswhetherthespecifiedcharvalueisaletter.

Syntax

boolean isLetter(char ch)

Page 131: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

119

ParametersHere is the detail of parameters

Primitive character type•

Return valueReturns true if passed character is really a character.

Example

public class Test{ public static void main(String args[]){ System.out.println( Character.isLetter(‘c’)); System.out.println( Character.isLetter(‘5’)); }}This produces following result:

truefalse

6.2.2 isDigit()isDigit()determineswhetherthespecifiedcharvalueisadigit.Themethoddetermineswhetherthespecifiedcharvalueisadigit.

Syntax

boolean isDigit(char ch)

ParametersHere is the detail of parameters:

Primitive character type•

Return valueReturns true if passed character is really a digit.

Example

public class Test{ public static void main(String args[]){ System.out.println( Character.isDigit(‘c’)); System.out.println( Character.isDigit(‘5’)); }}This produces following result:

falsetrue

6.2.3 isWhitespace()isWhitespace()determineswhetherthespecifiedcharvalueiswhitespace.Themethoddetermineswhetherthespecifiedcharvalueisadigit.

Page 132: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

120

Syntax

boolean isWhitespace(char ch)

ParametersHere is the detail of parameters

Primitive character type•

Return valueReturns true if passed character is really a digit.

Example

public class Test{ public static void main(String args[]){ System.out.println( Character.isDigit(‘c’)); System.out.println( Character.isDigit(‘5’)); }}This produces following result:falsetrue

6.2.4 isUpperCase()isUpperCasedetermineswhetherthespecifiedcharvalueisuppercase.Themethoddetermineswhetherthespecifiedcharvalueisawhitespacewhichincludesspace,tabornewline.

Syntax

boolean isUpperCase(char ch)

ParametersHere is the detail of parameters

Primitive character type•

Return value Returns true if passed character is really a white space.

Page 133: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

121

Example

public class Test{ public static void main(String args[]){ System.out.println( Character.isWhitespace(‘c’)); System.out.println( Character.isWhitespace(‘ ‘)); System.out.println( Character.isWhitespace(‘\n’)); System.out.println( Character.isWhitespace(‘\t’)); }}This produces following result:

falsetruetruetrue

6.2.5 isLowerCase()isLowerCase()determineswhetherthespecifiedcharvalueislowercaseThemethoddetermineswhetherthespecifiedcharvalueislowercase.

Syntax

boolean isLowerCase(char ch)

ParametersHere is the detail of parameters

Primitive character type•

Return value Returns true if passed character is really a lowercase.

Example

public class Test{ public static void main(String args[]){ System.out.println( Character.isLowerCase(‘c’)); System.out.println( Character.isLowerCase(‘C’)); System.out.println( Character.isLowerCase(‘\n’)); System.out.println( Character.isLowerCase(‘\t’)); }}This produces following result:truefalsefalsefalse

Page 134: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

122

6.2.6 toUpperCase()toUpperCase()returnstheuppercaseformofthespecifiedcharvalue.Themethodreturnstheuppercaseformofthespecifiedcharvalue.

Syntax

char toUpperCase(char ch)

ParametersHere is the detail of parameters:

Primitive character type•

Return valueReturnstheuppercaseformofthespecifiedcharvalue.

Example

public class Test{ public static void main(String args[]){ System.out.println( Character.toUpperCase(‘c’)); System.out.println( Character.toUpperCase(‘C’)); }}This produces following result:

CC

6.2.7 toLowerCase()toLowerCase()returnsthelowercaseformofthespecifiedcharvalue.Themethodreturnsthelowercaseformofthespecifiedcharvalue.

Syntax

char toLowerCase(char ch)

ParametersHere is the detail of parameters:

Primitive character type•

Return value Returnsthelowercaseformofthespecifiedcharvalue.

Page 135: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

123

Example

public class Test{ public static void main(String args[]){ System.out.println( Character.toLowerCase(‘c’)); System.out.println( Character.toLowerCase(‘C’)); }}This produces following result:cc

6.2.8 toString()toString()returnsaStringobjectrepresentingthespecifiedcharactervaluethatis,aone-characterstring.ThemethodreturnsaStringobjectrepresentingthespecifiedcharactervaluethatis,aone-characterstring.

Syntax

String toString(char ch)

ParametersHere is the detail of parameters

Primitive character type•

Return valueReturns String object

Example

public class Test{ public static void main(String args[]){ System.out.println( Character.toString(‘c’)); System.out.println( Character.toString(‘C’)); }}

This produces following result:

cC

6.3 String ClassStrings, which are widely used in Java programming, are a sequence of characters. In the Java programming •language, strings are objects.The Java platform provides the String class to create and manipulate strings.•

Page 136: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

124

Creating StringsThe most direct way to create a string is to write:•

String greeting = “Hello world!”.

Whenever it encounters a string literal in your code, the compiler creates a String object with its valuein this •case, “Hello world!’.As with any other object, you can create String objects by using the new keyword and a constructor. •The String class has eleven constructors that allow you to provide the initial value of the string using different •sources, such as an array of characters:

public class StringDemo{ public static void main(String args[]){ char[] helloArray = { ‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘.’}; String helloString = new String(helloArray); System.out.println( helloString ); }}This would produce following result:hello

Note: The String class is immutable; so that once it is created a String object cannot be changed. If there is a necessity tomakealotofmodificationstoStringsofcharactersthenyoushoulduseStringBuffer&StringBuilderClasses.

6.4 String LengthMethods used to obtain information about an object are known as accessor methods. •One access or method that you can use with strings is the length() method, which returns the number of characters •contained in the string object.After the following two lines of code have been executed, len equals 17•

public class StringDemo{ public static void main(String args[]){ String palindrome = “Dot saw I was Tod”; int len = palindrome.length(); System.out.println( “String Length is : “ + len ); }}This would produce following result:

String Length is : 17

6.5 Concatenating StringsThe String class includes a method for concatenating two strings:•

string1.concat(string2);

This returns a new string that is string1 with string2 added to it at the end. •

Page 137: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

125

You can also use the concat() method with string literals, as in:•

“Mynameis“.concat(“Zara”);

Strings are more commonly concatenated with the + operator, as in:•

“Hello,” + “world”+ “!”

Which results in:•

“Hello, world!”

Let us look at the following example:•

public class StringDemo{ public static void main(String args[]){ String string1 = “saw I was “; System.out.println(“Dot “ + string1 + “Tod”); }}This would produce following result:Dot saw I was Tod

6.6 Creating Format StringsYou have printf() and format() methods to print output with formatted numbers. •The String class has an equivalent class method, format(), that returns a String object rather than a PrintStream •object.Using String’s static format() method allows you to create a formatted string that you can reuse, as opposed to •a one-time print statement. For example, instead of:

System.out.printf(“Thevalueof thefloatvariable is “+”%f,while thevalueof the integer “+“variableis%d,andthestring“+”is%s”,floatVar,intVar,stringVar);

You can write:•

String fs;fs=String.format(“Thevalueof thefloatvariable is“+”%f,while thevalueof the integer“+“variableis%d,andthestring“+”is%s”,floatVar,intVar,stringVar);System.out.println(fs);

6.7 String MethodsHere are the list methods supported by String classThismethodreturnsthecharacterlocatedattheString’sspecifiedindex.Thestringindexesstartfromzero.

SyntaxHere is the syntax of this method:

Page 138: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

126

public char charAt(int index)

ParametersHere is the detail of parameters:Index: Index of the character to be returned.

Return value: Returnsacharatthespecifiedindex.

Example

public class Test{ public static void main(String args[]){ String s = “Strings are immutable”; char result = s.charAt(8); System.out.println(result); }}This produces following result:a

6.7.1 char charAt(int index) CharcharAt(intindex)returnsthecharacteratthespecifiedindex.There are two variant of this method. First method compares this String to another Object and second method compares two strings lexicographically.

SyntaxHere is the syntax of this method:

int compareTo(Object o)orint compareTo(String anotherString)

ParametersHere is the detail of parameters:Object o: the Object to be compared.String anotherString: the String to be compared.

Return value: The value 0 if the argument is a string lexicographically equal to this string; a value less than 0 if the argument is a string lexicographically greater than this string; and a value greater than 0 if the argument is a string lexicographically less than this string.

Page 139: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

127

Example

public class Test{ public static void main(String args[]){ String str1 = “Strings are immutable”; String str2 = “Strings are immutable”; String str3 = “Integers are not immutable”;

int result = str1.compareTo( str2 ); System.out.println(result); result = str2.compareTo( str3 ); System.out.println(result); result = str3.compareTo( str1 ); System.out.println(result); }}This produces following result:

010-10

6.7.2 int compareTo(Object o) Compares this String to another Object.There are two variant of this method. First method compares this String to another Object and second method compares two strings lexicographically.

SyntaxHere is the syntax of this method:

int compareTo(Object o)orint compareTo(String anotherString)

ParametersHere is the detail of parameters:Object o: the Object to be compared.String anotherString: the String to be compared.

Return value: The value 0 if the argument is a string lexicographically equal to this string; a value less than 0 if the argument is a string lexicographically greater than this string; and a value greater than 0 if the argument is a string lexicographically less than this string.

Page 140: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

128

Example

public class Test{ public static void main(String args[]){ String str1 = “Strings are immutable”; String str2 = “Strings are immutable”; String str3 = “Integers are not immutable”;

int result = str1.compareTo( str2 ); System.out.println(result); result = str2.compareTo( str3 ); System.out.println(result); result = str3.compareTo( str1 ); System.out.println(result); }}This produces following result:

010-10

6.7.3 int compareTo(String anotherString)Compares two strings lexicographically.This method compares two strings lexicographically, ignoring case differences.

SyntaxHere is the syntax of this method:

int compareToIgnoreCase(String str)

ParametersHere is the detail of parameters:String str: the String to be compared.

Return value: Anegativeinteger,zero,orapositiveintegerasthethespecifiedStringisgreaterthan,equalto,orless than this String, ignoring case considerations.

Page 141: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

129

Example

public class Test{ public static void main(String args[]){ String str1 = “Strings are immutable”; String str2 = “Strings are immutable”; String str3 = “Integers are not immutable”;

int result = str1.compareToIgnoreCase( str2 ); System.out.println(result); result = str2.compareToIgnoreCase( str3 ); System.out.println(result); result = str3.compareToIgnoreCase( str1 ); System.out.println(result); }}This produces following result:010-10

6.7.4 int compareToIgnoreCase(String str) Compares two strings lexicographically, ignoring case differences.This method appends one String to the end of another. The method returns a String with the value of the String passed in to the method appended to the end of the String used to invoke this method.

SyntaxHere is the syntax of this method:

public String concat(String s)

ParametersHere is the detail of parameters:String str: the String that is concatenated to the end of this String.

Return value: A string that represents the concatenation of this object’s characters followed by the string argument’s characters.

Page 142: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

130

Example

public class Test{ public static void main(String args[]){ String s = “Strings are immutable”; s = s.concat(“ all the time”); System.out.println(s); }}This produces following result:

Strings are immutable all the time

6.7.5 String concat(String str)Stringconcat(Stringstr)concatenatesthespecifiedstringtotheendofthisstring.This method appends one String to the end of another. The method returns a String with the value of the String passed in to the method appended to the end of the String used to invoke this method.

SyntaxHere is the syntax of this method:

public String concat(String s)

ParametersHere is the detail of parameters:String str: the String that is concatenated to the end of this String.

Return value: A string that represents the concatenation of this object’s characters followed by the string argument’s characters.

Example

public class Test{ public static void main(String args[]){ String s = “Strings are immutable”; s = s.concat(“ all the time”); System.out.println(s); }}This produces following result:

Strings are immutable all the time

6.7.6 boolean contentEquals(StringBuffer sb) ReturnstrueifandonlyifthisStringrepresentsthesamesequenceofcharactersasthespecifiedStringBuffer.Thismethod returns true if andonly if thisString represents the same sequenceof characters as the specifiedStringBuffer.

Page 143: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

131

SyntaxHere is the syntax of this method:

public boolean contentEquals(StringBuffer sb)

ParametersHere is the detail of parameters:StringBuffer sb: the StringBuffer to compare to.

Return value: This method returns true if and only if this String represents the same sequence of characters as the specifiedStringBuffer,otherwisefalse.

Example

public class Test{ public static void main(String args[]){ String str1 = “Not immutable”; String str2 = “Strings are immutable”; StringBuffer str3 = new StringBuffer( “Not immutable”);

boolean result = str1.contentEquals( str3 ); System.out.println(result); result = str2.contentEquals( str3 ); System.out.println(result); }}This produces following result:truefalse

6.7.7 static String copyValueOf(char[] data) ReturnsaStringthatrepresentsthecharactersequenceinthearrayspecifiedThis method has two different forms:

public static String copyValueOf(char[] data):• Returns a String that represents the character sequence in the arrayspecified.public static String copyValueOf(char[] data, int offset, int count):• Returns a String that represents the charactersequenceinthearrayspecified.

SyntaxHere is the syntax of this method:

public static String copyValueOf(char[] data)orpublic static String copyValueOf(char[] data, int offset, int count)

ParametersHere is the detail of parameters:data: the character array.offset: initial offset of the subarray.count : length of the subarray.

Page 144: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

132

Return Value: This method returns a String that contains the characters of the character array.

Example

public class Test{ public static void main(String args[]){ char[] Str1 = “This is really not immutable!!”; String Str2;

Str2 = copyValueOf( Str1 ); System.out.println(“Returned String “ + Str2);

Str2 = copyValueOf( Str1, 5, 10 ); System.out.println(“Returned String “ + Str2);

}}

This produces following result:This is really not immutable!!is rea

6.7.8 static String copyValueOf(char[] data, int offset, int count)ReturnsaStringthatrepresentsthecharactersequenceinthearrayspecified.This method has two different forms:

public static String copyValueOf(char[] data):• Returns a String that represents the character sequence in the arrayspecified.public static String copyValueOf(char[] data, int offset, int count):• Returns a String that represents the charactersequenceinthearrayspecified.

SyntaxHere is the syntax of this method:

public static String copyValueOf(char[] data)orpublic static String copyValueOf(char[] data, int offset, int count)

ParametersHere is the detail of parameters:data: the character array.offset: initial offset of the subarray.count: length of the subarray.

Return value: This method returns a String that contains the characters of the character array.

Page 145: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

133

Example

public class Test{ public static void main(String args[]){ char[] Str1 = “This is really not immutable!!”; String Str2;

Str2 = copyValueOf( Str1 ); System.out.println(“Returned String “ + Str2);

Str2 = copyValueOf( Str1, 5, 10 ); System.out.println(“Returned String “ + Str2);

}}This produces following result:

This is really not immutable!!is rea

6.7.9 boolean endsWith(String suffix) Testsifthisstringendswiththespecifiedsuffix.Thismethodtestsifthisstringendswiththespecifiedsuffix.

SyntaxHere is the syntax of this method:

publicbooleanendsWith(Stringsuffix)

ParametersHere is the detail of parameters:suffix:thesuffix.

Return value: Thismethodreturnstrueifthecharactersequencerepresentedbytheargumentisasuffixofthecharacter sequence represented by this object; false otherwise. Note that the result will be true if the argument is the empty string or is equal to this String object as determined by the equals(Object) method.

Page 146: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

134

Example

public class Test{ public static void main(String args[]){ String Str = new String(“This is really not immutable!!”); boolean retVal;

retVal = Str.endsWith( “immutable!!” ); System.out.println(“Returned Value “ + retVal ); retVal = Str.endsWith( “immu” ); System.out.println(“Returned Value “ + retVal );

}}This produces following result:Returned Value trueReturned Value false

6.7.10 boolean equals(Object anObject)Comparesthisstringtothespecifiedobject.Thismethodcomparesthisstringtothespecifiedobject.Theresultistrueifandonlyiftheargumentisnotnulland is a String object that represents the same sequence of characters as this object.

SyntaxHere is the syntax of this method:

public boolean equals(Object anObject)

ParametersHere is the detail of parameters:anObject: the object to compare this String against.

Return value: true if the String are equal; false otherwise.

Page 147: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

135

Example

public class Test{ public static void main(String args[]){ String Str1 = new String(“This is really not immutable!!”); String Str2 = Str1; String Str3 = new String(“This is really not immutable!!”); boolean retVal;

retVal = Str1.equals( Str2 ); System.out.println(“Returned Value “ + retVal );

retVal = Str1.equals( Str3 ); System.out.println(“Returned Value “ + retVal ); }}This produces following result:

Returned Value trueReturned Value true

6.7.11 boolean equalsIgnoreCase(String anotherString)Compares this String to another String, ignoring case considerations.

DescriptionThis method compares this String to another String, ignoring case considerations. Two strings are considered equal ignoring case if they are of the same length, and corresponding characters in the two strings are equal ignoring case.

SyntaxHere is the syntax of this method:

public boolean equalsIgnoreCase(String anotherString)

ParametersHere is the detail of parameters:anotherString: the String to compare this String against

Return value: true if the argument is not null and the Strings are equal, ignoring case; false otherwise.

Page 148: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

136

Example

public class Test{ public static void main(String args[]){ String Str1 = new String(“This is really not immutable!!”); String Str2 = Str1; String Str3 = new String(“This is really not immutable!!”); String Str4 = new String(“This IS REALLY NOT IMMUTABLE!!”); boolean retVal;

retVal = Str1.equals( Str2 ); System.out.println(“Returned Value “ + retVal );

retVal = Str1.equals( Str3 ); System.out.println(“Returned Value “ + retVal );

retVal = Str1.equals( Str4 ); System.out.println(“Returned Value “ + retVal ); }}This produces following result:

Returned Value trueReturned Value trueReturned Value true

6.7.12 byte getBytes() Encodes this String into a sequence of bytes using the platform’s default charset, storing the result into a new byte array.

6.7.13 byte[] getBytes(String charsetNameEncodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.

DescriptionThis method has following two forms:

getBytes(String charsetName): • Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.getBytes():• Encodes this String into a sequence of bytes using the platform’s default charset, storing the result into a new byte array.

SyntaxHere is the syntax of this method:public byte[] getBytes(String charsetName) throws UnsupportedEncodingExceptionorpublic byte[] getBytes()

ParametersHere is the detail of parameters:charsetName: The name of a supported charset.

Page 149: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

137

Return value: The resultant byte arrayExample

import java.io.*;

public class Test{ public static void main(String args[]){ String Str1 = new String(“Welcome to Tutorialspoint.com”);

try{ byte[] Str2 = Str1.getBytes(); System.out.println(“Returned Value “ + Str2 );

Str2 = Str1.getBytes( “UTF-8” ); System.out.println(“Returned Value “ + Str2 );

Str2 = Str1.getBytes( “ISO-8859-1” ); System.out.println(“Returned Value “ + Str2 ); }catch( UnsupportedEncodingException e){ System.out.println(“Unsupported character set”); } }}This produces following result:

Returned Value [B@192d342Returned Value [B@15ff48bReturned Value [B@1b90b39

6.7.14 void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)Copies characters from this string into the destination character array.This method copies characters from this string into the destination character array.

SyntaxHere is the syntax of this method:

public void getChars(int srcBegin,int srcEnd,char[] dst, int dstBegin)

ParametersHere is the detail of parameters:srcBegin:indexofthefirstcharacterinthestringtocopy.srcEnd: index after the last character in the string to copy.dst: the destination array.dstBegin: the start offset in the destination array.

Return value: It does not return any value but throws IndexOutOfBoundsException.

Page 150: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

138

Example

import java.io.*;

public class Test{ public static void main(String args[]){ String Str1 = new String(“Welcome to Tutorialspoint.com”); char[] Str2 = new char[7];

try{ Str1.getChars(2, 9, Str2, 0); System.out.print(“Copied Value “ ); System.out.println(Str2 );

}catch( Exception ex){ System.out.println(“Raised exception...”); } }}This produces following result:

Copied Value lcome t

6.7.15 int hashCode()Returns a hash code for this string.

DescriptionThis method returns a hash code for this string. The hash code for a String object is computed as:

s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]

Using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.)

SyntaxHere is the syntax of this method:

public int hashCode()

ParametersHere is the detail of parameters:NA

Return value: It returns a hash code value for this object.

Page 151: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

139

Example

import java.io.*;

public class Test{ public static void main(String args[]){ String Str = new String(“Welcome to Tutorialspoint.com”); System.out.println(“Hashcode for Str :” + Str.hashCode() ); }}This produces following result:Hashcode for Str :1186874997

6.7.16 int indexOf(int ch) Returnstheindexwithinthisstringofthefirstoccurrenceofthespecifiedcharacter.This method has following different variants:

public int indexOf(int ch):• Returnstheindexwithinthisstringofthefirstoccurrenceofthespecifiedcharacteror -1 if the character does not occur.public int indexOf(int ch, int fromIndex): • Returnstheindexwithinthisstringofthefirstoccurrenceofthespecifiedcharacter,startingthesearchatthespecifiedindexor-1ifthecharacterdoesnotoccur.int indexOf(String str):• Returnstheindexwithinthisstringofthefirstoccurrenceofthespecifiedsubstring.If it does not occur as a substring, -1 is returned.int indexOf(String str, int fromIndex):• Returns the indexwithin this stringof thefirstoccurrenceof thespecifiedsubstring,startingatthespecifiedindex.Ifitdoesnotoccur,-1isreturned.

SyntaxHere is the syntax of this method:

public int indexOf(int ch )orpublic int indexOf(int ch, int fromIndex)orint indexOf(String str)orint indexOf(String str, int fromIndex)

ParametersHere is the detail of parameters:ch: a character.fromIndex: the index to start the search from.str: A string.

Return value: See the description.

Page 152: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

140

Example

import java.io.*;

public class Test{ public static void main(String args[]){ String Str = new String(“Welcome to Tutorialspoint.com”); String SubStr1 = new String(“Tutorials” ); String SubStr2 = new String(“Sutorials” );

System.out.print(“Found Index :” ); System.out.println(Str.indexOf( ‘o’ )); System.out.print(“Found Index :” ); System.out.println(Str.indexOf( ‘o’, 5 )); System.out.print(“Found Index :” ); System.out.println( Str.indexOf( SubStr1 )); System.out.print(“Found Index :” ); System.out.println( Str.indexOf( SubStr1, 15 )); System.out.print(“Found Index :” ); System.out.println(Str.indexOf( SubStr2 )); }}This produces following result:Found Index :4Found Index :9Found Index :11Found Index :-1Found Index :-1

6.7.17 int indexOf(int ch, int fromIndex) Returns the indexwithin this stringof thefirstoccurrenceof the specifiedcharacter, starting the searchat thespecifiedindex.

DescriptionThis method has following different variants:

public int indexOf(int ch):• Returnstheindexwithinthisstringofthefirstoccurrenceofthespecifiedcharacteror -1 if the character does not occur.public int indexOf(int ch, int fromIndex):• Returnstheindexwithinthisstringofthefirstoccurrenceofthespecifiedcharacter,startingthesearchatthespecifiedindexor-1ifthecharacterdoesnotoccur.int indexOf(String str):• Returnstheindexwithinthisstringofthefirstoccurrenceofthespecifiedsubstring.If it does not occur as a substring, -1 is returned.int indexOf(String str, int fromIndex): • Returns the indexwithin this stringof thefirstoccurrenceof thespecifiedsubstring,startingatthespecifiedindex.Ifitdoesnotoccur,-1isreturned.

SyntaxHere is the syntax of this method:

Page 153: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

141

public int indexOf(int ch )orpublic int indexOf(int ch, int fromIndex)orint indexOf(String str)orint indexOf(String str, int fromIndex)

ParametersHere is the detail of parameters:ch: a character.fromIndex: the index to start the search from.str: A string.

Return value: See the description.

Example

import java.io.*;public class Test{ public static void main(String args[]){ String Str = new String(“Welcome to Tutorialspoint.com”); String SubStr1 = new String(“Tutorials” ); String SubStr2 = new String(“Sutorials” ); System.out.print(“Found Index :” ); System.out.println(Str.indexOf( ‘o’ )); System.out.print(“Found Index :” ); System.out.println(Str.indexOf( ‘o’, 5 )); System.out.print(“Found Index :” ); System.out.println( Str.indexOf( SubStr1 )); System.out.print(“Found Index :” ); System.out.println( Str.indexOf( SubStr1, 15 )); System.out.print(“Found Index :” ); System.out.println(Str.indexOf( SubStr2 )); }}This produces following result:

Found Index :4Found Index :9Found Index :11Found Index :-1Found Index :-1

6.7.18 int indexOf(String str)Returnstheindexwithinthisstringofthefirstoccurrenceofthespecifiedsubstring.

DescriptionThis method has following different variants:

public int indexOf(int ch):• Returnstheindexwithinthisstringofthefirstoccurrenceofthespecifiedcharacteror -1 if the character does not occur.public int indexOf(int ch, int fromIndex):• Returnstheindexwithinthisstringofthefirstoccurrenceofthespecifiedcharacter,startingthesearchatthespecifiedindexor-1ifthecharacterdoesnotoccur.

Page 154: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

142

int indexOf(String str):• Returnstheindexwithinthisstringofthefirstoccurrenceofthespecifiedsubstring.If it does not occur as a substring, -1 is returned.int indexOf(String str, int fromIndex):• Returns the indexwithin this stringof thefirstoccurrenceof thespecifiedsubstring,startingatthespecifiedindex.Ifitdoesnotoccur,-1isreturned.

SyntaxHere is the syntax of this method:

public int indexOf(int ch )orpublic int indexOf(int ch, int fromIndex)orint indexOf(String str)orint indexOf(String str, int fromIndex)

ParametersHere is the detail of parameters:ch: a character.fromIndex: the index to start the search from.str: A string.

Return value See the description.

Example

import java.io.*;

public class Test{ public static void main(String args[]){ String Str = new String(“Welcome to Tutorialspoint.com”); String SubStr1 = new String(“Tutorials” ); String SubStr2 = new String(“Sutorials” );

System.out.print(“Found Index :” ); System.out.println(Str.indexOf( ‘o’ )); System.out.print(“Found Index :” ); System.out.println(Str.indexOf( ‘o’, 5 )); System.out.print(“Found Index :” ); System.out.println( Str.indexOf( SubStr1 )); System.out.print(“Found Index :” ); System.out.println( Str.indexOf( SubStr1, 15 )); System.out.print(“Found Index :” ); System.out.println(Str.indexOf( SubStr2 )); }}This produces following result:

Found Index :4Found Index :9Found Index :11Found Index :-1Found Index :-1

Page 155: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

143

6.7.19 int indexOf(String str, int fromIndex)Returns the indexwithin this string of thefirst occurrence of the specified substring, starting at the specifiedindex.This method has following different variants:

public int indexOf(int ch):• Returnstheindexwithinthisstringofthefirstoccurrenceofthespecifiedcharacteror -1 if the character does not occur.public int indexOf(int ch, int fromIndex):• Returnstheindexwithinthisstringofthefirstoccurrenceofthespecifiedcharacter,startingthesearchatthespecifiedindexor-1ifthecharacterdoesnotoccur.int indexOf(String str):• Returnstheindexwithinthisstringofthefirstoccurrenceofthespecifiedsubstring.If it does not occur as a substring, -1 is returned.int indexOf(String str, int fromIndex):• Returns the indexwithin this stringof thefirstoccurrenceof thespecifiedsubstring,startingatthespecifiedindex.Ifitdoesnotoccur,-1isreturned.

SyntaxHere is the syntax of this method:

public int indexOf(int ch )orpublic int indexOf(int ch, int fromIndex)orint indexOf(String str)orint indexOf(String str, int fromIndex)

ParametersHere is the detail of parameters:ch: a character.fromIndex: the index to start the search from.str: A string.

Return value See the description.

Page 156: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

144

Example

import java.io.*;

public class Test{ public static void main(String args[]){ String Str = new String(“Welcome to Tutorialspoint.com”); String SubStr1 = new String(“Tutorials” ); String SubStr2 = new String(“Sutorials” );

System.out.print(“Found Index :” ); System.out.println(Str.indexOf( ‘o’ )); System.out.print(“Found Index :” ); System.out.println(Str.indexOf( ‘o’, 5 )); System.out.print(“Found Index :” ); System.out.println( Str.indexOf( SubStr1 )); System.out.print(“Found Index :” ); System.out.println( Str.indexOf( SubStr1, 15 )); System.out.print(“Found Index :” ); System.out.println(Str.indexOf( SubStr2 )); }}This produces following result:

Found Index :4Found Index :9Found Index :11Found Index :-1Found Index :-1

6.7.20 String intern()Returns a canonical representation for the string object.

DescriptionThis method returns a canonical representation for the string object. It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.

SyntaxHere is the syntax of this method:

public String intern()

ParametersHere is the detail of parameters:

NA•

Return value Returns a canonical representation for the string object.

Page 157: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

145

Example:

import java.io.*;

public class Test{ public static void main(String args[]){ String Str1 = new String(“Welcome to Tutorialspoint.com”); String Str2 = new String(“WELCOME TO SUTORIALSPOINT.COM”);

System.out.print(“Canonical representation:” ); System.out.println(Str1.intern());

System.out.print(“Canonical representation:” ); System.out.println(Str2.intern()); }}This produces following result:

Canonical representation: Welcome to Tutorialspoint.comCanonical representation: WELCOME TO SUTORIALSPOINT.COM

There are some other string functions which are mentioned in the table given below:

String intern()1. Returns a canonical representation for the string object.

int lastIndexOf(int ch) 2. Returnstheindexwithinthisstringofthelastoccurrenceofthespecifiedcharacter.

int lastIndexOf(int ch, int fromIndex) 3. Returnstheindexwithinthisstringofthelastoccurrenceofthespecifiedcharacter,searching backwardstartingatthespecifiedindex.

int lastIndexOf(String str)4. Returnstheindexwithinthisstringoftherightmostoccurrenceofthespecifiedsubstring.

int lastIndexOf(String str, int fromIndex) 5. Returnstheindexwithinthisstringofthelastoccurrenceofthespecifiedsubstring,searching backwardstartingatthespecifiedindex.

int length() 6. Returns the length of this string.

boolean matches(String regex) 7. Tells whether or not this string matches the given regular expression.

boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) 8. Tests if two string regions are equal.

boolean regionMatches(int toffset, String other, int ooffset, int len)9. Tests if two string regions are equal.

String replace(char oldChar, char newChar)10. Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

String replaceAll(String regex, String replacement)11. Replaces each substring of this string that matches the given regular expression with the given replacement.

String replaceFirst(String regex, String replacement) 12. Replacesthefirstsubstringofthisstringthatmatchesthegivenregularexpressionwiththegiven replacement.

Page 158: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

146

String[] split(String regex) 13. Splits this string around matches of the given regular expression.

String[] split(String regex, int limit) 14. Splits this string around matches of the given regular expression.

boolean startsWith(String prefix)15. Testsifthisstringstartswiththespecifiedprefix.

boolean startsWith(String prefix, int toffset)16. Testsifthisstringstartswiththespecifiedprefixbeginningaspecifiedindex.

CharSequence subSequence(int beginIndex, int endIndex)17. Returns a new character sequence that is a subsequence of this sequence.

String substring(int beginIndex)18. Returns a new string that is a substring of this string.

String substring(int beginIndex, int endIndex)19. Returns a new string that is a substring of this string.

char[] toCharArray() 20. Converts this string to a new character array.

String toLowerCase()21. Converts all of the characters in this String to lower case using the rules of the default locale.

tring toLowerCase(Locale locale)22. Converts all of the characters in this String to lower case using the rules of the given Locale.

String toString()23. This object (which is already a string!) is itself returned.

String toUpperCase() 24. Converts all of the characters in this String to upper case using the rules of the default locale.

String toUpperCase(Locale locale) 25. Converts all of the characters in this String to upper case using the rules of the given Locale.

String trim() 26. Returns a copy of the string, with leading and trailing whitespace omitted.

static String valueOf(primitive data type x) 27. Returns the string representation of the passed data type argument.

Page 159: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

147

Summary Normally, when we work with characters, we use primitive data types char.•However in development we come across situations were we need to use objects instead of primitive data •types.In-order to achieve this Java provides wrapper classe Character for primitive data type char.•The Character class offers a number of useful class (i.e., static) methods for manipulating characters. •isLetterdetermineswhetherthespecifiedcharvalueisaletter.•isDigit()determineswhetherthespecifiedcharvalueisadigit.•isWhitespace()determineswhetherthespecifiedcharvalueiswhitespace.•isUpperCasedetermineswhetherthespecifiedcharvalueisuppercase.•isLowerCase()determineswhetherthespecifiedcharvalueislowercase.•toUpperCase()returnstheuppercaseformofthespecifiedcharvalue.•toLowerCase()returnsthelowercaseformofthespecifiedcharvalue.•toString()returnsaStringobjectrepresentingthespecifiedcharactervaluethatis,aone-characterstring.•Methods used to obtain information about an object are known as accessor methods. •One access or method that you can use with strings is the length() method, which returns the number of characters •contained in the string object.The String class has an equivalent class method, format(), that returns a String object rather than a PrintStream •object.CharcharAt(intindex)returnsthecharacteratthespecifiedindex.•Stringconcat(Stringstr)concatenatesthespecifiedstringtotheendofthisstring.•Returns true if and only if this String represents the same sequence of characters as the specified •StringBuffer.

References Ivor Horton’s, 2009. • Beginning Java 2 Jdk (5Th Ed.). Wiley-India David Flanagan, 2005. • Java in a nutshell. O’Reilly Media, Inc.Ivor Horton, 2003. • Beginning Java 2 SDK 1.4 edition. Wirox

Recommended Reading Duane J. Jarc, 2000. • Java Programming & Projects (jdk 5 Edition). Wiley-India. Dr. G.T.Thampi, 2009• . Object Oriented Programming In Java (With Cd). Wiley-India. R. Nageswara Rao/kogent Solutions, 2008. • Core Java: An Integrated Approach. Dreamtech Press.

Page 160: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

148

Self AssessmentJava provides wrapper classes character for ________data type char.1.

primitivea. non- primitiveb. ancientc. modernd.

The Character class offers a number of useful class (i.e., static) methods for ______________characters. 2. controllinga. operatingb. manipulatingc. directing d.

If you pass a primitive char into a method that expects an object, the compiler automatically converts the char 3. to a Character for you, this feature is called _______.

autoboxinga. wrapping b. adding c. mixing d.

How do you represent newline coding language?4. nla. /nlb. \nc. \nld.

___________determineswhetherthespecifiedcharvalueisaletter.5. Lettera. isLetterb. LetterISc. Letteris d.

______________determineswhetherthespecifiedcharvalueisadigit.6. Digit()isa. isDigit()ISb. isDigit()c. Digit()d.

isWhitespace()determineswhetherthespecifiedcharvalueis________.7. white colour a. white space b. white wordc. white image d.

Page 161: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

149

isUpperCasedetermineswhetherthespecifiedcharvalueis_____________.8. upwarda. uppercaseb. upperlevelc. upperstaged.

___________determineswhetherthespecifiedcharvalueislowercase.9. LowerCase()a. LowerCase()isb. isLowerCasec. isLowerCase()d.

Which of the following sentences is true? 10. toLowerCase()returnsthelowerlevelformofthespecifiedcharvalue.a. toLowerCase()returnsthelowvalueformofthespecifiedcharvalue.b. toLowerCase()returnsthelowerstageformofthespecifiedcharvalue.c. toLowerCase()returnsthelowercaseformofthespecifiedcharvalue.d.

Page 162: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

150

Chapter VII

Arrays and Files

Aim

The aim of this chapter is to:

explain the concept of Array •

draw the declaration format of Array•

elucidate method of creating Arrays •

explain processing of Arrays•

Objectives

The objectives of this chapter are to:

explain the making of nested loop in programming •

elaborate passing arrays to methods •

discuss returning an arrays from methods •

explain an classes in arrays•

Learning outcome

At the end of this chapter, the students will be able to:

understandfilestructuresinJava•

explain methods for reading characters from console •

discuss method to read string from arrays •

Page 163: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

151

7.1 Introduction to ArrayJavaprovidesadatastructureandthearraywhichstoreafixed-sizesequentialcollectionofelementsofthe•same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of •variables of the same type.Instead of declaring individual variables, such as number0, number1, ..., and number99, declare one array variable •such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables.This tutorial introduces how to declare array variables, create arrays, and process arrays using indexed •variables.

7.2 Declaring Array VariablesTo use an array in a program, one must declare a variable to reference the array, and specify the type of array •the variable can reference. Here is the syntax for declaring an array variable:•

dataType[] arrayRefVar; // preferred way.ordataType arrayRefVar[]; // works but not preferred way.

Note: The style dataType[] arrayRefVar is preferred. The style dataType arrayRefVar[] comes from the C/C++ language and was adopted in Java to accommodate C/C++ programmers.

ExampleThe following code snippets are examples of this syntax:

double[] myList; // preferred way.ordouble myList[]; // works but not preferred way.

7.3 Creating ArraysYou can create an array by using the new operator with the following syntax:•

arrayRefVar = new dataType[arraySize];

The above statement does two things:•It creates an array using new dataType[arraySize]; �It assigns the reference of the newly created array to the variable arrayRefVar. �

Declaring an array variable, creating an array and assigning the reference of the array to the variable can be •combined in one statement, as shown below:

dataType[] arrayRefVar = new dataType[arraySize];

Alternatively you can create arrays as follows:•

dataType[] arrayRefVar = {value0, value1, ..., valuek};

Page 164: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

152

The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to •arrayRefVar.length-1.

ExampleFollowing statement declares an array variable, myList, creates an array of 10 elements of double type, and assigns its reference to myList.:double[] myList = new double[10];Following picture represents array myList. Here myList holds ten double values and the indices are from 0 to 9.

5.64.53.313.24.0

34.33

34.0

45.4599.993

11123

referencemyList

Array reference variable

Array element at index 5

Element value

myList [0]myList [1]myList [2]myList [3]myList [4]myList [5]myList [6]myList [7]myList [8]myList [9]

Fig. 7.1 Array myList

7.4 Processing ArraysWhen processing array elements, we often use either for loop or foreach loop because all of the elements in an array are of the same type and the size of the array is known.

Page 165: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

153

ExampleHere is a complete example of showing how to create, initialize and process arrays:

public class TestArray { public static void main(String[] args) { double[] myList = {1.9, 2.9, 3.4, 3.5};

// Print all the array elements for (int i = 0; i < myList.length; i++) { System.out.println(myList[i] + “ “); } // Summing all elements double total = 0; for (int i = 0; i < myList.length; i++) { total += myList[i]; } System.out.println(“Total is “ + total); // Finding the largest element double max = myList[0]; for (int i = 1; i < myList.length; i++) {if(myList[i]>max)max=myList[i]; } System.out.println(“Max is “ + max); }}This would produce following result:1.92.93.43.5Total is 11.7Max is 3.5

7.5 foreach LoopsJDK 1.5 introduced a new for loop, known as foreach loop or enhanced for loop, which enables you to traverse the complete array sequentially without using an index variable.

Page 166: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

154

ExampleThe following code displays all the elements in the array myList:

public class TestArray { public static void main(String[] args) { double[] myList = {1.9, 2.9, 3.4, 3.5}; // Print all the array elements for (double element: myList) { System.out.println(element); } }}This would produce following result:1.92.93.43.5

7.6 Passing Arrays to MethodsJust as you can pass primitive type values to methods, you can also pass arrays to methods. For example, the •following method displays the elements in an int array:

public static void printArray(int[] array) { for (int i = 0; i < array.length; i++) { System.out.print(array[i] + “ “); }}

You can invoke it by passing an array. For example, the following statement invokes the printArray method to •display 3, 1, 2, 6, 4, and 2:

printArray(new int[]{3, 1, 2, 6, 4, 2});

Returning an Array from a methodA method may also return an array. For example, the method shown below returns an array that is the reversal of another array:

public static int[] reverse(int[] list) { int[] result = new int[list.length];

for (int i = 0; i = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; } result result;}

Page 167: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

155

7.7 Arrays ClassThe java.util.Arrays class contains various static methods for sorting and searching arrays, comparing arrays and fillingarrayelements.Thesemethodsareoverloadedforallprimitivetypes.

Methods with Description

public static int binarySearch(Object[] a, Object key)SearchesthespecifiedarrayofObject(Byte,Int,doubleetc)forthespecifiedvalueusingthebinary search algorithm. The array must be sorted prior to making this call. This returns index of the search key, if it is contained in the list; otherwise, (insertion point + 1).

public static boolean equals(long[] a, long[] a2)Returnstrueifthetwospecifiedarraysoflongsareequaltooneanother.Twoarraysareconsideredequal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. This returns true if the two arrays are equal. Same method could be used by all other premitive data types ( Byte, short, Int etc.)

public static void fill(int[] a, int val)Assignsthespecifiedintvaluetoeachelementofthespecifiedarrayofints.Samemethodcouldbe used by all other premitive data types ( Byte, short, Int etc.)

public static void sort(Object[] a)Sortsthespecifiedarrayofobjectsintoascendingorder,accordingtothenaturalorderingofitselements. Same method could be used by all other premitive data types ( Byte, short, Int etc.)

Table 7.1 Array Class

7.8 Streams, Files and I/OThe java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java. •All these streams represent an input source and an output destination.The stream in the java.io package supports many data such as primitives, Object, localised characters etc.•Astreamcanbedefinedasasequenceofdata.TheInputStreamisusedtoreaddatafromasourceandthe•OutputStream is used for writing data to a destination.Javadoesprovidestrong,flexiblesupportforI/Oasitrelatestofilesandnetworksbutthistutorialcoversvery•basic functionlity related to streams and I/O.

7.9 Reading Characters from ConsoleTo read a character from a BufferedReader, we would read( ) method whose sytax is as follows:•

int read( ) throws IOException

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”:

Page 168: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

156

// Use a BufferedReader to read characters from the console.

import java.io.*;

class BRRead { public static void main(String args[]) throws IOException { char c; // Create a BufferedReader using System.in BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println(“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.123abcq123abcq

7.10 Reading Strings from ConsoleTo read a string from the keyboard, use the version of readLine( ) that is a member of the BufferedReader •class. Its general form is shown here:•

String readLine( ) throws IOException

The following program demonstrates BufferedReader and the readLine( ) method. •The program reads and displays lines of text until you enter the word “end”:•

Page 169: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

157

// Read a string from console using a BufferedReader.import java.io.*;class BRReadLines { public static 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 ‘end’ to quit.”); do { str = br.readLine(); System.out.println(str); } while(!str.equals(“end”)); }}Here is a sample run:

Enter lines of text.Enter ‘end’ to quit.This is line oneThis is line oneThis is line twoThis is line twoendend

Writing Console outputConsole output is most easily accomplished with print( ) and println().•ThesemethodsaredefinedbytheclassPrintStreamwhichisthetypeoftheobjectreferencedbySystem.out.•Even though System.out is a byte stream, using it for simple program output is still acceptable.•Because PrintStream is an output stream derived from OutputStream, it also implements the low-level method •write( ). Thus, write( ) can be used to write to the console. Thesimplestformofwrite()definedbyPrintStreamisshownhere:•

void write(int byteval)

Thismethodwritestothestreamthebytespecifiedbybyteval.•Although byteval is declared as an integer, only the low-order eight bits are written.•

Page 170: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

158

ExampleHere is a short example that uses write( ) to output the character “A” followed by a newline to the screen:

import java.io.*;

// Demonstrate System.out.write().class WriteDemo { public static void main(String args[]) { int b; b = ‘A’; System.out.write(b); System.out.write(‘\n’); }}This would produce simply ‘A’ character on the output screen.A

Note: You will not often use write( ) to perform console output because print( ) and println( ) are substantially easier to use.

7.11 Reading and Writing FilesAsdescribedearlier,Astreamcanbedefinedasasequenceofdata.•The InputStream is used to read data from a source and the OutputStream is used for writing data to a •destination.Here is a hierarchy of classes to deal with Input and Output streams.•

Object

InputStream

Sequence Input Stream

Pushback input Stream

DatainputStream Buffered input Stream

Buffer Output Stream

Print Stream Data Output Stream

Filter Input Stream

String Buffer Input Stream

File Input Stream

OutputStream

Byte Array OutputStream

Filter Output Stream Filter Output Stream

Fig. 7.2 Reading and writing files

Page 171: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

159

The two important streams are FileInputStream and FileOutputStream which would be discussed in this •tutorial:

7.12 FileInputStreamThisstreamisusedforreadingdatafromthefiles.Objectscanbecreatedusingthekeywordnewandthereare•several types of constructors available.Followingconstructortakesafilenameasastringtocreateaninputstreamobjecttoreadthefile.:•

InputStream f = new FileInputStream(“C:/java/hello”);

Followingconstructortakesafileobjecttocreateaninputstreamobjecttoreadthefile.•FirstwecreateafileobjectusingFile()methodasfollows:•

File f = new File(“C:/java/hello”);InputStream f = new FileInputStream(f);

Once you have InputStream object in hand then there is a list of helper methods which can be used to read to •stream or to do other operations on the stream.

Methods with description

public void close() throws IOException{}Thismethodclosesthefileoutputstream.Releasesanysystemresourcesassociatedwiththefile.Throwsan IOException.

protected void finalize()throws IOException {}Thismethodcleansuptheconnectiontothefile.Ensuresthattheclosemethodofthisfileoutputstreamis called when there are no more references to this stream. Throws an IOException.

public int read(int r)throws IOException{}ThismethodreadsthespecifiedbyteofdatafromtheInputStream.Returnsanint.Returnsthenextbyteofdataand-1willbereturnedifit’sendoffile.

public int read(byte[] r) throws IOException{}This method reads r.length bytes from the input stream into an array. Returns the total number of bytes read.Ifendoffile-1willbereturned.

public int available() throws IOException{}Givesthenumberofbytesthatcanbereadfromthisfileinputstream.Returnsanint.

Table 7.2 Methods with Description of FileInputStream

There are other important input streams available, for more detail you can refer to the following links:•ByteArrayInputStream �DataInputStream �

Page 172: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

160

7.13 ByteArrayInputStreamThe ByteArrayInputStream class allows a buffer in the memory to be used as an InputStream. •The input source is a byte array. •There are following forms of constructors to create ByteArrayInputStream objects•Takes a byte array as the parameter•

ByteArrayInputStream bArray = new ByteArrayInputStream(byte [] a);

Anotherformtakesanarrayofbytes,andtwoints,whereoffisthefirstbytetobereadandlenisthenumber•of bytes to be read.

ByteArrayInputStream bArray = new ByteArrayInputStream(byte []a, int off, int len)

Once you have ByteArrayInputStream object in hand then there is a list of helper methods which can be used •to read the stream or to do other operations on the stream.

Methods with description

public int read()This method reads the next byte of data from the InputStream. Returns an int as the next byte of data. Ifitisendoffilethenitreturns-1.

public int read(byte[] r, int off, int len)This method reads upto len number of bytes starting from off from the input stream into an array. Returns thetotalnumberofbytesread.Ifendoffile-1willbereturned.

public int available() Givesthenumberofbytesthatcanbereadfromthisfileinputstream.Returnsanintthatgivesthenumber of bytes to be read.

public void mark(int read)This sets the current marked position in the stream. The parameter gives the maximum limit of bytes that can be read before the marked position becomes invalid.

public long skip(long n)Skips n number of bytes from the stream. This returns the actual number of bytes skipped.

Table 7.3 ByteArrayInputStream

Page 173: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

161

ExampleFollowing is the example to demonstrate ByteArrayInputStream and ByteArrayOutputStream

7.14 DataInputStreamThe DataInputStream is used in the context of DataOutputStream and can be used to read primitives.•Following is the constructor to create an InputStream:•

InputStream in = DataInputStream(InputStream in);

Once you have DataInputStream object in hand then there is a list of helper methods which can be used to read •the stream or to do other operations on the stream.

Methods with Descriptionpublic final int read(byte[] r, int off, int len)throws IOExceptionReads up to len bytes of data from the input stream into an array of bytes. Returns the total number of bytesreadintothebufferotherwise-1ifitisendoffile.

Public final int read(byte [] b)throws IOExceptionReads some bytes from the inputstream an stores in to the byte array. Returns the total number of bytes readintothebufferotherwise-1ifitisendoffile.

public final Boolean readBooolean()throws IOException,publicfinalbytereadByte()throwsIOException,publicfinalshortreadShort()throwsIOExceptionpublicfinalIntreadInt()throwsIOExceptionThese methods will read the bytes from the contained InputStream. Returns the next two bytes of theInputStreamasthespecificprimitivetype.

public String readLine() throws IOExceptionReads the next line of text from the input stream. It reads successive bytes, converting each byte separately intoacharacter,untilitencountersalineterminatororendoffile;thecharactersreadarethenreturnedas a String.

Table 7.4 DataInputStream

Page 174: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

162

ExampleFollowing is the example to demonstrate DataInputStream and DataInputStream. This example reads 5 lines given inafiletest.txtandconvertthoselinesintocapitallettersandfinallycopiesthemintoanotherfiletest1.txt.

import java.io.*;

public class Test{ public static void main(String args[])throws IOException{

DataInputStream d = new DataInputStream(new FileInputStream(“test.txt”));

DataOutputStream out = new DataOutputStream(new FileOutputStream(“test1.txt”));

String count; while((count = d.readLine()) != null){ String u = count.toUpperCase(); System.out.println(u); out.writeBytes(u + “ ,”); } d.close(); out.close(); }}Here is the sample run of the above program:

THIS IS TEST 1,THIS IS TEST 2,THIS IS TEST 3,THIS IS TEST 4 ,THIS IS TEST 5 ,

7.15 File Navigation and I/OThere are several other classes that we would be going through to get to know the basics of File Navigation •and I/O.

File Class �FileReader Class �FileWriter Class �

7.16 Directories in JavaCreating directoriesThere are two useful File utility methods which can be used to create directories:

The • mkdir( ) method creates a directory, returning true on success and false on failure. Failure indicates that thepathspecifiedintheFileobjectalreadyexists,orthatthedirectorycannotbecreatedbecausetheentirepath does not exist yet.The • mkdirs() method creates both a directory and all the parents of the directory.

Page 175: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

163

Following example creates “/tmp/user/java/bin” directory:

import java.io.File;

class CreateDir { public static void main(String args[]) { String dirname = “/tmp/user/java/bin”; File d = new File(dirname); // Create directory now. d.mkdirs(); }}Compile and execute above code to create “/tmp/user/java/bin”.

Note: Java automatically takes care of path separators on UNIX and Windows as per conventions. If you use a forward slash (/) on a Windows version of Java, the path will still resolve correctly.

Reading directoriesAdirectoryisaFilethatcontainsalistofotherfilesanddirectories.• When you create a File object and it is a directory, the isDirectory( ) method will return true.•Youcancalllist()onthatobjecttoextractthelistofotherfilesanddirectoriesinside.•The program shown here illustrates how to use list( ) to examine the contents of a directory:•

Page 176: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

164

import java.io.File;

class DirList { public static void main(String args[]) { String dirname = “/java”; File f1 = new File(dirname); if (f1.isDirectory()) { System.out.println( “Directory of “ + dirname); String s[] = f1.list(); for (int i=0; i < s.length; i++) { File f = new File(dirname + “/” + s[i]); if (f.isDirectory()) { System.out.println(s[i] + “ is a directory”); } else {System.out.println(s[i]+“isafile”); } } } else { System.out.println(dirname + “ is not a directory”); } }}This would produce following result:

Directory of /mysqlbin is a directorylib is a directorydemo is a directorytest.txtisafileREADMEisafileindex.htmlisafileinclude is a directory

Page 177: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

165

Summary Javaprovidesadatastructure,thearray,whichstoresafixed-sizesequentialcollectionofelementsofthesame•type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of •variables of the same type.Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one •array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables.The style dataType[] arrayRefVar is preferred. The style dataType arrayRefVar[] comes from the C/C++ language •and was adopted in Java to accommodate C/C++ programmers. When processing array elements, we often use either for loop or foreach loop because all of the elements in an •array are of the same type and the size of the array is known.JDK 1.5 introduced a new for loop, known as foreach loop or enhanced for loop, which enables you to traverse •the complete array sequentially without using an index variable.Just as one can pass primitive type values to methods, one can also pass arrays to methods. For example, the •following method displays the elements in an int array. You can invoke it by passing an array. For example, the following statement invokes the printArray method to •display 3, 1, 2, 6, 4, and 2. The java.util.Arrays class contains various static methods for sorting and searching arrays, comparing arrays, •andfillingarrayelements.Thesemethodsareoverloadedforallprimitivetypes.The java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java. •All these streams represent an input source and an output destination.The stream in the java.io package supports many data such as primitives, Object, localised characters etc.•Astreamcanbedefinedasasequenceofdata.TheInputStreamisusedtoreaddatafromasourceandthe•OutputStream is used for writing data to a destination.Each time that read( ) is called, it reads a character from the input stream and returns it as an integer value. •To read a string from the keyboard, use the version of readLine( ) that is a member of the BufferedReader •class. Console output is most easily accomplished with print( ) and println( ), described earlier.•ThesemethodsaredefinedbytheclassPrintStreamwhichisthetypeoftheobjectreferencedbySystem.out.•Even though System.out is a byte stream, using it for simple program output is still acceptable.•The InputStream is used to read data from a source and the OutputStream is used for writing data to a •destination.

ReferencesY. Daniel Liang, 2010• . Introduction to Java Programming. Prentice Hall. Cay S. Horstmann, 2009. • Java Concepts: Compatible with Java 5, 6 and 7. john Wiley and Sons. Buyya, 2009. • Object Oriented Prog With Java. Tata McGraw-Hill Education.

Recommended Reading Barry Burd, 2009. • Java For Dummies. Wiley-India. Balagurusamy, 2009. • Programming With Java 4E. Tata McGraw-Hill Education. Schildt, 2006. • Java: The Complete Reference. Tata McGraw-Hill Education.

Page 178: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

166

Self Assessment Java provides a data structure, the array, which stores a ___________sequential collection of elements of the 1. same type.

fixed-sizea. variable size b. changeable c. unchangeable d.

An array is used to _________a collection of data. 2. build-upa. storeb. addc. put-byd.

The array elements are accessed through the _______________.3. variable a. index b. data c. source d.

myList holds ten double values and the indices are from_________.4. 0 to 99a. 0 to 9b. 0 to 10c. 10 to 19d.

Just as one can pass primitive type values to methods, one can also pass arrays to____.5. methodsa. variable b. functionc. sub-routine d.

Which of the following sentences is true?6. A method may also return an array.a. A variable may also return an array.b. A function may also return an array.c. A program may also return an array.d.

The __________class contains various static methods for sorting and searching arrays, comparing arrays and 7. fillingarrayelements.

java.unit.Arraysa. java.untitle.Arraysb. java.util.Arraysc. java.until.Arraysd.

Page 179: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

167

The ____________package contains nearly every class you might ever need to perform input and output (I/O) 8. in Java.

java.oia. java.ipb. java.opc. java.iod.

Astreamcanbedefinedasa_______ofdata.9. runa. stringb. sequencec. orderd.

The InputStream is used to _______data from a source.10. writea. readb. printc. copyd.

Page 180: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

168

Application I

JavaScript, also known as ECMAScript is a prototype-based object-oriented scripting language that is dynamic, •weaklytypedandhasfirst-classfunctions.It is also considered a functional programming language like Scheme and OCaml because it has closures and •supports higher-order functions.JavaScript is an implementation of the ECMAScript language standard and is primarily used in the form of •client-side JavaScript, implemented as part of a web browser in order to provide enhanced user interfaces and dynamic websites. This enables programmatic access to computational objects within a host environment.•JavaScript’suseinapplicationsoutsidewebpagesforexampleinPDF-documents,site-specificbrowsersand•desktopwidgetsisalsosignificant.NewerandfasterJavascriptVMs,particularlyNode.jshavealsoincreasedthe popularity of Javascript for server-side web apps.JavaScriptusessyntaxinfluencedbythatofC.JavaScriptcopiesmanynamesandnamingconventionsfrom•Java, but the two languages are otherwise unrelated and have very different semantics. The key design principles within JavaScript are taken from the Self and Scheme programming languages.As of 2009, the latest version of the language is JavaScript 1.8.1. •It is a superset of ECMAScript (ECMA-262) Edition 3. •Extensions to the language, including partial E4X (ECMA-357) support and experimental features considered •for inclusion into future ECMAScript editions, are documented here.

Simple examplesA simple recursive function:

function factorial(n) { if (n === 0) { return 1; } return n * factorial(n - 1); }

A simple personalised greeting script:

var name = prompt("What is your name?");alert("Welcome "+name);

Anonymous function (or lambda) syntax:

function add (i, j) { var add_pri = function (x, y) { return x + y; }; return add_pri(i, j);}

Page 181: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

169

Closures:

function showclosure () { var inc = makeinc(1); inc(); // 1 inc(); // 2 inc(); // 3} function makeinc (initialValue) { var count = initialValue; return function () { return count++; };}

Variadic function demonstration. This will alert with 1 then 2 then 3. arguments is a special variable.

function unlimited_args () { for (var i = 0; i < arguments.length; i++) { alert(arguments[i]); }} unlimited_args(1, 2, 3);

More advanced exampleThis sample code showcases various JavaScript features.

/* Finds the lowest common multiple of two numbers */function LCMCalculator (x, y) { // constructor function var checkInt = function (x) { // inner function if (x % 1 !== 0) { throw new TypeError(x + " is not an integer"); // exception throwing } return x; }; this.a = checkInt(x) // ^ semicolons are optional (but beware since this may cause consecutive lines to be //erroneously treated as a single statement) this.b = checkInt(y);}// The prototype of object instances created by a constructor is // that constructor's "prototype" property.LCMCalculator.prototype = { // object literal constructor : LCMCalculator, // when reassigning a prototype, set the constructor property appropriately gcd : function () { // method that calculates the greatest common divisor // Euclidean algorithm: var a = Math.abs(this.a), b = Math.abs(this.b), t;

Page 182: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

170

if (a < b) { // swap variables t = b; b = a; a = t; } while (b !== 0) { t = b; b = a % b; a = t; }//Onlyneedtocalculategcdonce,so"redefine"thismethod.//(Actuallynotredefinition-it'sdefinedontheinstanceitself,//sothatthis.gcdreferstothis"redefinition"insteadofLCMCalculator.prototype.gcd.) // Also, 'gcd' == "gcd", this['gcd'] == this.gcd this['gcd'] = function () { return a; }; return a; }, "lcm" /* can use strings here */: function () {

// Variable names don't collide with object properties, e.g. |lcm| is not |this.lcm|. // not using |this.a * this.b| to avoid FP precision issues var lcm = this.a / this.gcd() * this.b; //Onlyneedtocalculatelcmonce,so"redefine"thismethod. this.lcm = function () { return lcm; }; return lcm; }, toString : function () { return "LCMCalculator: a = " + this.a + ", b = " + this.b; }}; //Note:Array'smap()andforEach()arepredefinedinJavaScript1.6.// They are currently not available in the JScript engine built into// Microsoft Internet Explorer, but are implemented in Firefox, Chrome, etc. // They are used here to demonstrate JavaScript's inherent functional nature. [[25, 55],[21, 56],[22, 58],[28, 56]].map(function (pair) { // array literal + mapping function return new LCMCalculator(pair[0], pair[1]);}).sort(function (a, b) { // sort with this comparative function return a.lcm() - b.lcm();}).forEach(function (obj) { /* Note: print() is a JS builtin function available in Mozilla's js CLI;

Page 183: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

171

* It is functionally equivalent to Java's System.out.println(). * Within a web browser, print() is a very different function * (opens the "Print Page" dialog), * so use something like document.write() or alert() instead. */ // print (obj + ", gcd = " + obj.gcd() + ", lcm = " + obj.lcm()); // alert (obj + ", gcd = " + obj.gcd() + ", lcm = " + obj.lcm());document.write(obj+",gcd="+obj.gcd()+",lcm="+obj.lcm()+"<br>");});

The following output should be displayed in the browser window.

LCMCalculator: a = 28, b = 56, gcd = 28, lcm = 56LCMCalculator: a = 21, b = 56, gcd = 7, lcm = 168LCMCalculator: a = 25, b = 55, gcd = 5, lcm = 275LCMCalculator: a = 22, b = 58, gcd = 2, lcm = 638

QuestionsWhich language is latest in Java?1. Answer:The latest version of the language is JavaScript 1.8.1.

What is alias of JavaScript?2. Answer:JavaScript, also known as ECMAScript.

What is ECMAScript? 3. Answer:ECMAScript is a prototype-based object-oriented scripting language that is dynamic, weakly typed and has first-classfunctions.ItisalsoconsideredafunctionalprogramminglanguagelikeSchemeandOCamlbecauseit has closures and supports higher-order functions.

Mention application of JavaScript? 4. Answer:JavaScript’suseinapplicationsoutsidewebpagesforexampleinPDF-documents,site-specificbrowsersanddesktopwidgetsisalsosignificant.NewerandfasterJavaScriptVMs,particularlyNode.jshavealsoincreasedthe popularity of JavaScript for server-side web apps.

Write a program for simple recursive function.5. Answer:

function factorial(n) { if (n === 0) { return 1; } return n * factorial(n - 1); }

Page 184: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

172

Application II

Groovy is an object-oriented programming language for the Java platform. •It is a dynamic language with features similar to those of Python, Ruby, Perl, and Smalltalk. •It can be used as a scripting language for the Java Platform.•Groovy uses a Java-like bracket syntax. It is dynamically compiled to Java Virtual Machine (JVM) byte code •and interoperates with other Java code and libraries. Most Java code is also syntactically valid Groovy.•Groovy 1.0 was released on January 2, 2007.•Many(butnotall)validJavafilesarealsovalidGroovyfiles.•Although the two languages are similar, Groovy code can be more compact, because it does not require all the •elements that Java requires. This makes it possible for Java programmers to gradually learn Groovy by starting with familiar Java syntax before acquiring more Groovy idioms.Groovy features not available in Java include both static and dynamic typing (with the def keyword), closures, •operator overloading, native syntax for lists and associative arrays (maps), native support for regular expressions, polymorphic iteration, expressions embedded inside strings, additional helper methods, and the safe navigation operator“?.”toautomaticallycheckfornulls(forexample,"variable?.method()",or"variable?.field").Groovy's syntax can be made far more compact than Java. For example, a declaration in Standard Java 5+ such as:•

for (String it : new String[] {"Rod", "Carlos", "Chris"}) if (it.length() <= 4) System.out.println(it);can be expressed in Groovy as:["Rod","Carlos","Chris"].findAll{it.size()<=4}.each{printlnit}

Groovy provides native support for various markup languages such as XML and HTML, accomplished via an •inlineDOMsyntax.Thisfeatureenablesthedefinitionandmanipulationofmanytypesofheterogeneousdataassets with a uniform and concise syntax and programming methodology.UnlikeJava,aGroovysourcecodefilecanbeexecutedasan(uncompiled)script,ifitcontainscodeoutside•anyclassdefinition,orifitisaclasswithamainmethod,orisaRunnableorGroovyTestCase.But, unlike some script languages such as Ruby, a Groovy script is fully parsed, compiled, and generated before •execution. (This occurs under the hood, and the compiled version is not saved as an artifact of the process.)GroovyBeans are Groovy’s version of JavaBeans. Groovy implicitly generates accessor and mutator methods. •In the following code, setColor(String color) and getColor() are implicitly generated; and the last two lines, which appear to access color directly, are actually calling the implicitly generated methods.

Page 185: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

173

class AGroovyBean { String color} def myGroovyBean = new AGroovyBean() myGroovyBean.setColor('baby blue')assert myGroovyBean.getColor() == 'baby blue' myGroovyBean.color = 'pewter'assert myGroovyBean.color == 'pewter'Groovy offers simple, consistent syntax for handling lists and maps, reminiscent of Java's array syntax.[7]def movieList = ['Dersu Uzala', 'Ran', 'Seven Samurai'] //looks like an array, but is a listassert movieList[2] == 'Seven Samurai'movieList[3] = 'Casablanca' //adds an element to the listassert movieList.size() == 4 def monthMap = [ 'January' : 31, 'February' : 28, 'March' : 31 ] //declares a mapassert monthMap['March'] == 31 //accesses an entrymonthMap['April'] = 30 //adds an entry to the mapassert monthMap.size() == 4

QuestionsWhat do you mean by Groovy? 1. When did Groovy 1.0 release? 2. Why is Groovy Code more compact? 3. Which language did groovy support? 4. What do you mean by GroovyBeans? 5.

Page 186: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

174

Application III

Java Card Java Card refers to a technology that allows Java-based applications (applets) to run securely on smart cards •and similar small memory footprint devices. Java Card is the tiniest of Java targeted for embedded devices. •JavaCardgivestheuserabilitytoprogramthedeviceandmakethemapplicationspecific.•It is widely used in SIM cards (used in GSM mobile phones) and ATM cards.•ThefirstJavaCardwasintroducedin1996bySchlumberger’scarddivisionwhichlatermergedwithGemplus•to form Gemalto. JavaCardproductsarebasedon theJavaCardPlatformspecificationsdevelopedbySunMicrosystems,a•subsidiary of Oracle Corporation. ManyJavacardproductsalsorelyontheGlobalPlatformspecificationsforthesecuremanagementofapplications•on the card (download, installation, personalisation, deletion).The main design goals of the Java Card technology are portability and security. •

PortabilityJavaCardaimsatdefiningastandardsmartcardcomputingenvironment,allowingthesameJavaCardapplet•to run on different smart cards, much like a Java applet that runs on different computers. As in Java, this is accomplished using the combination of a virtual machine (the Java Card Virtual Machine) •andawell-definedruntimelibrary,whichlargelyabstractstheappletfromdifferencesbetweensmartcards.Portability remains mitigated by issues of memory size, performance, and runtime support (For example, for •communication protocols or cryptographic algorithms).

SecurityJava Card technology was originally developed for the purpose of securing sensitive information stored on •smart cards. Security is determined by various aspects of this technology:•Data encapsulation:Data is stored within the application and Java Card applications are executed in an isolated environment (the Java Card VM), separate from the underlying operating system and hardware.

Applet Firewall:Unlike other Java VMs, a Java Card VM usually manages several applications, each one controlling sensitive data.Differentapplicationsarethereforeseparatedfromeachotherbyanappletfirewallwhichrestrictsandchecks access of data elements of one applet to another.

Cryptography:Commonly used encryption algorithms like DES, Triple DES, AES, RSA (including elliptic curve cryptography) are supported. Other cryptographic services like signing, key generation and key exchange are also supported.

Applet:The applet is a state machine which processes only incoming command requests and responds by sending data or response status words back to the interface device.

Page 187: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

175

(Source: Java Card – Technology for Today’s World, Available at: <http://www.articlesbase.com/software-articles/java-card-technology-for-todays-world-2709902.html>[Accessed13October2011]).

QuestionsWhat does Java Card mean? 1. When was the Java Card introduced in the market?2. What does ‘portability’ mean with reference to Java Card?3. What do you mean by security in Java Card? 4. Who developed Java card? 5.

Page 188: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

176

Bibliography

ReferencesAndrew Mulholland, Glenn Murphy, 2003. • Java 1.4 Game Programming. Wordware Publishing. Balagurusamy, 2006.• Programming With Java:A Primer 3E. Tata McGraw-HillBalagurusamy, 2009. • Programming With Java 4E. Tata McGraw-Hill. Buyya, 2009. • Object Oriented Prog With Java. Tata McGraw-Hill Education. C. Thomas Wu, 2009. • An Introduction to Object-Oriented Programming with Java. McGraw-Hill Higher Education. Cay S. Horstmann, 2009. • Java Concepts: Compatible with Java 5, 6 and 7. john Wiley and Sons. David Flanagan, 2005. • Java in a nutshell. O'Reilly Media, Inc.Doug Lowe, Barry Burd, 2007. • Java all-in-one desk reference for dummies. Dummies. Eckel, 2006. • Thinking Java. Pearson Education India. Ivor Horton, 2003. • Beginning Java 2 SDK 1.4 edition. Wirox. Ivor Horton's, 2009. • Beginning Java 2 Jdk (5Th Ed.). Wiley-India Jim Knowlton, 2008. • Python: create-modify-reuse. John Wiley and Sons. Mary Campione, Kathy Walrath, Alison Huml, 2001.• The Java tutorial: a short course on the basics. Addison-Wesley. Powell, 2004. • Java Script: The Complete Reference. Tata McGraw-Hill. Richard F. Raposa, 2009. • SCJP Sun certified programmer for Java platform, SE6 study guide. John Wiley and Sons. Stephen J. Chapman, 1999. • Introduction to Java. Prentice Hall. Wu Thomas, 2009. • An Into To Oop With Java, 4E. Tata McGraw-Hill. Y. Daniel Liang, 2004. Introduction to Java programming with JBuilder. Prentice Hall. •Y. Daniel Liang, 2010. • Introduction to Java Programming. Prentice Hall. Y. Daniel Liang, 2010• . Introduction to Java Programming. Prentice Hall. Y. Daniel Liang,2010. • Introduction to Java Programming. Prentice Hall.

Recommended Reading Arnold, 2000. • The Java Programming language. Pearson Education India. Arulkumaran Kumaraswamipillai, Sivayini Arulkumaran,2007. • Java/J2EE Job Interview Companion. Lulu.com. Balagurusamy, 2009. • Programming With Java 4E. Tata McGraw-Hill Education. Balagurusamy, 2009. • Programming With Java 4E. Tata McGraw-Hill. Barry Burd, 2009. • Java For Dummies. Wiley-India. Cay S. Horstmann, Gary Cornell, 2001. • Core Java 2: Fundamentals. Prentice Hall PTR. David Barnes, David J. Barnes, 2000. • Object-oriented programming with Java: an introduction. Prentice Hall. David Flanagan, 2005. • Java in a nutshell. O'Reilly Media, Inc.David Flanagan, 2005.• Java in a nutshell. O'Reilly Media. Dr. G.T.Thampi, 2009• . Object Oriented Programming In Java (With Cd). Wiley-India. Duane J. Jarc, 2000. • Java Programming & Projects (jdk 5 Edition). Wiley-India. E. Reed Doke, Bill C. Hardgrave, 1999. • Java for the COBOL programmer. Cambridge University Press.

Page 189: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

177

Julie Anderson, Hervé Franceschi, 2008. • Java 6 illuminated: an active learning approach. Jones & Bartlett Learning. Julie Anderson, Hervé Franceschi, 2008. • Java 6 illuminated: an active learning approach. Jones & Bartlett Learning. Kenneth A. Barclay, John Savage, W. John Savage, 2007. • Groovy programming: an introduction for Java developers. Morgan Kaufmann. Mark Grand, Jonathan Knudsen, 1997. • Java fundamental classes reference. O'Reilly. Mary Campione, Kathy Walrath, Alison Huml, 2001. • The Java tutorial: a short course on the basics. Addison-Wesley. Nell B. Dale, Chip Weems, Mark R. Headington, 2002. • Introduction to Java and software design. Jones & Bartlett Learning. R. Nageswara Rao/kogent Solutions, 2008. • Core Java: An Integrated Approach. Dreamtech Press. R. Nageswara Rao/kogent Solutions,2008. • Core Java: An Integrated Approach. Dreamtech Press. Schildt, 2006. • Java: The Complete Reference. Tata McGraw-Hill Education.

Page 190: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

Programming in Java

178

Self Assessment Answers

Chapter Ia1. a2. d3. b4. c5. a6. d7. d8. c9. a10.

Chapter IIc1. a2. a3. b4. d5. a6. c7. a8. c9. d 10.

Chapter IIIb1. b2. a3. c4. c5. d6. a7. d8. c9. a10.

Chapter IV a1. b2. a3. b4. c5. a6. d7. a8. a9. b10.

Page 191: jnujprdistance.comjnujprdistance.com/assets/lms/LMS JNU/MCA/Sem V... · II Contents Chapter I ...

179

Chapter Vd1. c2. a3. b4. a5. c6. c7. a8. b9. a10.

Chapter VI a1. c2. a3. c4. b5. c6. c7. b8. d9. d10.

Chapter VIIa1. b2. c3. b4. a5. a6. c7. d8. c9. b10.