120 8 5MB
English Pages 452 Year 2020
Programming with
JAVA
Rohit Khurana Founder and CEO ITLESL, Delhi
VIKAS® PUBLISHING HOUSE PVT LTD
VIKAS® PUBLISHING HOUSE PVT LTD E-28, Sector-8, Noida-201301 (UP) India Phone: +91-120-4078900 • Fax: +91-120-4078999 Registered Office: 576, Masjid Road, Jangpura, New Delhi-110014. India E-mail: [email protected]
• Website: www.vikaspublishing.com
• Ahmedabad : 305, Grand Monarch, 100 ft, Shyamal Road, Near Seema Hall, Ahmedabad-380 051 • Ph. 079-65254204, 98982 94208 • Bengaluru
: First Floor, N.S. Bhawan, 4th Cross, 4th Main, Gandhi Nagar, Bengaluru-560009 • Ph. +91-80-22204639, 22281254
• Chennai
: E-12, Nelson Chambers, 115, Nelson Manickam Road, Aminjikarai Chennai -600029 • Ph. +91-44-23744547, 23746090
• Hyderabad : Aashray Mansion, Flat-G (G.F.), 3-6-361/8, Street No. 20, Himayath Nagar, Hyderabad-500029 • Ph. +91-40-23269992 • Fax. +91-40-23269993 • Kolkata
:
• Mumbai
: 67/68, 3rd Floor, Aditya Industrial Estate, Chincholi Bunder, Malad (West), Mumbai-400064 • Ph. +91-22-28772545, 28768301
82, Park Street, Kolkata-700017 • Ph. 033-22837880
• Patna
: Flat No. 101, Sri Ram Tower, Besides Chiraiyatand Over Bridge, Kankarbagh Main Road, Kankarbagh, Patna - 800 020, (Bihar)
Programming with Java ISBN: 978-93259-7839-3 Vikas® is the registered trademark of Vikas Publishing House Pvt Ltd Copyright © Author, 2014 All rights reserved. No part of this publication which is material protected by this copyright notice may be reproduced or transmitted or utilized or stored in any form or by any means now known or hereinafter invented, electronic, digital or mechanical, including photocopying, scanning, recording or by any information storage or retrieval system, without prior written permission from the publisher. Information contained in this book has been published by VIKAS® Publishing House Pvt Ltd and has been obtained by its Authors from sources believed to be reliable and are correct to the best of their knowledge. However, the Publisher and its Authors shall in no event be liable for any errors, omissions or damages arising out of use of this information and specifically disclaim any implied warranties or merchantability or fitness for any particular use. Disputes if any are subject to Delhi Jurisdiction only. Printed in India.
Dedication I would like to dedicate this book to my uncle,
Shri G K Jaju for his understanding, constant support and trust in me. He has always inspired me to aim higher and achieve bigger. He has been a great friend, philosopher and guide.
This Page has been intentionally left blank
PREFACE Software development technology has been changing quite rapidly. The programming languages, paradigms and practices that were applied yesterday are out of date today. To keep pace with the emerging trends, Java language has been introduced. The main motivation behind the development of Java was the need for a platform-independent language that could be used to create software that could be embedded in various consumer electronic devices. C and C++ cannot be used with such devices because they are designed to be compiled for a specific target. Within a few years, Java grew from a concept into one of the world’s dominant computer languages. Moreover, within a few span of years, Java has gone through two major revisions. The first one was Java 1.1 and the second major revision was Java 2.
The book in your hands, Programming with Java, provides all the necessary knowledge required to develop simple as well as network-aware Java programs. The book moves from simple material covering the basics of programming and object-oriented software to relatively advanced material. The text has been carefully organized to make it particularly easy for the students to grasp the concepts of Java. Key Features
• • • • • • • •
Simple and easy-to-follow text Complete coverage of the subject as per the syllabi of most universities Lucid, well-explained concepts with clear examples Relevant illustrations for better understanding and retention Numerous programming examples for better clarity of concept Chapter objectives at the beginning of the chapter for an overview of the chapter Chapter-end summary and exercises for quick review and to test your knowledge A comprehensive index at the end of the book for quick access to the topics
Chapter Organization The book is organized into 20 chapters. Chapter 1 provides an overview of various programming paradigms, introduces the object-oriented (OO) methodology and its fundamental concepts, benefits and applications of OO approach. Chapter 2 explains how Java is important to the Internet and a simple program to demonstrate how Java compiler works. Chapter 3 introduces various data types, variables, constants that constitute the basic elements of a language. Chapter 4 covers the different types of control statements in Java. Chapter 5 presents the basic concepts of object-oriented programming, including classes and objects.
vi
Preface
Chapter 6 familiarises the student with the basic concepts of arrays, strings and vectors. It also discusses the concept of wrapper classes. Chapter 7 focuses on the use of inheritance to create reusable classes. This chapter discusses how polymorphism can be achieved. Chapter 8 provides an overview of interface, which is a convenient alternative to implement multiple inheritance. Chapter 9 explains the concept of package and its advantages. It also discusses various API packages and how they can be used in our program. Chapter 10 gives an overview of exception that can occur in a program. It describes techniques to deal with compile time as well as run time errors. Chapter 11 describes the concept of multithreading and how it can be implemented in Java. Chapter 12 presents Java’s input-output classes, showing how to read and write stream and files. Chapter 13 explains the creation and use of applets in applications. It also discusses the significance of graphics class in applets. Chapter 14 describes the role of events in applet programming and how they can be handled. Chapter 15 presents each of the AWT component and shows how to place them in container and handle the events they generate. Chapter 16 explains how Swing, a part of Java Federation Classes (JFC), the next generation GUI toolkit, can be used to develop large-scale enterprise applications in Java. Chapter 17 provides an overview of Java Database Connectivity (JDBC) that can accessa database in Java. Chapter 18 explains how reusable software components can be developed using the Java Beans technology. Chapter 19 explains how Servlets can be created in Java, which are loaded and executed by web server. Chapter 20 explains how Java supports creation of sockets and exchange information using different protocols. Acknowledgements In all my efforts towards making this book a reality, my special thanks goes to my technical and editorial team, without whom this work would not have achieved its desired level of excellence. I sincerely extend my thanks to my research and development team for devoting their time and relentless effort in bringing out this high-quality book. I convey my gratitude to my publisher Vikas Publishing House Pvt. Ltd for sharing this dream and giving all the support in realizing it. In our attempt towards further improvement, I welcome you all to send your feedback to [email protected]. I will highly appreciate all your constructive comments. I hope you will enjoy reading the book and hope it proves to be a good resource for all. Rohit Khurana Founder and CEO ITLESL, Delhi
CONTENTS Preface
v
Chapter 1
Objected-Oriented Methodology
1 – 14
1.1 1.2 1.3 1.4 1.5
Introduction 1 Paradigms of Programming Languages 1 Evolution of Objected-oriented Methodology 2 Comparison of Object-Oriented and Procedure-Oriented Approach 2 Basic Concepts of OO Approach 5 1.5.1 Objects 5 1.5.2 Classes 5 1.5.3 Abstraction 7 1.5.4 Encapsulation 7 1.5.5 Inheritance 7 1.5.6 Polymorphism 8 1.5.7 Method Overriding 8 1.5.8 Message Passing 9 1.6 Benefits of OOP 9 1.7 Introduction to Common OO Languages 10 1.8 Applications of OOP 11 Summary 12 Exercises 12
Chapter 2
Java and the Internet 2.1 Introduction 15 2.2 Basic Features of Java Programming Language 15 2.3 Java versus C++ 16 2.4 Java’s Importance to the Internet 17 2.5 Java Compiler 17 2.6 Java Virtual Machine Concepts 17 2.7 JDK (Java Development Kit) 18 2.8 A First Look at Java Program 18 2.9 Running Java Applications 19 2.10 Command Line Arguments 20 Summary 20 Exercises 21
15 – 22
viii Contents
Chapter 3
Programming Elements of Java
23 – 40
3.1 3.2 3.3
Introduction 23 Character Set 23 Tokens 23 3.3.1 Keywords 24 3.3.2 Identifiers 24 3.3.3 Constants 24 3.3.4 Operators 26 3.3.5 Punctuators 26 3.4 Structure of a Java Program 26 3.5 Data Types 27 3.5.1 Primitives Data Types 27 3.5.2 Non-Primitive Data Types 28 3.6 Variables 29 3.7 Type Casting 30 3.8 Operators and Operations 32 3.8.1 Arithmetic Operators 32 3.8.2 Increment and Decrement Operators 33 3.8.3 Relational Operators 33 3.8.4 Logical Operators 34 3.8.5 Conditional Operator 34 3.8.6 Assignment Operators 35 3.8.7 Other Operators 35 3.8.8 Operators Precedence and Associativity 36 Summary 37 Exercises 38
Chapter 4
Control Statements
41 – 58
4.1 4.2 4.3
Introduction 41 Selection Statements 41 Iteration Statements 48 4.3.1 The for Loop 48 4.3.2 The while Loop 48 4.3.3 The do-while Loop 51 4.4 Jump Statements 53 4.5 Labeled Loops 54 Summary 56 Exercises 56
Chapter 5
Classes and Objects 5.1 5.2
Introduction 59 Class Fundamentals 59
59 – 80
Contents
ix
5.2.1 Introducing Methods 60 Creating Objects 61 Accessing Members of a Class 62 Assigning Object Reference Variables 63 Argument Passing 64 5.6.1 Call-by-Value 64 5.6.2 Call-by-Reference 65 5.7 Static Variables and Methods 66 5.8 Method Overloading 67 5.9 Constructors 68 5.9.1 Parameterized Constructors 69 5.9.2 Overloading Constructor 70 5.10 Using Objects as Parameters 71 5.11 Returning Objects 72 5.12 Recursion 73 5.13 Inner Classes 75 5.14 this Keyword 75 5.15 Garbage Collection 77 5.15.1 The finalize() Method 77 Summary 78 Exercises 78 5.3 5.4 5.5 5.6
Chapter 6
Arrays, Strings and Vectors
81 – 97
6.1 6.2
Introduction 81 Arrays 81 6.2.1 Single-dimensional Arrays 82 6.2.2 Multi-dimensional Arrays 84 6.3 Strings 88 6.3.1 String Class 88 6.3.2 StringBuffer Class 89 6.4 Vectors 91 6.5 Wrapper Classes 92 Summary 95 Exercises 95
Chapter 7
Inheritance and Polymorphism 7.1 7.2 7.3
Introduction 99 Inheritance Basics 99 7.2.1 Defining a Subclass 100 Types of Inheritance 100 7.3.1 Single Inheritance 100 7.3.2 Hierarchical Inheritance 102
99 – 119
x Contents 7.3.3 Multilevel Inheritance 104 7.3.4 Multiple Inheritance 106 7.4 Visibility Controls (Access Controls) 106 7.5 Subclass Constructor 108 7.6 Method Overriding 110 7.7 Run-Time Polymorphism or Dynamic Method Dispatch 111 7.8 Using final Keyword 112 7.8.1 Final Variables 113 7.8.2 Final Methods 113 7.8.3 Final Classes 114 7.9 Abstract Methods and Classes 115 Summary 116 Exercises 117
Chapter 8
Interface
121 – 132
8.1 Introduction 121 8.2 Defining Interface 121 8.3 Implementing Interface 122 8.4 Extending Interfaces 124 8.5 Variables in Interfaces 125 8.6 Interface and Abstract Classes 126 8.7 Extends and Implements Together 127 Summary 129 Exercises 129
Chapter 9
Packages Introduction 133 Packages 133 Java API Packages 133 9.3.1 Package Naming 135 9.4 Defining Packages 135 9.5 CLASSPATH 136 9.6 Accessibility of Packages 138 9.7 Using Package Members 138 9.8 Adding a Class 140 9.9 Hiding a Class 141 9.10 Packages and Visibility Controls Summary 145 Exercises 145
133 – 147
9.1 9.2 9.3
Chapter 10
Exception Handling 10.1
Introduction 149
142
149 – 165
Contents
xi
10.2 10.3 10.4 10.5
Exceptions 149 Exception Handling 150 Types of Exceptions 151 Using try and catch blocks 152 10.5.1 Multiple catch blocks 153 10.5.2 Nested try blocks 155 10.6 Using finally Block 156 10.7 Using throw Keyword 158 10.8 Using throws Keyword 159 10.9 Creating Your Own Exceptions 160 Summary 161 Exercises 162
Chapter 11
Multithreading Introduction 167 Concept of Threads 167 Main Thread 168 Creating Threads 169 11.4.1 Extending Threads 169 11.4.2 Implementing Runnable Interface 171 11.5 Life Cycle of a Thread 172 11.6 Thread Methods 174 11.6.1 Using yield(), sleep() and stop() method 11.6.2 Using isAlive() and join() method 176 11.7 Threads Priority 179 11.8 Synchronization of Threads 181 11.8.1 Synchronizing Methods 181 11.8.2 Synchronizing Statements 184 11.8.3 Deadlock 185 11.9 Inter-Thread Communication 188 11.10 Suspending, Resuming and Stopping Threads 192 Summary 194 Exercises 195
167 – 197
11.1 11.2 11.3 11.4
Chapter 12
I/O in Java 12.1 12.2 12.3 12.4
12.5
Introduction 199 I/O Basics 199 Streams 199 Stream Classes 200 12.4.1 Byte Stream Classes 201 12.4.2 Character Stream Classes 204 The PrintStream Class 208
174
199 – 228
xii Contents 12.6 12.7 12.8 12.9
Predefined streams 209 Reading From and Writing to Console 209 Reading and Writing Files 210 Data Streams 213 12.9.1 The DataInputStream Class 213 12.9.2 The DataOutputStream Class 214 12.10 The StringTokenizer Class 216 12.11 The StreamTokenizer Class 218 12.12 The transient and volatile Modifiers 221 12.13 Using instanceof Operator 221 12.14 Native Methods 223 Summary 225 Exercises 226
Chapter 13
Java Applets
229 – 252
13.1 13.2
Introduction 229 Applet Fundamentals 229 13.2.1 Life Cycle of an Applet 230 13.3 Steps to Build an Applet 231 13.3.1 Creating an Applet code 231 13.3.2 Creating an Executable Applet 232 13.3.3 Designing an HTML Document 232 13.3.4 Running the Applet 234 13.4 Passing Parameters to Applets 235 13.5 getDocumentBase() and getCodeBase() 236 13.6 AppletContext and showDocument() 237 13.7 Working with Graphics 238 13.7.1 Using Graphics Class 238 13.7.2 Using Color class 243 13.7.3 Using Font class 245 13.7.4 Using Image class 247 13.8 Adding Sound to an Applet 249 Summary 250 Exercises 250
Chapter 14
Event Handling 14.1 14.2 14.3
14.4
Introduction 253 Events 253 Event Handling Model 253 14.3.1 Java 1.0 Event Model 254 14.3.2 Delegation Event Model 254 Event Handling 255
253 – 266
Contents
xiii
14.4.1 Event Classes 255 14.4.2 Event Sources 256 14.4.3 Event Listener Interfaces 257 14.4.4 Adapter Classes 263 Summary 265 Exercises 265
Chapter 15
Abstract Window Toolkit 15.1 Introduction 267 15.2 AWT: Working with Windows Graphics and Text 15.3 Using AWT Controls 268 15.4 AWT Layout Managers 275 Summary 280 Exercises 280
Chapter 16
267 – 282 267
Java Swing 16.1 16.2
16.3 16.4
16.5 16.6 16.7
Introduction 283 Features of Swing 283 16.2.1 Lightweight Components 283 16.2.2 Pluggable Look and Feel 284 The Swing Packages 284 Swing Components and Containers 284 16.4.1 Swing Components (JComponent Class) 16.4.2 Swing Containers 285 Creating a Swing Applet and Application 285 Layout Manager 288 User Interface Components 288 16.7.1 JApplet 288 16.7.2 JFrame 288 16.7.3 Label 290 16.7.4 Button 290 16.7.5 ToggleButton 290 16.7.6 CheckBox 291 16.7.7 TextField 291 16.7.8 TextArea 291 16.7.9 RadioButton 292 16.7.10 Panel 292 16.7.11 ScrollPane 292 16.7.12 List 293 16.7.13 ComboBox 297 16.7.14 ScrollBar 299 16.7.15 Menu Bar and Menus 300
283 – 345
284
xiv Contents 16.7.16 Toolbars 305 Programming using Panes 307 16.8.1 Layered Panes 307 16.8.2 Split Panes 308 16.8.3 Tabbed Panes 311 16.9 Working with Layouts 312 16.9.1 Flow Layout 313 16.9.2 Border Layout 314 16.9.3 Grid Layout 316 16.9.4 Card Layout 317 16.9.5 Grid Bag Layout 320 16.10 Windows 323 16.11 Internal Frame 324 16.12 Using Dialogs 326 16.13 JOptionPane 329 16.13.1 Message Dialog Box 329 16.13.2 Input Dialog Box 331 16.13.3 Confirmation Dialog Box 333 16.13.4 Option Dialog Box 335 16.14 JTable 337 16.15 Timer 339 16.16 JProgressBar 340 16.17 JSlider 341 Summary 342 Exercises 343
16.8
Chapter 17
Java Database Connectivity (JDBC) 17.1 17.2 17.3 17.4
347 – 358
Introduction 347 Overview of JDBC 347 JDBC-ODBC Bridge 348 JDBC Implementation 349 17.4.1 The DriverManager Class 349 17.4.2 The Connection Interface 349 17.4.3 The Statement Interface (Handling database queries statically) 350 17.4.4 The ResultSet Interface 350 17.4.5 The PreparedStatement Interface (Handling Database Queries Dynamically) 353 17.4.6 The ResultSetMetaData Interface 354 Summary 356 Exercises 356
Contents
Chapter 18
Java Beans
xv
359 – 388
18.1 18.2
Introduction 359 Java Beans 359 18.2.1 Bean Architecture 360 18.2.2 Introspection 360 18.2.3 Bound and Constrained Properties 363 18.2.4 Persistence 363 18.2.5 Customization 364 18.2.6 Bean Conventions 364 18.2.7 A Simple Bean 364 18.3 Application Builder Tools 365 18.4 The Bean Development Kit 366 18.4.1 Downloading and Installing the BDK 366 18.4.2 Starting the BeanBox 366 18.4.3 Using the BeanBox 367 18.5 JAR Files 370 18.6 Developing a New Bean Using BeanBox 373 18.7 Using Bound Properties 379 18.8 Using the BeanInfo Interface 380 18.9 The Java Beans API 382 18.10 Enterprise JavaBeans (EJB) 384 18.10.1 Session Beans 385 18.10.2 Entity Beans 386 Summary 386 Exercises 387
Chapter 19
Java Servlets 19.1 19.2 19.3 19.4 19.5 19.6 19.7
Introduction 389 Introduction to Servlet 389 Servlet—Life Cycle of a Servlet 390 The Servlet API 390 Creating and Executing Servlets 392 Using GenericServlet Class 393 Handling HTTP Request and Response 397 19.7.1 The doGet() Method 397 19.7.2 The doPost() Method 400 19.8 Session Tracking 400 19.8.1 Using Cookies 402 19.9 Introduction to JSP (Java Server Pages) 406 19.9.1 Elements of JSP code 407 Summary 410 Exercises 410
389 – 412
xvi Contents
Chapter 20
Socket Programming
413 – 428
20.1 20.2
Introduction 413 Client and Server Concept 413 20.2.1 TCP/IP Protocols 414 20.2.2 IP Address 415 20.2.3 Ports and Port Numbers 415 20.2.4 Sockets 415 20.3 URLs (Uniform Resource Locators) 416 20.3.1 URL Class 417 20.4 The Networking Classes and Interfaces 417 20.5 The InetAddress Class 418 20.6 TCP/IP Sockets 419 20.6.1 Simple Server Program 420 20.6.2 Simple Client Program 422 20.7 UDP Sockets 423 Summary 426 Exercises 426
Index
429 – 436
CHAPTER OBJECTED-ORIENTED METHODOLOGY
1
CHAPTER OBJECTIVES After reading this chapter, you will be able to: • Understand the evolution of various programming methodologies • Differentiate between OOP and structured programming • Understand the key concepts of OOP, including objects, classes, encapsulation, abstraction, inheritance, method overriding and polymorphism, and message passing • Describe the applications of OOP in different areas • Get familiar with object-oriented languages that purely or partially follow the object-oriented concepts
1.1
INTRODUCTION
The goal of programmers is to develop software that are correct, reliable and maintainable, and satisfy all the user requirements. Software development is not a static process. Software needs to be modified or redesigned according to the change in user requirements, business rules and strategies. In addition, the complexity of the software also increases. To cope with the dynamic nature and complexity of the software, different approaches of programming were developed since the invention of the computer. These approaches are known as programming paradigms. This chapter provides an overview of various programming paradigms, introduces the objectoriented methodology and its fundamental concepts, benefits and applications of OO approach, etc.
1.2
PARADIGMS OF PROGRAMMING LANGUAGES
A programming paradigm (also known as programming methodology) describes the structure of a program. In other words, it determines how the instructions are placed in a program. Each programming language follows one or the other programming paradigm. There is no specific rule to decide which programming paradigm is to be followed as different paradigms can be used to develop different software. However, whatever paradigm is followed, some of the quality issues of software must be kept in mind. This includes correctness, usefulness, robustness, maintainability, reusability, portability, reliability and interoperability of the software. Some of the paradigms are: unstructured programming paradigm, procedural paradigm and object-oriented paradigm.
2
Programming with Java
1.3
EVOLUTION OF OBJECTED-ORIENTED METHODOLOGY
Initially, when computers were invented, binary language was used to write the programs. However, as programs grew in size, it became difficult to write programs using binary language. Then assembly language was invented to write large programs, which were also not user-friendly. With the change in user requirements, the size and the complexity of the programs continued to grow, which led to the development of high-level languages such as BASIC and FORTRAN. However, these languages provided an unstructured way of writing programs. In unstructured programming paradigm, all the instructions of a program were written one after the other in a single function and hence, suitable for writing only small and simple programs. For large and complex programs, it became difficult to trace and debug errors. To overcome the limitations of unstructured programming paradigm, other programming paradigms, namely, procedural and object-oriented programming paradigms, were developed, which helped the programmers to develop the programs in a structured way. Of these two, the object-oriented paradigm is the most commonly used approach these days.
1.4
COMPARISON OF OBJECT-ORIENTED AND PROCEDURE-ORIENTED APPROACH
In the late 1960s, the high-level languages such as C and Pascal were developed, which provided a structured way of writing programs. Structured programming (also known as procedural programming) was a powerful and an easy approach to writing complex programs. In procedural programming, programs are divided into different procedures (also known as functions, routines or subroutines) and each procedure contains a set of instructions that performs a specific task. This approach follows the top-down approach for designing the program. That is, first the entire program is divided into a number of subroutines and these subroutines are again divided into small subroutines and so on until each subroutine becomes an indivisible unit (see Figure 1.1).
Figure 1.1 Top-down Approach
Objected-Oriented Methodology 3 Programs in procedural programming consist of a controlling procedure known as the main, which controls the execution of other procedures. When a call to a procedure is made, the program control is passed to that procedure and all the instructions in that procedure are executed one after another. After executing all the instructions, the program control returns to the procedure from where the call is made. For example, to write a program that can add, modify, find and delete students’ records from a database using structured programming, the entire program can be divided into four different procedures, namely, add, find, delete and modify (see Figure 1.2). In addition to these procedures, the program consists of a main procedure. If a user wants to add a record of a student in a database, the control is passed from the main procedure to the add procedure. Once all the instructions are executed in add procedure, the control is transferred back to the main procedure. The same steps are followed while calling other procedures.
Figure 1.2 Procedural Programming
Though writing programs using procedural programming paradigm is a simple and easy task, there are some limitations also: • The emphasis is on the functionality of the software rather than the data used by the functions. • Procedural programming allows data to move freely from one function to another without any security. That is, the data to be shared among many functions is declared globally so that all the functions can easily access it. However, this makes the global data liable to change as any function can modify its value. • In case the need arises to modify the format of the data, all the functions accessing the data also need to be modified. This causes an extra overhead and makes the programs error-prone. • The procedural programming approach does not model the real world very well as any realworld entity is characterized not only by the functions it performs but also the properties (or data) it possesses. However, in procedural approach the data and the associated functions are loosely related.
4
Programming with Java • The large programs developed using this approach are difficult to maintain, debug and extend. The basic idea behind the procedural programming approach is shown in Figure 1.3.
Figure 1.3 Accessing Global Data
To overcome the limitations of procedural programming, object-oriented programming (OOP) paradigm was developed, which has revolutionized the process of software development. It not only includes the best features of structured programming, but also some new and advanced features that the procedural programming lacked. The most important feature is that unlike procedural approach in which the program is divided into a number of functions, OOP divides the program into a number of objects. An object is a unit of structural and behavioural modularity that contains a set of properties (or data) as well as the associated functions. In addition, programmers can create relationships between the objects. As stated earlier, OOP has introduced some new and advanced features that procedural programming lacked. The most important feature is that unlike the procedural approach, in which the program is divided into a number of functions, OOP divides the program into a number of objects. Some of the other features of OOP are also described here: • OOP emphasises data rather than the functions or the procedures. • OOP models the real world very well by binding the data and associated functions together under a single unit and thus, prevents the free movement of data from one function to another. • The data of one object can be accessed by the associated functions of that object only. Other functions are not allowed to access that data. In other words, data is hidden from the outside world. However, the functions of one object can access the functions of other object. • The objects of the entire system can interact with each other by sending messages to each other. • The programs written in OOP are easy to maintain and extend as new objects can be easily added to the existing system whenever required without modifying the other objects. • OOP follows the bottom-up approach for designing the programs. That is, first objects are designed and then these objects are combined to form the entire program. The basic idea behind OOP is shown in Figure 1.4.
Objected-Oriented Methodology 5
Figure 1.4 Data and Functions in OOP
1.5
BASIC CONCEPTS OF OO APPROACH
To understand the concept of object-oriented programming, it is necessary to know the fundamental terms and concepts of this approach. These include objects, classes, data abstraction, encapsulation, inheritance, method overriding and polymorphism, and message passing 1.5.1
Objects
Objects are the small, self-contained and modular units with a well-defined boundary. An object consists of a state and behaviour. The state of an object is one of the possible conditions that an object can exist in and is represented by its characteristics or attributes or data. The behaviour of an object determines how an object acts or behaves and is represented by the operations that it can perform. In OOP, the attributes of an object are represented by the variables and the operations are represented by the functions. For example, an object Biscuit may consist of data product code P001, product name Britannia Biscuits, price 20 and quantity in hand 50. These data values specify the attributes or features of the object. Similarly, consider another object Maggi with product code P002, product name Maggi Noodles, price 10, and quantity in hand 20 (see Figure 1.5). In addition, the data in the object can be used by the functions such as check_qty() and display_product(). These functions specify the actions that can be performed on data. Objects are what actually runs in the computer and thus, are the basic run-time entities in object-oriented systems. They are the building blocks of object-oriented programming. Although, two or more objects can have same attributes, still they are separate and independent objects with their own identity. In other words, all the objects in a system take a separate space in the memory independent of each other. Note that the main objective of breaking down complex software projects into objects is that changes made to one part of a software should not adversely affect the other parts. 1.5.2 Classes A class is defined as a user-defined data type which contains the entire set of similar data and the functions that the objects possess. In other words, a class in OOP represents a group of similar
6
Programming with Java
objects. As stated earlier, in the real world millions of objects exist and each of them has its own identity. However, each of them can be categorized under different groups depending on the common properties they possess and the functions they perform. For example, cars, scooters, motorbikes, buses, etc., all can be grouped under the category vehicles. Similarly, dogs, cats, horses, etc., can be grouped under the category animals. Thus, vehicles and animals can be considered as the classes. A class serves as a blueprint or template for its objects. That is, once a class has been defined, any number of objects belonging to that class can be created. The objects of a class are also known as the instances or the variables of that class and the process of creating objects from a class is known as instantiation. Note that a class does not represent an object, rather it represents the data and functions that an object will have. For example, a class Product consists of data such as p_code, p_name, p_price and qty_in_ hand which specify the attributes or features of the objects of the Product class. In addition, it consists of functions such as display_product() and check_qty() that specify the actions that can be performed on data (see Figure 1.5).
Figure 1.5 Class and its Objects
Note that the data belonging to a particular class is known as its data members and the functions of the class are known as the member functions and both collectively are known as the members of the class. Note: In Java, the data members are referred to as instance variables and member functions are referred to as methods.
Objected-Oriented Methodology 7 1.5.3 Abstraction Abstraction is a mechanism to hide irrelevant details and represent only the essential features so that one can focus on important things at a time. It allows managing complex systems by concentrating on the essential features only. For example, while driving a car, a driver only knows the essential features to drive a car such as how to use clutch, brake, accelerator, gears, steering, etc., and doesa not bother about the internal details of the car like motor, engine, wiring, etc. Abstraction can be of two types, namely, data abstraction and control abstraction. Data abstraction (also known as data hiding) means hiding the details about the data and control abstraction means hiding the implementation details. In object-oriented approach, one can abstract both data and functions. However, generally, the classes in OOP are defined in such a way that the data is hidden from the outside world and the functions form the public interface. That is, the functions of the class can be directly accessed by other functions outside the class, and the hidden data can be accessed indirectly with the help of these functions. Since the internal details of the class are hidden from the outside world, the data abstraction ensures security of data by preventing it from accidental changes or manipulations by other parts of the program. Note: Classes in the object-oriented programming are also known as Abstract Data Types (ADT) as they use the concept of abstraction.
1.5.4
Encapsulation
Encapsulation is the technique of binding or keeping the data and functions (that operate on them) together in a single unit called a class. Encapsulation is the way to implement data abstraction. A well-encapsulated object acts as a ‘black box’ for other parts of the program. That is, it provides services to the external functions or other objects that interact with it. However, these external functions or the objects do not need to know its internal details. For example, in Figure 1.5 the data p_code, p_name, p_price and qty_in_hand and the functions display_product() and check_qty are encapsulated in a class Product. 1.5.5
Inheritance
Inheritance can be defined as the process whereby an object of a class acquires characteristics from the object of another class. As stated earlier, all the objects of a similar kind are grouped together to form a class. However, sometimes a situation arises when different objects cannot be combined together under a single group as they share only some common characteristics. In this situation, the classes are defined in such a way that the common features are combined to form a generalized class and the specific features are combined to form a specialized class. The specialized class is defined in such a way that in addition to the individual characteristics and functions, it also inherits all the properties and the functions of its generalized class. For example, in the real world, all the vehicles cannot be automobiles—some of them are pulledvehicles also. Thus, both car and scooter are vehicles that come under the category of automobiles. Similarly, rickshaw and bicycle are the vehicles that come under the category of pulled-vehicles. Thus, automobiles and pulled-vehicles inherit the common properties of the vehicle class and also
8
Programming with Java
have some other properties that are not common and differentiate them. Thus, the vehicles class is the generalization of automobiles and pulled-vehicles class, and automobiles and pulled-vehicles classes are the specialized versions of the vehicles class. Note that while inheriting the vehicle class, the automobiles and pulled-vehicles do not modify the properties of the vehicle class, however, can add new properties that are exclusive for them (see Figure 1.6).
Figure1.6 Inheritance
In the same way, OOP allows one class to inherit the properties of another class or classes. The class, which is inherited by the other classes, is known as superclass or base class or parent class and the class, which inherits the properties of the base class, is called sub class or derived class or child class. The sub class can further be inherited to form other derived classes. For example, in Figure 1.6, car and scooter are the derived classes of automobiles and rickshaw and bicycle are the derived classes of pulled-vehicles. The main advantage of inheritance is reusability. The existing classes can be simply re-used in new software instead of writing a new code. Moreover, new features can be added without altering or modifying the features of the existing class. 1.5.6
Polymorphism
Polymorphism (a Greek word meaning having multiple forms) is the ability of an entity such as a function or a message to be processed in more than one form. It can also be defined as the property of an object belonging to a same or different class to respond to the same message or function in a different way. For example, if a message change_gear is passed to all the vehicles then the automobiles will respond to the message appropriately however, the pulled vehicles will not respond. The concept of polymorphism plays an important role in OOP as it allows an entity to be represented in various forms. 1.5.7
Method Overriding
A base class method can be inherited in the derived class, however, sometimes it may need to be redefined according to the requirement in the derived class. This redefining of the base class method in the derived class is called method overriding (another form of polymorphism). Method overriding implies that a method in a derived class has the same name as that of the base class method, however, it has a different implementation.
Objected-Oriented Methodology 9 1.5.8
Message Passing
Message passing is a process of interacting between different objects in a program. As discussed earlier, a program following the object-oriented paradigm comprises a set of objects each with a set of data and functions. When the program is executed, these objects interact or communicate with each other by sending and receiving messages. The messages are exchanged by calling the member functions of the classes. Any object of a class that wants to communicate with the object of another class requests the object to invoke the required member function of its class. This function call is different from the normal function call as in this case the sending object is sending a request for the execution of the function. However, the receiving object may or may not accept the request depending on whether the function forms the public interface or it is hidden from the outside world. Thus, this form of communication is called message sending and not an ordinary function call. For example, consider two classes Product and Order. The object of the Product class can communicate with the object of the Order class by sending a request for placing order (see Figure 1.7).
Figure 1.7 Message Passing
1.6
BENEFITS OF OOP
The object-oriented programming paradigm came into use as it overcomes certain limitations of structured and unstructured programming paradigms. The new and advanced features of OOP such as encapsulation, abstraction, inheritance, and polymorphism help in developing high-quality software. The high-quality software can be developed due to its certain advantages. Some of the advantages of OOP are listed here. • In OOP, writing programs with the help of objects is much similar to working with real-world objects. That is, the real-world objects can be conveniently represented in a program which reduces the compexity of the program and also makes the program structure clear. • In object-oriented programs, each object is an independent and separate entity which makes modifications, locating and fixing problems in a program an easy task. In addition, any changes made inside the class do not affect the other parts of a program. Thus, object-oriented programs are easy-to-write and easy-to-maintain.
10
Programming with Java
• In object-oriented programming, data integrity and data security is high as it focuses on the data and its protection from manipulation by different parts of the program. As a result, objectoriented programs are less error-prone, more reliable and secure. • Object-oriented programs are easy to extend as new features in a program can be added easily by introducing a few new objects without modifying the existing ones. • Object-oriented programming allows re-usability of code. That is, the objects created in one program can be re-used in other programs. In addition, new classes can be created with the help of existing ones using inheritance. It leads to faster software development and high-quality programs. • Object-oriented programs are easier to adapt and scale, that is, large system can be created by assembling re-usable subsystems.
1.7
INTRODUCTION TO COMMON OO LANGUAGES
To develop software, the object-oriented concepts need to be implemented in any high-level language. The high-level language that implements the concepts of object-oriented programming concepts is known as an object-oriented language (also called an OO language). In general, an object-oriented language must support all or some of these OO concepts. • Encapsulation and data hiding • Inheritance • Polymorphism and dynamic binding • All built-in and user-defined data types are objects • All operations are performed using the message passing techniques Depending on the extent to which they support OO concepts, the OO languages are classified into several categories: • Pure OO languages: Languages that not only support but also enforce all object-oriented concepts are called pure OO languages. In these languages, everything from character and punctuations to modules is treated as an object. Smalltalk, Eiffel and Ruby are the examples of pure OO languages. • Hybrid languages: Languages that support some (not all) of the OO concepts are called hybrid languages. Java, Python and C# are the examples of hybrid languages. • Multi-paradigm languages: Languages that support many programming paradigms (such as procedural programming, generic programming, etc.), one of which is object-oriented paradigm are called multi-paradigm languages. C++ is the example of multi-paradigm language. • Object-based languages: Languages that support the concept of abstract data types and also other OO concepts like encapsulation, data hiding and operator overloading are known as known as object-based languages. However, these languages do not support the concept of inheritance and dynamic binding. Ada and Modula-2 are the examples of object-based languages. An evaluation and comparison of some of the popularly used programming languages, based on the OO concepts they support, is listed in Table 1.1.
Objected-Oriented Methodology 11 Table 1.1 Comparison of Some Popular OO Languages OO concept Encapsulation and data hiding Inheritance Multiple inheritance Function overloading Operator overloading Dynamic binding Class variables and functions Pointer arithmetic Built-in data types are objects User-defined data types are objects All operations are performed using message passing technique
Eiffel Yes Yes
Smalltalk Yes Yes
Ruby Yes Yes
Java Yes Yes
C# Yes Yes
C++ Yes Yes
Python No Yes
Yes No Yes Yes No No Yes Yes
No No Yes Yes Yes No Yes Yes
No No Yes Yes Yes No Yes Yes
No Yes No Yes Yes No No Yes
No Yes Yes Yes Yes Yes No Yes
Yes Yes Yes Yes Yes Yes No No
Yes No Yes Yes No No Yes Yes
Yes
Yes
Yes
No
No
No
No
There is no fixed rule or principle based on which a particular language can be chosen for developing software. The decision of choice of language entirely depends on the characteristics and basic needs of the application to be developed, re-usability of the existing code, the impact of the organisation on the choice of the programming language and various other aspects.
1.8
APPLICATIONS OF OOP
Since 1960, when Simula-67 was developed, object-oriented paradigm has touched many major application areas of software development. Some of the application areas where OOP has been used to develop software are listed here. • Simulations and modelling: Simulation is the technique of representing the real-world entities with the help of a computer program. Simula-67 and Smalltalk are two object-oriented languages that are designed for making simulations. • User-interface design: Another popular application of OOP has been in the area of designing graphical user interfaces such as Windows. C++ is mainly used for developing user-interfaces. • Developing computer games: OOP is also used for developing computer games such as Diablo, Startcraft, Warcraft III and many more. These games offer virtual reality environments in which a number of objects interact with each other in complex ways to give the desired result. • Scripting: In recent years, OOP has also been used for developing HTML, XHTML and XML documents for the Internet. Python, Ruby and Java are the scripting languages based on objectoriented principles which are used for scripting. • Object databases: These days OOP concepts have also been introduced in database systems to develop a new DBMS named object databases. These databases store the data directly in the form of objects. However, these databases are not as popular as the traditional RDBMS. Some other areas of applications include office automation systems, decision support systems, Artificial Intelligence (AI) and expert systems, Neural networks and parallel programming, and Computer-Aided Design (CAD) systems.
12
Programming with Java
SUMMARY • A programming paradigm describes the structure of a program. In other words, it determines how the instructions are placed in a program. Each programming language follows one or the other programming paradigm. • In unstructured programming paradigm, all the instructions of a program were written one after the other in a single function and hence, suitable for writing only small and simple programs. • In procedural programming, programs are divided into different procedures (also known as functions, routines or subroutines) and each procedure contains a set of instructions that performs a specific task. It follows top-down approach. • Programs in procedural programming consist of a controlling procedure known as the main, which controls the execution of other procedures. • The procedural programming paradigm has certain limitations, which led to the development of object-oriented paradigm. • In object-oriented programming (OOP) paradigm, the programmers define not only the data, but also the operations (functions) that can be performed on it together under a single unit. It follows bottomup approach. • OOP is based on certain important concepts that include objects, classes, abstraction, encapsulation, inheritance, and polymorphism. • An object is a unit of structural and behavioural modularity that contains a set of properties (or data) as well as the associated functions. • A class is defined as a user-defined data type which contains the entire set of similar data and the functions that the objects possess. The process of creating objects from a class is known as instantiation. • Abstraction is a mechanism to hide irrelevant details and represent only the essential features so that one can focus on important things at a time. Abstraction can be of two types, namely, data abstraction and control abstraction. • Inheritance can be defined as the process whereby an object of a class acquires characteristics from the object of the other class. Inheritance can be of two types, namely, single inheritance and multiple inheritance. • Polymorphism (a Greek word meaning having multiple forms) is the ability of an entity such as a function or a message to be processed in more than one form. • Message passing is a process of interacting between different objects in a program. • The high-level language that implements the concepts of object-oriented programming concepts is known as an object-oriented (OO) language. For example, Eiffel, Smalltalk, Ruby, Java, C#, C++ and Python are OO languages. • OOP has been used to develop software in many areas including Simulations and Modelling, Userinterface design, Developing computer games, Scripting, Object Databases.
EXERCISES Fill in the blanks 1. In _______________ paradigm, all the instructions of a program were written one after the other in a single function. 2. In procedural programming, programs are divided into different __________. 3. An ___________ is a unit of structural and behavioural modularity that contains a set of properties (or data) as well as the associated functions.
Objected-Oriented Methodology 13 4. The data belonging to a particular class is known as its ___________ and the functions of the class are known as the ___________. 5. ______________ means hiding the details about the data and ___________ means hiding the implementation details Choose the correct option. 1. The process of creating objects from a class is known as ____________. (a) Object declaration (b) Variable declaration (c) Instantiation (d) Data abstraction 2. Which of these OOP concepts makes the reusability of code possible? (a) Inheritance (b) Encapsulation (c) Message passing (d) Data abstraction 3. The redefining of the base class method in the derived class is called___________. (a) Polymorphism (b) Method overriding (c) Abstraction (d) None of these 4. Which of the following programming languages falls in the category of Object based languages? (a) Python (b) Ada (c) C++ (d) Smalltalk 5. Which of the following object-oriented languages is designed for making simulations? (a) Simula-76 (b) Ruby (c) Python (d) None of these State true or false. 1. 2. 3. 4. 5.
OOP follows the bottom-up approach for designing the programs. Languages that support some of the object-oriented concepts are called pure OO languages. Classes in the object-oriented programming are also known as Abstract Data Types (ADT). Polymorphism is a process of interacting between different objects in a program. Simulation is the technique of representing the real-world entities with the help of a computer program.
Answer the following questions. 1. Write a short note on the evolution of various programming paradigms. 2. List some of the limitations of procedural programming paradigm. 3. What are the differences between object-oriented programming paradigm and procedural programming paradigm? 4. Differentiate between a class and an object. 5. Write a short note on message passing. 6. List some of the benefits of object-oriented programming.
14
Programming with Java
7. Define these terms. (a) Derived class (b) Parent class 8. Discuss the various OOP concepts in detail. 9. What are various types of OO languages? Give a brief comparison of some of the OO languages. 10. List a few areas of applications of OOP paradigm.
CHAPTER JAVA AND THE INTERNET
2
CHAPTER OBJECTIVES After reading this chapter, you will be able to: • Describe Java programming language and explain its features • Understand the role of Java compiler • Explain the Java runtime environment • Understand the simple Java program • Run Java application • Explain command line argument
2.1
INTRODUCTION
Java, initially named “Oak”, was developed by the team headed by James Gosling at Sun Microsystems, USA, in 1991. The first and foremost reason behind the development of Java was the need for a platform-independent and portable software to be embedded in the consumer’s electronic devices like remote controls, microwave ovens, etc. Second reason that led to the growth of Java is the Internet and World Wide Web as these media need portable and platform-independent programs. Gosling and other team members developed web applets using the new language that could run on all types of computers. During 1993, the first web browser, ‘HotJava’, was developed to locate and run applet programs. This development made Java language popular for the Internet. By 1996, Java became the general-purpose, object-oriented programming language which was used for Internet programming. Soon, Java became popular and many web browsers like Internet Explorer, Netscape Navigator incorporated the ability to run Java applets.
2.2
BASIC FEATURES OF JAVA PROGRAMMING LANGUAGE
Java is a third generation programming language which implements most of the concepts of OOPs. Java has become a popular language for Internet applications because of various features which are as follows. The important features of Java are as follows. • Simple: Java inherits the syntax of C/C++ and many of the OOPs features of C++ thus one who has understood the concepts of object-oriented language can learn Java with least effort. Moreover Java omits the complex and unreliable code of C and C++ like operator overloading, pointers, preprocessor header files. Java provides small and convenient ways to accomplish a given task.
16
Programming with Java • Interpreted: Unlike other languages Java uses two-stage system as it uses both compiler and interpreter for its program execution. First, the compiler converts the program code to bytecode which in turn is converted to machine code on any machine using the interpreter. The machine code so generated can be executed irrespective of the system on which it is being executed. • Architecture-neutral (platform-independent): This feature makes Java language very special. Java programs can run on any platform, that is, they can run on different CPU and on different operating system architectures. The bytecode produced by Java compiler can be run on any machine which has Java runtime environment. • Object-oriented language: Java is an object-oriented language as everything in Java is an object. The objects and classes contain the program code and data. The Java object model is easily extensible and classes can be used anywhere in the program in the form of packages. • Robust: Java is a robust language because of mainly two reasons. First, it is a strictly typed language that checks the code at the compile time. Secondly, Java does memory management in an effective way. In C++, the programmer has to manually deallocate the dynamic memory used by the objects. Java automatically deallocates free memory that is no longer referenced by the objects (with the help of garbage collector). • Distributed: Since Java is platform independent, it is suitable for developing applications for the networks. Java can handle TCP/IP protocols and hence applications developed in Java can access remote objects on Internet like any object on a local system. • Multithreaded: Java supports multithreaded programming which allows us to write a program that can perform more than one task simultaneously. User need not to wait for one program to finish one task, before starting next task. For example, user can listen an audio clip while downloading the applet. This feature helps to improve the performance of graphical applications. • High performance: As stated earlier, the Java program is converted to bytecode which is then converted to machine code using interpreter. Since bytecode is highly optimized, it enables the JVM to execute programs at much faster rate. • Dynamic: It is dynamic in nature, that is, Java programs can link to new class libraries, objects, methods, etc., at the run-time. Java language also provides the facility to include the functions of other languages like C and C++. They are referred to as native methods. These methods are also linked dynamically at run-time.
2.3
JAVA VERSUS C++
Both C++ and Java are object-oriented languages but they are very different from each other. Some of the features of C++ language were deliberately removed and some new features were added to make Java more flexible and reliable language. Some of the differences between Java and C++ are as follows. • Java does not support multiple inheritance of classes directly. • The concept of multithreading is supported by Java. • The destructor function in Java is replaced by finalize method. • The keyword typedef is not supported by Java.
Java and the Internet 17 Java does not support pointers, instead it uses implicit object references. The virtual keyword is not supported in Java. Java does not support the concept of global variables. Java supports exception handling in different way than C++. It provides finally clause for cleanup. • The non-primitive data types are allocated memory by using the new operator. • Java adds many features that are necessary for object-oriented programming.
• • • •
2.4
JAVA’S IMPORTANCE TO THE INTERNET
In recent years, Java has become popular language for the programs that are required to run on different systems. Java’s new innovation named “applet” has completely changed Internet programming. Applets are tiny programs that are designed in such a way that they can be transmitted over the Internet. They can be downloaded on demand and executed automatically by Java-compatible web browser. They are used to handle user input, data supplied by the server and simple functions that executes locally on the client machine. Applet is dynamic, self-executing program and is intelligent enough to change with the user inputs. Dynamic programs when downloaded and executed can cause serious harm to the computer as they may contain viruses like Trojan horse and malicious programs. These harmful programs may search the contents on local file system of the client computer and may gather private information like credit card numbers, passwords, etc. Earlier viruses were scanned before executing the downloaded program, but Java has resolved the issue by confining the Java programs to Java execution environment only.
2.5
JAVA COMPILER
In most programming languages, the program is converted to machine code either by using compiler or interpreter. The machine code so generated is machine dependent, that is, it may not run on the machine other than the one on which it is generated. Unlike in case of other programming languages, the Java compiler does not convert source code to machine code, it converts source code to a special intermediate code known as bytecode. The bytecode so generated is in the form of class files that can be interpreted. The command used for compilation in Java is javac which converts the corresponding Java file into class file. The bytecode is machine independent, that is, it can be run on any machine with the help of Java virtual machine (JVM) which is discussed in the next section.
Figure 2.1 Compilation of a Java Program
2.6
JAVA VIRTUAL MACHINE CONCEPTS
As discussed earlier, Java uses both compiler and interpreter. Source code written in Java is compiled to generate bytecode and then this bytecode is interpreted to machine instructions for specific machine. The bytecode generated by the compiler is not machine specific. It is generated for the virtual machine that exists only inside the computer memory known as Java Virtual Machine
18
Programming with Java
(JVM). This virtual machine is designed in such a way that it can be implemented on the top of any existing processor and itself acts as virtual processor chip. It hides the underlying operating system details from Java applications.
Figure 2.2 Execution of a Java Program
2.7
JDK (JAVA DEVELOPMENT KIT)
JDK consists of various tools that are used to develop and execute Java programs. The tools included in JDK are listed in Table 2.1. Table 2.1 Tools in Java Development Kit Tool javac java javadoc javah javap jdb appletviewer
2.8
Function Java compiler that converts source code to Java bytecode Java interpreter that interprets class files generated by java compiler and converts it to machine code Document generator which automatically generates documentation from source code Generates C headers and a stub generator used for writing native methods The class file disassembler which enables to convert bytecode files to a program description Java debugger which helps in tracking errors in the program Used for running and debugging Java applets without a web browser
A FIRST LOOK AT JAVA PROGRAM
Let us start learning Java with a simple Java program that prints a string on the screen. Example 2.1
A simple Java program
class Sample { public static void main (String args[]) { System.out.println(“Welcome to Java Programming”); System.out.println(“Its easy and simple.”); } }
Though this program is the simplest one, it includes the basic features that every Java program has. Let us now look at the features one by one. Class Definition The first statement class Sample declares a class where class is a keyword and Sample is the identifier that indicates the name of the class. The opening and closing curly braces ‘{ }’ enclose the definition of a class.
Java and the Internet 19 The Main Statement The statement public static void main (String args[]) indicates the main method. This method is the point where the execution of Java program begins. Since, it is the startup point of any Java program, it is the most essential part of any Java program. This statement has keywords, namely, public, static and void. The descriptions of these keywords are as follows. • public: It is an access specifier which specifies that the main method is accessible to all other classes. • static: The main method is declared static which specifies that this method belongs to the entire class. Interpreter uses this method before the creation of objects. • void: The void keyword specifies that the main method does not return a value. The pair of parentheses contains the declaration of the parameters of the methods. In the above statement, the String args[ ] declares a parameter args, that contains an array of objects of the class type String. The Output Statement The statements System.out.println(“Welcome to Java Programming.”); and System.out.println(“Its easy and simple.”); are used to display information on the standard output device, that is, the println() is a method of the out object, which is the static member of class System. These statements will display the following strings on the monitor. Welcome to Java Programming. Its easy and simple. The statements will be printed in separate lines as the method println() appends a newline character at the end of the string. However, if we use print() method instead of println() newline character is not appended at the end of the string. Note that like C++, every statement in Java must end with a semicolon.
2.9
RUNNING JAVA APPLICATIONS
A program can be created using any text editor. Nowadays, there are several text editors available for writing programs like Notepad, Jcreator, etc. After creating the file, save the file with the name .Java. The name of the file must be the same as that of the class name containing the main() method. Once the file is created, it can be compiled to generate the bytecode using Java compiler javac as given here. javac Sample.java If the source code is error free then the compiler creates a file containing the bytecode and the file will be named as .class. In our example, the name of file will be Sample.class. Even though after compilation, the source code is converted into its equivalent bytecode, it cannot be executed. To execute this bytecode, it needs to be converted to machine code using the interpreter. The command for converting bytecode to machine code and run it is as follows: java Sample After giving this command, the interpreter searches for the main() method in the source code and starts executing the instructions written in this method and displays the corresponding output.
20
Programming with Java
2.10
COMMAND LINE ARGUMENTS
Like C++, Java enables to pass arguments to the main() method also. These arguments are passed by typing them after the program name on the command line. Hence, these arguments are known as command line arguments. They help in providing data to the program. As stated earlier, the argument named as args of String type is passed to the main method. It is this argument which will receive any data passed to the program through command line. Example 2.2
A program to demonstrate the use of command line arguments
class CommandLineArg { public static void main(String args[]) { System.out.println("The arguments entered are: "); int a; for (a=0;a