Programming with JAVA · Java compiler works. Chapter 3 introduces various data types, variables,...

16

Transcript of Programming with JAVA · Java compiler works. Chapter 3 introduces various data types, variables,...

Page 1: Programming with JAVA · Java compiler works. Chapter 3 introduces various data types, variables, constants that constitute the basic elements of a language. Chapter 4 covers the
Page 2: Programming with JAVA · Java compiler works. Chapter 3 introduces various data types, variables, constants that constitute the basic elements of a language. Chapter 4 covers the

Programming with

JAVA

VIKAS® PUBLISHING HOUSE PVT LTD

Rohit KhuranaFounder and CEO

ITLESL, Delhi

Page 3: Programming with JAVA · Java compiler works. Chapter 3 introduces various data types, variables, constants that constitute the basic elements of a language. Chapter 4 covers the

VIKAS® PUBLISHING HOUSE PVT LTDE-28, Sector-8, Noida-201301 (UP) IndiaPhone: +91-120-4078900 • Fax: +91-120-4078999Registered 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 : 82, Park Street, Kolkata-700017 • Ph. 033-22837880• Mumbai : 67/68, 3rd Floor, Aditya Industrial Estate, Chincholi Bunder, Malad (West),

Mumbai-400064 • Ph. +91-22-28772545, 28768301• Patna : Flat No. 101, Sri Ram Tower, Besides Chiraiyatand Over Bridge,

Kankarbagh Main Road, Kankarbagh, Patna - 800 020, (Bihar)

Programming with JavaISBN: 978-93259-7839-3

Vikas® is the registered trademark of Vikas Publishing House Pvt LtdCopyright © 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.

Page 4: Programming with JAVA · Java compiler works. Chapter 3 introduces various data types, variables, constants that constitute the basic elements of a language. Chapter 4 covers the

Dedication

I would like to dedicate this book to my uncle,

Shri G K Jajufor 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.

Page 5: Programming with JAVA · Java compiler works. Chapter 3 introduces various data types, variables, constants that constitute the basic elements of a language. Chapter 4 covers the
Page 6: Programming with JAVA · Java compiler works. Chapter 3 introduces various data types, variables, constants that constitute the basic elements of a language. Chapter 4 covers the

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 OrganizationThe 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.

Page 7: Programming with JAVA · Java compiler works. Chapter 3 introduces various data types, variables, constants that constitute the basic elements of a language. Chapter 4 covers the

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.

AcknowledgementsIn 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 KhuranaFounder and CEO

ITLESL, Delhi

vi Preface

Page 8: Programming with JAVA · Java compiler works. Chapter 3 introduces various data types, variables, constants that constitute the basic elements of a language. Chapter 4 covers the

Preface v

Chapter 1 Objected-Oriented Methodology 1 – 141.1 Introduction 11.2 Paradigms of Programming Languages 11.3 Evolution of Objected-oriented Methodology 21.4 Comparison of Object-Oriented and Procedure-Oriented Approach 21.5 Basic Concepts of OO Approach 5

1.5.1 Objects 51.5.2 Classes 51.5.3 Abstraction 71.5.4 Encapsulation 71.5.5 Inheritance 71.5.6 Polymorphism 81.5.7 Method Overriding 81.5.8 Message Passing 9

1.6 Benefits of OOP 91.7 Introduction to Common OO Languages 101.8 Applications of OOP 11Summary 12Exercises 12

Chapter 2 Java and the Internet 15 – 222.1 Introduction 152.2 Basic Features of Java Programming Language 152.3 Java versus C++ 162.4 Java’s Importance to the Internet 172.5 Java Compiler 172.6 Java Virtual Machine Concepts 172.7 JDK (Java Development Kit) 182.8 A First Look at Java Program 182.9 Running Java Applications 192.10 Command Line Arguments 20Summary 20Exercises 21

CONTENTS

Page 9: Programming with JAVA · Java compiler works. Chapter 3 introduces various data types, variables, constants that constitute the basic elements of a language. Chapter 4 covers the

viii Contents

Chapter 3 Programming Elements of Java 23 – 403.1 Introduction 233.2 Character Set 233.3 Tokens 23

3.3.1 Keywords 243.3.2 Identifiers 243.3.3 Constants 243.3.4 Operators 263.3.5 Punctuators 26

3.4 Structure of a Java Program 263.5 Data Types 27

3.5.1 Primitives Data Types 273.5.2 Non-Primitive Data Types 28

3.6 Variables 293.7 Type Casting 303.8 Operators and Operations 32

3.8.1 Arithmetic Operators 323.8.2 Increment and Decrement Operators 333.8.3 Relational Operators 333.8.4 Logical Operators 343.8.5 Conditional Operator 343.8.6 Assignment Operators 353.8.7 Other Operators 353.8.8 Operators Precedence and Associativity 36

Summary 37Exercises 38

Chapter 4 Control Statements 41 – 584.1 Introduction 414.2 Selection Statements 414.3 Iteration Statements 48

4.3.1 The for Loop 484.3.2 The while Loop 484.3.3 The do-while Loop 51

4.4 Jump Statements 534.5 Labeled Loops 54Summary 56Exercises 56

Chapter 5 Classes and Objects 59 – 805.1 Introduction 595.2 Class Fundamentals 59

Page 10: Programming with JAVA · Java compiler works. Chapter 3 introduces various data types, variables, constants that constitute the basic elements of a language. Chapter 4 covers the

Contents ix

5.2.1 Introducing Methods 605.3 Creating Objects 615.4 Accessing Members of a Class 625.5 Assigning Object Reference Variables 635.6 Argument Passing 64

5.6.1 Call-by-Value 645.6.2 Call-by-Reference 65

5.7 Static Variables and Methods 665.8 Method Overloading 675.9 Constructors 68

5.9.1 Parameterized Constructors 695.9.2 Overloading Constructor 70

5.10 Using Objects as Parameters 715.11 Returning Objects 725.12 Recursion 735.13 Inner Classes 755.14 this Keyword 755.15 Garbage Collection 77

5.15.1 The finalize() Method 77Summary 78Exercises 78

Chapter 6 Arrays, Strings and Vectors 81 – 976.1 Introduction 816.2 Arrays 81

6.2.1 Single-dimensional Arrays 826.2.2 Multi-dimensional Arrays 84

6.3 Strings 886.3.1 String Class 886.3.2 StringBuffer Class 89

6.4 Vectors 916.5 Wrapper Classes 92Summary 95Exercises 95

Chapter 7 Inheritance and Polymorphism 99 – 1197.1 Introduction 997.2 Inheritance Basics 99

7.2.1 Defining a Subclass 1007.3 Types of Inheritance 100

7.3.1 Single Inheritance 1007.3.2 Hierarchical Inheritance 102

Page 11: Programming with JAVA · Java compiler works. Chapter 3 introduces various data types, variables, constants that constitute the basic elements of a language. Chapter 4 covers the

x Contents

7.3.3 Multilevel Inheritance 1047.3.4 Multiple Inheritance 106

7.4 Visibility Controls (Access Controls) 1067.5 Subclass Constructor 1087.6 Method Overriding 1107.7 Run-Time Polymorphism or Dynamic Method Dispatch 1117.8 Using final Keyword 112

7.8.1 Final Variables 1137.8.2 Final Methods 1137.8.3 Final Classes 114

7.9 Abstract Methods and Classes 115Summary 116Exercises 117

Chapter 8 Interface 121 – 1328.1 Introduction 1218.2 Defining Interface 1218.3 Implementing Interface 1228.4 Extending Interfaces 1248.5 Variables in Interfaces 1258.6 Interface and Abstract Classes 1268.7 Extends and Implements Together 127Summary 129Exercises 129

Chapter 9 Packages 133 – 1479.1 Introduction 1339.2 Packages 1339.3 Java API Packages 133

9.3.1 Package Naming 1359.4 Defining Packages 1359.5 CLASSPATH 1369.6 Accessibility of Packages 1389.7 Using Package Members 1389.8 Adding a Class 1409.9 Hiding a Class 1419.10 Packages and Visibility Controls 142Summary 145Exercises 145

Chapter 10 Exception Handling 149 – 16510.1 Introduction 149

Page 12: Programming with JAVA · Java compiler works. Chapter 3 introduces various data types, variables, constants that constitute the basic elements of a language. Chapter 4 covers the

Contents xi

10.2 Exceptions 14910.3 Exception Handling 15010.4 Types of Exceptions 15110.5 Using try and catch blocks 152

10.5.1 Multiple catch blocks 15310.5.2 Nested try blocks 155

10.6 Using finally Block 15610.7 Using throw Keyword 15810.8 Using throws Keyword 15910.9 Creating Your Own Exceptions 160Summary 161Exercises 162

Chapter 11 Multithreading 167 – 19711.1 Introduction 16711.2 Concept of Threads 16711.3 Main Thread 16811.4 Creating Threads 169

11.4.1 Extending Threads 16911.4.2 Implementing Runnable Interface 171

11.5 Life Cycle of a Thread 17211.6 Thread Methods 174

11.6.1 Using yield(), sleep() and stop() method 17411.6.2 Using isAlive() and join() method 176

11.7 Threads Priority 17911.8 Synchronization of Threads 181

11.8.1 Synchronizing Methods 18111.8.2 Synchronizing Statements 18411.8.3 Deadlock 185

11.9 Inter-Thread Communication 18811.10 Suspending, Resuming and Stopping Threads 192Summary 194Exercises 195

Chapter 12 I/O in Java 199 – 22812.1 Introduction 19912.2 I/O Basics 19912.3 Streams 19912.4 Stream Classes 200

12.4.1 Byte Stream Classes 20112.4.2 Character Stream Classes 204

12.5 The PrintStream Class 208

Page 13: Programming with JAVA · Java compiler works. Chapter 3 introduces various data types, variables, constants that constitute the basic elements of a language. Chapter 4 covers the

xii Contents

12.6 Predefined streams 20912.7 Reading From and Writing to Console 20912.8 Reading and Writing Files 21012.9 Data Streams 213

12.9.1 The DataInputStream Class 21312.9.2 The DataOutputStream Class 214

12.10 The StringTokenizer Class 21612.11 The StreamTokenizer Class 21812.12 The transient and volatile Modifiers 22112.13 Using instanceof Operator 22112.14 Native Methods 223Summary 225Exercises 226

Chapter 13 Java Applets 229 – 25213.1 Introduction 22913.2 Applet Fundamentals 229

13.2.1 Life Cycle of an Applet 23013.3 Steps to Build an Applet 231

13.3.1 Creating an Applet code 23113.3.2 Creating an Executable Applet 23213.3.3 Designing an HTML Document 23213.3.4 Running the Applet 234

13.4 Passing Parameters to Applets 23513.5 getDocumentBase() and getCodeBase()  236

13.6 AppletContext and showDocument()  237

13.7 Working with Graphics 23813.7.1 Using Graphics Class 23813.7.2 Using Color class 24313.7.3 Using Font class 24513.7.4 Using Image class 247

13.8 Adding Sound to an Applet 249Summary 250Exercises 250

Chapter 14 Event Handling 253 – 26614.1 Introduction 25314.2 Events 25314.3 Event Handling Model 253

14.3.1 Java 1.0 Event Model 25414.3.2 Delegation Event Model 254

14.4 Event Handling 255

Page 14: Programming with JAVA · Java compiler works. Chapter 3 introduces various data types, variables, constants that constitute the basic elements of a language. Chapter 4 covers the

Contents xiii

14.4.1 Event Classes 25514.4.2 Event Sources 25614.4.3 Event Listener Interfaces 25714.4.4 Adapter Classes 263

Summary 265Exercises 265

Chapter 15 Abstract Window Toolkit 267 – 28215.1 Introduction 26715.2 AWT: Working with Windows Graphics and Text 26715.3 Using AWT Controls 26815.4 AWT Layout Managers 275Summary 280Exercises 280

Chapter 16 Java Swing 283 – 34516.1 Introduction 28316.2 Features of Swing 283

16.2.1 Lightweight Components 28316.2.2 Pluggable Look and Feel 284

16.3 The Swing Packages 28416.4 Swing Components and Containers 284

16.4.1 Swing Components (JComponent Class) 28416.4.2 Swing Containers 285

16.5 Creating a Swing Applet and Application 28516.6 Layout Manager 28816.7 User Interface Components 288

16.7.1 JApplet  288

16.7.2 JFrame  288

16.7.3 Label 29016.7.4 Button 29016.7.5 ToggleButton 29016.7.6 CheckBox 29116.7.7 TextField 29116.7.8 TextArea 29116.7.9 RadioButton 29216.7.10 Panel 29216.7.11 ScrollPane 29216.7.12 List 29316.7.13 ComboBox 29716.7.14 ScrollBar 29916.7.15 Menu Bar and Menus 300

Page 15: Programming with JAVA · Java compiler works. Chapter 3 introduces various data types, variables, constants that constitute the basic elements of a language. Chapter 4 covers the

xiv Contents

16.7.16 Toolbars 30516.8 Programming using Panes 307

16.8.1 Layered Panes 30716.8.2 Split Panes 30816.8.3 Tabbed Panes 311

16.9 Working with Layouts 31216.9.1 Flow Layout 31316.9.2 Border Layout 31416.9.3 Grid Layout 31616.9.4 Card Layout 31716.9.5 Grid Bag Layout 320

16.10 Windows 32316.11 Internal Frame 32416.12 Using Dialogs 32616.13 JOptionPane   329

16.13.1 Message Dialog Box 32916.13.2 Input Dialog Box 33116.13.3 Confirmation Dialog Box 33316.13.4 Option Dialog Box 335

16.14 JTable  337

16.15 Timer  339

16.16 JProgressBar  340

16.17 JSlider  341

Summary 342Exercises 343

Chapter 17 Java Database Connectivity (JDBC) 347 – 35817.1 Introduction 34717.2 Overview of JDBC 34717.3 JDBC-ODBC Bridge 34817.4 JDBC Implementation 349

17.4.1 The DriverManager Class 34917.4.2 The Connection Interface 34917.4.3 The Statement Interface (Handling database

queries statically) 35017.4.4 The ResultSet Interface 35017.4.5 The PreparedStatement Interface (Handling Database

Queries Dynamically) 35317.4.6 The ResultSetMetaData Interface 354

Summary 356Exercises 356

Page 16: Programming with JAVA · Java compiler works. Chapter 3 introduces various data types, variables, constants that constitute the basic elements of a language. Chapter 4 covers the

Programming With Java

Publisher : SChand Publications ISBN : 9789325978393 Author : Rohit Khurana

Type the URL : http://www.kopykitab.com/product/11722

Get this eBook

21%OFF