Java Free Book Rel 1 Upto V12

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 660

Java Free Book

By. Chidambaram.S
Book starts with basic concepts and
covers the features of Java versions
5,6,7,8,9,10,11 and 12

One book to learn Java from beginning to advanced


concepts

Even beginner can start to learning Java

Concepts are explained in simple manner along with simple


programs

The book is free copy to all


About me and this book

I am software professional and would like to share my knowledge


to all by teaching and writing books.

Core Java knowledge is very essential, Because strong Core Java


knowledge is very important to go further

You can start anything directly without strong knowledge of Core


Java. The result would be even you can accomplish your tasks,
but without confidence.

Real confidence is real success

This book is the free copy for learning purpose and you can
share to any one freely without modifying the original content.

Connect me using below mail

[email protected]
The book work is provided “as is". Because of the possibility of human or
mechanical error we make no guarantees or warranties as to the accuracy, adequacy
or completeness of or results to be obtained from using the work, including any
information that can be accessed through the work via hyperlink or otherwise, and
expressly disclaim any warranty, express or implied.

We do not guarantee the accuracy, adequacy, or completeness of any information and


is not responsible for any errors or omissions or the results obtained from the
use of the information in this book.

Oracle and Java are registered trademarks of oracle corporation and/or its
affiliates. All other trademarks and logos are the property of their respective
owners,

This book is the free copy for learning purpose and you can share to any one
freely without modifying the original content.

You are agree to above terms and conditions if you continue to read this book.
Table of Contents

About me and this book ....................................................................................................................................................... 3

Chapter 1 - Java Technology ................................................................................................................................................... 22

What is Java ........................................................................................................................................................................ 22

Java Standards .................................................................................................................................................................... 23

Various types of programming approaches ....................................................................................................................... 23

History of C and C++ ........................................................................................................................................................... 23

Java’s Magic........................................................................................................................................................................ 23

JVM and JIT ......................................................................................................................................................................... 26

What is program? ............................................................................................................................................................... 26

Two Paradigms ................................................................................................................................................................... 26

Chapter 2 - OOPS Concepts .................................................................................................................................................... 27

Abstraction ......................................................................................................................................................................... 27

Encapsulation ..................................................................................................................................................................... 28

Polymorphism .................................................................................................................................................................... 30

Inheritance ......................................................................................................................................................................... 33

Chapter 3 - Class and Program Structure ............................................................................................................................... 35

What is Class? ..................................................................................................................................................................... 35

What is an object? .............................................................................................................................................................. 37

What is Method? ................................................................................................................................................................ 38

Constructor ........................................................................................................................................................................ 38
Instance variables ............................................................................................................................................................... 38

Instance Method ................................................................................................................................................................ 41

Simple Program with explanation ...................................................................................................................................... 42

Chapter 4 - Association, Aggregation, Composition ............................................................................................................... 45

Aggregation ........................................................................................................................................................................ 45

Composition ....................................................................................................................................................................... 45

Chapter 5 - Lexical issues ........................................................................................................................................................ 47

White space ........................................................................................................................................................................ 47

Identifiers ........................................................................................................................................................................... 47

Literals ................................................................................................................................................................................ 47

Comments .......................................................................................................................................................................... 48

Chapter 6 - Operators ............................................................................................................................................................. 53

Types of operators. ............................................................................................................................................................ 53

Basic arithmetic operator .............................................................................................................................................. 54

Arithmetic Assignment Operator ................................................................................................................................... 54

Increment and decrement Operator ............................................................................................................................. 54

Bitwise Operator ............................................................................................................................................................ 55

Bitwise Assignment Operator ........................................................................................................................................ 56

Relational operators ...................................................................................................................................................... 56

Boolean Logical operators ............................................................................................................................................. 56

Ternary operator ............................................................................................................................................................ 57

Operator precedence ......................................................................................................................................................... 57

Difference between Logical and short circuit and.............................................................................................................. 58

Chapter 7 - Data Type ............................................................................................................................................................. 60

Various types of variable declaration ................................................................................................................................. 61

Three Scopes and Life time of Variable .............................................................................................................................. 62


Instance Variables .............................................................................................................................................................. 62

Local Variable (Method Scope) .......................................................................................................................................... 62

Chapter 8 - Type Conversion .................................................................................................................................................. 64

Automatic type conversion ................................................................................................................................................ 64

Automatic type promotion ................................................................................................................................................. 65

Type promotion Rules ........................................................................................................................................................ 66

Chapter 9 - Selection Statements ........................................................................................................................................... 67

Java Selection Statements .................................................................................................................................................. 67

if ..................................................................................................................................................................................... 67

if else .............................................................................................................................................................................. 67

if..else if .......................................................................................................................................................................... 68

else if ladder................................................................................................................................................................... 68

Nested if ......................................................................................................................................................................... 69

switch ............................................................................................................................................................................. 70

Chapter 10 - Iteration Statement ........................................................................................................................................... 72

while(condition) ............................................................................................................................................................. 72

do..while ........................................................................................................................................................................ 72

for each .......................................................................................................................................................................... 74

for each two dimensional array syntax .......................................................................................................................... 75

Jumping Statements ...................................................................................................................................................... 75

Chapter 11 - Input from user .................................................................................................................................................. 77

Command line Input ........................................................................................................................................................... 77

Interactive input ................................................................................................................................................................. 78

Chapter 12 - Array .................................................................................................................................................................. 80

Array ................................................................................................................................................................................... 80

One dimensional array ................................................................................................................................................... 80


Two dimensional array................................................................................................................................................... 81

Three dimensional array ................................................................................................................................................ 82

Four dimensional array .................................................................................................................................................. 82

Jagged arrays ................................................................................................................................................................. 82

Assigning arrays ............................................................................................................................................................. 83

Chapter 13 - Call by value, Call by reference, and Constructor .............................................................................................. 87

Call by reference - Passing and returning objects .............................................................................................................. 87

Call by value ....................................................................................................................................................................... 88

Default Constructor ............................................................................................................................................................ 89

Constructor with parameters ............................................................................................................................................. 90

Chapter 14 - Modifiers, Static block, Anonymous object and this keyword........................................................................... 91

Access Modifier .................................................................................................................................................................. 91

public ............................................................................................................................................................................. 91

private ............................................................................................................................................................................ 91

default ............................................................................................................................................................................ 91

protected ....................................................................................................................................................................... 91

Non Access Modifiers ......................................................................................................................................................... 91

Using final (Non access modifier) ....................................................................................................................................... 92

Static variable ..................................................................................................................................................................... 93

Static method ..................................................................................................................................................................... 95

Anonymous Object ............................................................................................................................................................. 97

this keyword ....................................................................................................................................................................... 98

Chapter 15 - Inheritance and Delegation............................................................................................................................. 100

Inheritance ....................................................................................................................................................................... 100

Single Inheritance ........................................................................................................................................................ 101

Multilevel Inheritance .................................................................................................................................................. 101


Multiple Inheritance .................................................................................................................................................... 101

Hierarchical Inheritance ............................................................................................................................................... 101

Hybrid Inheritance ....................................................................................................................................................... 103

Why java does not support multiple ............................................................................................................................ 103

About Multilevel .......................................................................................................................................................... 103

Benefits of multilevel ................................................................................................................................................... 104

super ................................................................................................................................................................................ 104

Usage of super ............................................................................................................................................................. 104

Access super class variable .......................................................................................................................................... 104

Access super class constructors ................................................................................................................................... 104

Access super class methods ......................................................................................................................................... 105

Method overriding ....................................................................................................................................................... 105

Dynamic Method Dispatch........................................................................................................................................... 106

Object creation for super class and sub classes ........................................................................................................... 106

Allowed casting syntaxes between sub class and superclass ...................................................................................... 106

How can assign super class object in subclass reference?........................................................................................... 107

Delegation ........................................................................................................................................................................ 107

Chapter 16 - Abstract Classes and Interfaces ....................................................................................................................... 109

Abstract class.................................................................................................................................................................... 109

Interface ........................................................................................................................................................................... 111

Difference between interface and abstract class: ....................................................................................................... 111

Object creation for interface ....................................................................................................................................... 112

Chapter 17 - Package and Import Statement ....................................................................................................................... 113

Package ............................................................................................................................................................................ 113

What is package? ......................................................................................................................................................... 113

Access Protection Table ............................................................................................................................................... 114


Batch file ...................................................................................................................................................................... 116

Importing packages .......................................................................................................................................................... 116

Static import (added in 1.5) ............................................................................................................................................. 117

Chapter 18 - Class Loader ..................................................................................................................................................... 118

Bootstrap Class Loader ..................................................................................................................................................... 118

Extensions Class Loader ................................................................................................................................................... 118

Application class loader / System Class Loader ................................................................................................................ 118

Class loader delegation hierarchy .................................................................................................................................... 119

Clear the classpath ........................................................................................................................................................... 119

How to set the environment class variable ...................................................................................................................... 119

Chapter 19 - Auto Box and Auto Unbox, Transient, Volatile and instance of ....................................................................... 123

AutoBox ............................................................................................................................................................................ 123

Auto unboxing .................................................................................................................................................................. 123

Transient .......................................................................................................................................................................... 124

Volatile modifier ............................................................................................................................................................... 124

instanceof ......................................................................................................................................................................... 124

Chapter 20 - Generic classes ................................................................................................................................................. 126

Generic Class Object Creation .......................................................................................................................................... 126

Diamond Operator <> in Generics (Added in 1.7) ............................................................................................................ 127

Bounded and unbounded wildcards in generics .............................................................................................................. 130

Chapter 21 - Inner Class, A variable can return an object and Factory Method .................................................................. 132

Inner Class ........................................................................................................................................................................ 132

Types of inner class ...................................................................................................................................................... 132

A Variable can return an object ....................................................................................................................................... 137

Factory Method ................................................................................................................................................................ 137

Chapter 22 - Java internationalization and Regular expression concepts ............................................................................ 138


Resource Bundle .............................................................................................................................................................. 138

ListResourceBundle .......................................................................................................................................................... 141

Regular Expressions.......................................................................................................................................................... 143

Regular Expression example ........................................................................................................................................ 144

Chapter 23 - Exception Handling .......................................................................................................................................... 145

Exception .......................................................................................................................................................................... 145

Benefits of Exception ................................................................................................................................................... 145

Types of Exception ........................................................................................................................................................... 146

Unchecked Runtime Exception .................................................................................................................................... 146

Checked Compile time Exception ................................................................................................................................ 146

Caught Exception ......................................................................................................................................................... 146

Uncaught Exception ..................................................................................................................................................... 146

Sub classes of RuntimeException ................................................................................................................................. 146

Checked Exception classes ........................................................................................................................................... 149

Five keywords to manage exceptions .............................................................................................................................. 149

try .. catch .................................................................................................................................................................... 150

finally............................................................................................................................................................................ 150

throw............................................................................................................................................................................ 150

throws .......................................................................................................................................................................... 151

Try usage types................................................................................................................................................................. 152

Nested Try .................................................................................................................................................................... 152

Multiple try .................................................................................................................................................................. 153

Try and Finally .............................................................................................................................................................. 153

Try with multiple catch ................................................................................................................................................ 154

try catch - with multiple exception in one catch (Added in 1.7) .................................................................................. 154

try with resources (Added in 1.7) ................................................................................................................................ 155


Own Exceptions ................................................................................................................................................................ 156

Throwable class methods ................................................................................................................................................. 157

Chapter 24 - Multithreaded Programming and ThreadGroup .............................................................................................. 158

Thread .............................................................................................................................................................................. 158

States of Thread ............................................................................................................................................................... 158

Benefits of Threads .......................................................................................................................................................... 159

Single threaded system .................................................................................................................................................... 159

Types of multitasking ....................................................................................................................................................... 159

Process based or Multitasking Processed ........................................................................................................................ 160

Thread based or Multitasking threads ............................................................................................................................. 160

Difference between thread based and process based ..................................................................................................... 160

Thread creation ................................................................................................................................................................ 160

Thread Priorities and Context switching .......................................................................................................................... 162

Preemptive multitasking .................................................................................................................................................. 162

Synchronization ................................................................................................................................................................ 163

Messaging or Inter Thread communication ..................................................................................................................... 164

CountDownLatch .............................................................................................................................................................. 179

Semaphore ....................................................................................................................................................................... 186

CyclicBarrier ..................................................................................................................................................................... 186

ThreadGroup .................................................................................................................................................................... 191

Chapter 25 - BigDecimal, String and String Buffer ................................................................................................................ 192

String and StringBuffer Handling ...................................................................................................................................... 193

java.lang.String............................................................................................................................................................. 193

Differences between String and StringBuffer ............................................................................................................. 193

StringBuffer ...................................................................................................................................................................... 199

Chapter 26 - Java Database Programming............................................................................................................................ 202


Database concepts ........................................................................................................................................................... 202

SQL ................................................................................................................................................................................... 203

ResultSet .......................................................................................................................................................................... 204

Statements ....................................................................................................................................................................... 204

Four types of JDBC Drivers ............................................................................................................................................... 204

1. JDBC-ODBC Bridge Driver (Type-1): ......................................................................................................................... 204

Advantages of Type 1 Driver ........................................................................................................................................ 205

2. Native-API Driver (Type-2) ....................................................................................................................................... 206

3. Net-Protocol Pure Java Driver (Type-3) ................................................................................................................... 206

4. Native-Protocol Pure Java Driver (Type-4) ............................................................................................................... 207

DSN Creation(Data Source Name) ............................................................................................................................... 208

What is Procedure ............................................................................................................................................................ 208

Three statements in java.sql ............................................................................................................................................ 210

Difference between Statement and PreparedStatement ............................................................................................ 210

ResultSet Cursor Types ................................................................................................................................................ 211

ResultSet Concurrency ................................................................................................................................................. 212

ResultSet Methods(I) ................................................................................................................................................... 212

int getRow() ................................................................................................................................................................. 212

Create table using by user input in oracle ................................................................................................................... 215

Chapter 27 - javax.sql ........................................................................................................................................................... 259

GlassFish server ........................................................................................................................................................... 264

GlassFish Server Admin console .................................................................................................................................. 269

Chapter 28 - java.util package .............................................................................................................................................. 271

Collection ......................................................................................................................................................................... 271

Legacy Classes .............................................................................................................................................................. 271

Modern Collections Framework .................................................................................................................................. 272


ArrayList ........................................................................................................................................................................... 274

ListIterator ........................................................................................................................................................................ 276

Iterator ............................................................................................................................................................................. 276

LinkedList.......................................................................................................................................................................... 279

LinkedHashSet .................................................................................................................................................................. 281

Hashtable ......................................................................................................................................................................... 284

HashSet ............................................................................................................................................................................ 284

PriorityQueue ................................................................................................................................................................... 285

TreeSet ............................................................................................................................................................................. 287

HashMap .......................................................................................................................................................................... 290

Constructors................................................................................................................................................................. 290

HashMap internal structure ............................................................................................................................................. 290

TreeMap ........................................................................................................................................................................... 294

LinkedHashMap ................................................................................................................................................................ 295

IdentityHashMap .............................................................................................................................................................. 297

IdentityHashMap constructors .................................................................................................................................... 297

SortedMap........................................................................................................................................................................ 298

Chapter 29 - Legacy classes in collections ............................................................................................................................ 301

Vector ............................................................................................................................................................................... 301

Stack ................................................................................................................................................................................. 303

Hashtable ......................................................................................................................................................................... 306

Properties ......................................................................................................................................................................... 308

Chapter 30 - java.util Utility classes ...................................................................................................................................... 312

java.util.Date class ............................................................................................................................................................ 312

How to format the Date? ............................................................................................................................................. 312

java.util.Arrays ................................................................................................................................................................. 315


Formatter ......................................................................................................................................................................... 317

Formatter with Calendar object................................................................................................................................... 319

Observer and Observable ................................................................................................................................................. 324

Random ............................................................................................................................................................................ 327

Scanner ............................................................................................................................................................................. 329

Constructor .................................................................................................................................................................. 329

StringTokenizer ................................................................................................................................................................ 333

StringTokenizer constructors ....................................................................................................................................... 333

Chapter 31- java.lang Package .............................................................................................................................................. 338

java.lang.Number ............................................................................................................................................................. 338

Double class ..................................................................................................................................................................... 342

Double Constructors .................................................................................................................................................... 342

Illustrates Double class Fields ...................................................................................................................................... 342

Boolean class .................................................................................................................................................................... 351

Character class ................................................................................................................................................................. 353

java.lang.System class ...................................................................................................................................................... 358

Methods of java.lang.Class ............................................................................................................................................... 363

Reflection ......................................................................................................................................................................... 364

Cloning.............................................................................................................................................................................. 373

Math class static methods................................................................................................................................................ 376

Garbage Collection ........................................................................................................................................................... 380

Runtime class exec() ......................................................................................................................................................... 381

java.lang.Object class ....................................................................................................................................................... 382

Chapter 32 - java.net Package .............................................................................................................................................. 384

Simple Chat ...................................................................................................................................................................... 384

InetAddress ...................................................................................................................................................................... 387


Two Way Chat .................................................................................................................................................................. 389

Socket Methods ............................................................................................................................................................... 392

Mulitway Chat Application ............................................................................................................................................... 396

Datagram .......................................................................................................................................................................... 405

Two Way Chat - using DatagramSocket and DatagramPacket ......................................................................................... 406

URL and URLConnetion .................................................................................................................................................... 412

ServerSocket with IE as a client ........................................................................................................................................ 413

Chapter 33 - java.rmi – Remote Method invocation ............................................................................................................ 415

RMI ................................................................................................................................................................................... 415

JVM Communication ........................................................................................................................................................ 415

Socket (Http Based) ..................................................................................................................................................... 415

DatagramSocket and DatagramPacket (UDP Protocol) ............................................................................................... 415

RMI ............................................................................................................................................................................... 415

RMI Layers ........................................................................................................................................................................ 416

Application Layer ......................................................................................................................................................... 416

Proxy Layer................................................................................................................................................................... 416

Remote Reference Layer .............................................................................................................................................. 416

Transport Layer ............................................................................................................................................................ 416

Stub and Skeleton ............................................................................................................................................................ 416

Responsibilities of Stub ................................................................................................................................................ 416

Responsibilities of Skeleton ......................................................................................................................................... 417

Registry ............................................................................................................................................................................. 417

Server Application ............................................................................................................................................................ 417

Example Programs............................................................................................................................................................ 417

Chapter 34 - Swing Package.................................................................................................................................................. 429

Differences between AWT and Swing .......................................................................................................................... 429


Create and display the JFrame ..................................................................................................................................... 431

Add the controls in JFrame .......................................................................................................................................... 431

Layouts ............................................................................................................................................................................. 432

What is layout .............................................................................................................................................................. 432

Layout interfaces ......................................................................................................................................................... 432

Layout Classes .............................................................................................................................................................. 432

BorderLayout ............................................................................................................................................................... 434

Event handling ............................................................................................................................................................. 434

Chapter 35 - Applet .............................................................................................................................................................. 553

Applet Program Creation ................................................................................................................................................. 553

applet viewer.................................................................................................................................................................... 554

Html calling .................................................................................................................................................................. 554

Chapter 36 - Java 7 features ................................................................................................................................................. 569

Binary Literals ................................................................................................................................................................... 569

Underscores in Numeric Literals ...................................................................................................................................... 570

String in Switch ................................................................................................................................................................. 571

Type Inference for Generic Instance Creation ................................................................................................................. 572

try with resources ............................................................................................................................................................ 572

Prior 1.7 Example ......................................................................................................................................................... 572

1.7 Example .................................................................................................................................................................. 573

Handling More Than One Type of Exception ................................................................................................................... 573

Prior 1.7 Example ......................................................................................................................................................... 573

Since 1.7 Example ........................................................................................................................................................ 574

throw in 1.7 ...................................................................................................................................................................... 574

Chapter 37 Java 8 Features................................................................................................................................................... 578

Method References .......................................................................................................................................................... 578


Program without method reference - Simple program to invoke static method ........................................................ 578

Multiple invocation example with one Functional Interface type ............................................................................... 580

Constructor Reference ..................................................................................................................................................... 582

Class Collectors - java.util.stream.Collectors ................................................................................................................... 584

Lambda Experssions ......................................................................................................................................................... 586

Functional Interface ..................................................................................................................................................... 586

Lambda Example Program without parameter............................................................................................................ 587

Lambda Example Program with parameter ................................................................................................................. 588

Sort by salary ascending using classic model ............................................................................................................... 593

For Each ............................................................................................................................................................................ 595

java.util.Stream ................................................................................................................................................................ 596

Methods of BaseStream .............................................................................................................................................. 596

How to get the Stream object ...................................................................................................................................... 597

Terminal and Intermediate operations in Stream ....................................................................................................... 597

Lazy behavior of Intermediate Stream ........................................................................................................................ 598

Stateless and stateful Intermediate operation ............................................................................................................ 598

Intermediate operation examples ............................................................................................................................... 599

Convert stream to List .................................................................................................................................................. 599

ParallelStream .................................................................................................................................................................. 601

Stream with Iterator .................................................................................................................................................... 601

Date and Time handling added in Java 8 .......................................................................................................................... 602

Default and static methods of interface .......................................................................................................................... 604

Chapter 38 Java 9 Features .................................................................................................................................................. 607

of() .................................................................................................................................................................................... 607

of() List ......................................................................................................................................................................... 607

JShell ................................................................................................................................................................................. 609


Starting and Stopping JShell......................................................................................................................................... 609

private method in interface ............................................................................................................................................. 610

Usage the variable declared outside can be used in try with resources .......................................................................... 611

Chapter 39 Java 9 Modular System ..................................................................................................................................... 613

Prior approach before Java 9 Modular system ............................................................................................................ 613

Drawbacks of above Prior approach ............................................................................................................................ 613

What is Java 9 Modular System ................................................................................................................................... 615

Module Descriptor (module-info.java) ........................................................................................................................ 616

Modular Application Creation...................................................................................................................................... 617

Chapter 40 Java 10 Features ................................................................................................................................................ 621

JEP 286: Local-Variable Type Inference ............................................................................................................................ 621

Creating Unmodifiable Collections ................................................................................................................................... 622

java.util.Optional orElseThrow() ...................................................................................................................................... 625

JEP 296: Consolidate the JDK Forest into a Single Repository.......................................................................................... 626

JEP 304: Garbage Collector Interface ............................................................................................................................... 627

JEP 307: Parallel Full GC for G1 ........................................................................................................................................ 627

JEP 310: Application Class-Data Sharing .......................................................................................................................... 627

JEP 312: Thread-Local Handshakes .................................................................................................................................. 628

JEP 313: Remove the Native-Header Generation Tool..................................................................................................... 628

JEP 314: Additional Unicode Language-Tag Extensions ................................................................................................... 628

JEP 316: Heap Allocation on Alternative Memory Devices .............................................................................................. 629

JEP 317: Experimental Java-Based JIT Compiler ............................................................................................................... 629

JEP 319: Root Certificates................................................................................................................................................. 629

JEP 322: Time-Based Release Versioning ......................................................................................................................... 630

Chapter 41 Java 11 Features ................................................................................................................................................ 632

2018/09/25 General Availability ........................................................................................................................... 632


JEP 181: Nest-Based Access Control................................................................................................................................. 632

JEP 330: Launch Single-File Source-Code Programs ......................................................................................................... 632

Additions in java.lang.String ............................................................................................................................................. 633

strip methods in String class ........................................................................................................................................ 634

public String repeat(int count) ..................................................................................................................................... 635

Local-Variable Syntax for Lambda Parameters ................................................................................................................ 636

JEP 181: Nest-Based Access Control................................................................................................................................. 638

JEP 309: Dynamic Class-File Constants ............................................................................................................................. 639

JEP 315: Improve Aarch64 Intrinsics ................................................................................................................................ 640

JEP 318: Epsilon: A No-Op Garbage Collector (Experimental).......................................................................................... 640

JEP 321: HTTP Client (Standard) ....................................................................................................................................... 641

JEP 324: Key Agreement with Curve25519 and Curve448 ............................................................................................... 643

JEP 327: Unicode 10 ......................................................................................................................................................... 643

JEP 335: Deprecate the Nashorn JavaScript Engine ......................................................................................................... 644

JEP 320: Remove the Java EE and CORBA Modules ......................................................................................................... 644

JEP 329: ChaCha20 and Poly1305 Cryptographic Algorithms .......................................................................................... 644

JEP 328: Flight Recorder ................................................................................................................................................... 645

About Java Flight Recorder .......................................................................................................................................... 645

Java Mission Control was also open sourced ............................................................................................................... 645

JEP 331: Low-Overhead Heap Profiling ............................................................................................................................ 646

JEP 332: Transport Layer Security (TLS) 1.3...................................................................................................................... 646

JEP 333: ZGC: A Scalable Low-Latency Garbage Collector (Experimental) ....................................................................... 646

JEP 336: Deprecate the Pack200 Tools and API ............................................................................................................... 647

Chapter 42 Java 12 Features ................................................................................................................................................ 648

Internal changes ............................................................................................................................................................... 648

JEP 189: Shenandoah: A Low-Pause-Time Garbage Collector (Experimental) ................................................................. 648


JEP 230: Microbenchmark Suite ....................................................................................................................................... 648

JEP 334: JVM Constants API ............................................................................................................................................. 649

JEP 340: One AArch64 Port, Not Two ............................................................................................................................... 649

JEP 341: Default CDS Archives .......................................................................................................................................... 649

JEP 344: Abortable Mixed Collections for G1 ................................................................................................................... 650

JEP 346: Promptly Return Unused Committed Memory from G1.................................................................................... 651

Development changes ...................................................................................................................................................... 651

JEP 12: Preview Language and VM Features .................................................................................................................... 651

Switch Expressions ........................................................................................................................................................... 651

File.mismatch method...................................................................................................................................................... 654

Compact Number Format ................................................................................................................................................ 656

java.util.Stream class teeing() method ............................................................................................................................. 657

Java Strings New Methods ............................................................................................................................................... 658

transform() ....................................................................................................................................................................... 659


Java Book - Chidambaram.S

Chapter 1 - Java Technology

What is Java

Java is a machine independent language, thus Java is used in web programming,


also used in various fields such as desktop programming, network programming,
mobile application development, machine Learning, natural language processing,
device programming and many more.

The learner must learn core Java in depth then he can able to choose any one of
the above field to build the career. This book is the correct place to start
Core Java.

Java follows Unicode (Universal Code) representation,ranges from 0 to 65535. C


and C++ follow ASCII (American Standard Code for Information Interchange).

Java is an object oriented programming language and case sensitive also.

Page 22 of 660
Java Book - Chidambaram.S

Java Standards

1. J2SE –Java 2 Platform Standard Edition

2. J2EE- Java 2 Platform Enterprise Edition

Various types of programming approaches

1. Structural programming approach Ex. C

2. Top down approach Ex. Cobol

3. Bottom up approach Ex. C++, Java

4. Event driven programming approach Ex. VB

History of C and C++

C was invented by Dennis Ritchie in 1972 and it was standardized in 1989 by


ANSI(American National Standard Institute)

C++ was invented by Bjarne Stroustrup in 1979 at Bell laboratories in New


Jersey. Initially it was called as “C with Classes”. In 1983 it was renamed to
C++.

Java was developed by James Gosling, Patricknaughton, Chriswarth, Edfrank and


Mikesheridan at Sun Microsystems in 1991. This language was initially called as
“Oak” and it was renamed to Java in 1995.

The first (original) version is 1.0.

Java’s Magic

In C and C++, the source code will be converted by machine code by compiler.
Then the machine code goes to OS at run time to execute the program. The

Page 23 of 660
Java Book - Chidambaram.S

problem is that the windows based machine code will not run under other than
windows OS such as linux, unix. For linux and unix, the compiler will differ
and source code too.

In web based programming, the program should run in any platform without
modifying the source code, Java does it. The diagram of below explains the
Java’s magic

Page 24 of 660
Java Book - Chidambaram.S

Java’s Magic Diagram

Compile Time

Source Code written Byte Code


in java JVM
(class file)
(Compiler)

Run Time

JRE
Machine Code
JIT Compiler
Byte Code

OS

Page 25 of 660
Java Book - Chidambaram.S

JVM and JIT

JVM(Java Virtual Machine) is the compiler of Java and it compiles your source
code to byte code(class file). JIT(Just In Time) is the part of JVM converts
needed portion of byte code to machine code with the help of JRE(Java Runtime
Environment)

What is program?

Program is a collection of predefined statements and organized by specific


logic to perform end user need.

Two Paradigms

What is happening – Except Oops Ex: c

Who is being affected – In Oops Ex: C++, Java

What is happening – means what should be next. Consider on C program, the


statement will be executed one by one. This is considered as “What is
happening”

Who is being affected - means which object should be affected for the
each statement.

When C like programming language we should think about like "What is


happening".

In Java like programming language we should think about "Who is being


affected". Here "Who" reperesents an object.

Page 26 of 660
Java Book - Chidambaram.S

Chapter 2 - OOPS Concepts

Below topics are OOPS concepts.

Abstraction

Encapsulation

Polymorphism

Inheritance

Abstraction

Hiding information or data.

Abstraction provides the feature without including the background details and
explanations.

Consider, application provides the component (buttons, menus, etc..) to access


interfaces (classes, methods, etc..) to perform one action(save the file, open
the page, etc..). Here user only needs to use the component and no need to know
about how the implementation is working. For example, user needs to click
button or menu that's it, the component(button or menu) invokes class and
method to perform save or open action. Here user doesn't need to know about how
the component invokes class and method to perform save or open action.

Another example is car brake. Applying brake performs the action to slow / stop
the car and user no need to know about how brake internally invokes other parts
of car. The benefit of this system is that the improvements of braking system
won't affect the usage of brake, which means that the drum brake can be
improved to disc without affecting how brake is used by user.

Page 27 of 660
Java Book - Chidambaram.S

Abstraction in Java

In Java using access modifiers like private, we can hide the data or method to
outside world. The visible method can invoke the hidden private method / data,
so we can access the visible metod in turn to access the private member.

Encapsulation

Binding data with code.

It is the mechanism that binds together code and data. It means change the
state of an object (instance variables) by using behavior of an object
(instance methods).

Information can be hidden by programmer and exposed to outside world by using


getter / setter methods.

Hiding information can be achieved by using private members. Also access


specification can be done by (restrictions / permissions) protected, public,
private and default access specifiers.

Let's see the below example

1. class PrivateDemo {
2. /*
3. * private modifier restricts access "mark" variable directly from otherclas
ses
4. */
5. private int mark;
6. /*
7. * only the "mark" variable can be accessed using getmark() method
8. */
9. public int getMark() {
10. return mark;
11. }
12. /*

Page 28 of 660
Java Book - Chidambaram.S

13. /* only the mark variable can be assigned using setmark(int mark) method.
*/
14. public void setMark(int mark) {
15. this.mark = mark;
16. }
17.
18. public static void main(String args[])
19. {
20. PrivateDemo privateMember = new PrivateDemo();
21. /* with below statement the program will not be compiled
22. system.out.println(privatemember.mark);
23. */
24. /* below is the correct usage .
25. */
26. privateMember.setMark(100);
27. System.out.println("mark="+privateMember.getMark());
28.
29. }
30. }
31.
32. Output
33.
34. mark=100

The setter and getter methods are optional only.

If setter is not present, there is no way to set the value through other
classes and the same class can only set the value.

If getter is not present, there is no way to read this value through other
classes, and the same class can only read the value for internal usage.

Making members as private is abstraction and expsoing the private members


through the methods is encapsulation.

Page 29 of 660
Java Book - Chidambaram.S

Polymorphism

One Interface – Many forms

One interface can act vary as per given input. Runtime polymorphism is
implemented when we have “IS-A” relationship between objects.

Types of Polymorphism

Compile time polymorphism (or) stating binding (or) earlier binding.

For example, Method Overloading.

Same method names with different parameters in one class can be known as Method
over loading. It is the way to implement compile time polymorphism. Here
compiler will decide what method should be invoked.

Runtime polymorphism (or) Dynamic binding (or) Later binding

(Ex: Method Overriding)

Rewrite(override) the method in sub class (already defined in super


class) can be known as Runtime polymorphism. Here compiler can’t decide what
method should be called. The run time only can decide it. Because the objects
are created at run time. This concept is associated with Polymorphism and
Inheritance.

Example of Method Overloading

class PolymorphismDemo

void m1()

System.out.println("m1");

Page 30 of 660
Java Book - Chidambaram.S

void m1(int x)

System.out.println("m1 with x");

void m1(int x,int y)

System.out.println("m1 with x and y");

public static void main(String args[])

PolymorphismDemo polymorphismDemo = new PolymorphismDemo();

polymorphismDemo.m1();

polymorphismDemo.m1(5);

polymorphismDemo.m1(5,10);

Example of Method Overriding

class Parent

Page 31 of 660
Java Book - Chidambaram.S

void m1()

System.out.println("m1 of Parent");

class Child extends Parent

void m1()

System.out.println("m1 of Child");

class MainClass

public static void main(String args[])

Child child =new Child();

child.m1();

Page 32 of 660
Java Book - Chidambaram.S

Inheritance

Deriving existing technology to the new one without rewriting it and reuse the
same. It is the Process of one object can acquire the properties of another
object. The benefit is that the new technology needs not to concentrate the
code for already available features and it can concentrate to the newly needed
features.

Existing technology can be called as base class or super class, the new
technology can be called as derived class or sub class. In OOPS, the concept of
inheritance provides reusability. The real power of inheritance mechanism is
reusability.

Diagram Explanation

Plan of Car is a class.

Car1, Car2 are the objects.

Left box contains the behavior of car and right box contains the state of car.

If you use the break of car1, car2 will not be affected. Recall the meaning of
“Who is being affected”.

To use break, you must have car(object).

Car must have car plan(class).

Car’s state can be changed by using the behavior.

The whole OOPS concepts can be understood after understanding the below
diagram.

Page 33 of 660
Java Book - Chidambaram.S

OOPS Entities Diagram

Plan of Car

Car1
Car2

Break Move/Stop
Break Move/Stop

Gear 1/2/3
Gear 1/2/3

Steering Left/Right/Straig
Steering Left/Right/Straig
ht
ht

Page 34 of 660
Java Book - Chidambaram.S

Chapter 3 - Class and Program Structure

What is Class?

It is a user defined data type and behaves like the built in types.

Class is a template to create an object.

The entire set of data and code of an object can be made as a user defined data
type, with the help of class.

By creating class, really we are establishing the way to create an object.

Class can have constructors, methods, instance variables.

In java, classes can be available in two types

Concrete class – Instantiation is possible

Abstract class - Instantiation is not possible

Instantiation means an object creation.

Structure of class

[modifier] class <ClassName>

//instance variables declaration

//static variables declaration

//constructors

//instance methods

//static methods

Page 35 of 660
Java Book - Chidambaram.S

Example code

1. class A
2. {
3. // instance variables
4. int x,y;
5. //static variables
6. static int p,q;
7. //constructor
8. A()
9. {
10. //code
11. }
12. void get(int x,int y) // instance method
13. {
14. //code
15. }
16. static void getter(int p,int q) //static method
17. {
18. //code
19. }
20. }

Page 36 of 660
Java Book - Chidambaram.S

What is an object?

Objects are the basic runtime entities in an object oriented system.

Object is a runtime memory which has the copy of instance members of the class.

Object will have the memory for instance variables only.

A ob = new A();

In above sentence,

A()- Default constructor

new –Memory allocation Operator

Object creation

Object creation can be done in two ways.

Memory full state

Memory Less State

Memory full state

A ob=new A(); - It is known as an object.

ob.get(); // It invokes get() of class A

Memory less state

A ob; - It is a reference.

ob.get();

Here NullPointerException will be raised. Because reference can’t be used to


call class members.

Page 37 of 660
Java Book - Chidambaram.S

What is Method?

Methods are behavior of an object. It is used to change the state of an object,


and perform some useful tasks.

Syntax

[modifier] returntype methodName()

//code

Example

void sum() // default modifier method

Constructor

Constructor can be used to initialize the instance variables of the class and
perform some tasks when the time of object creation.

Classname and constructor name must be equal.

Constructor will be called by run time when you create an object.

If the class doesn’t have constructor, runtime supplies default constructor


automatically.

If you add parameterized constructor, you must add empty constructor.

Instance variables
Page 38 of 660
Java Book - Chidambaram.S

Memory is created for instance variables when an object is created.

Instance variables can be declared after class declaration.

Each one object will have separate memory for instance variables.

Instance variables are the state of an object.

Consider following example

class A

int x,y;// instance variables

void assignValues(int a,int b)

x=a;

y=b;

public static void main(String args[])

A ob1=new A();

A ob2=new A();

A ob3=new A();

ob1.assignValues(1,2);

ob2.assignValues(5,200);

ob3.assignValues(10,20);

Page 39 of 660
Java Book - Chidambaram.S

Above program creates below objects as follows.

Ob1 Ob2 Ob3

X=1 X=5 X=10

Y=2 Y=200 Y=20

Implicit argument of constructors and methods

1.
2. class A
3. {
4. int a;
5. A(){}
6. A(int c)
7. {
8. a=c;
9. }
10. void print(int x) // called function // formal parameters
11. {
12. System.out.println(x);
13. System.out.println("a="+a);
14. }
15. public static void main(String arg[])
16. {
17. A ob=new A(100);
18. int x=200;
19. ob.print(x); // caller // Actual parameters.

Page 40 of 660
Java Book - Chidambaram.S

20. A ob1=new A(200);


21. ob1.print(300);
22. }
23. }
24. Output
25. 200
26. a=100
27. 300
28. a=200

In above program, ob,ob1 are the objects and ob,ob1 will have “a” separately.

Listen, “a” is printed from print() without using object in line no 13.

It means when you create an object or calling the method by using an object,
the object will be passed as implicit parameter to the constructor or method.
It means the method / constructor can use the invoking object with or without
this.

Within instance methods and constructors, the object can be referred by using
“this” keyword. It is optional. The “this” keyword may or may not be used to
access the members of class within same class. But using this keyword is highly
recommended because when the program grows it is useful to differentiate
instance and other variables.

Formal parameters will have memory only when actual sends the value.

Instance Method

The method can be called by using an object only, that object can be known as
invoking object.

Instance method can use instance variables and static variables of the class.

Page 41 of 660
Java Book - Chidambaram.S

Instance methods will have invoking object as a implicit parameter.

Simple Program with explanation

class A (1)

{ (2)

public static void main(String args[]) (3)

{(4)

System.out.println(“Welcome To Java”);(5)

}(6)

}(7)

(1)

The Java program must be within class. Class name must be started with capital
letter and each one word’s first character should be capital letter. Even
though it is not compulsory and it is highly recommonded and good practice.

(2)

Open brace for class

(3)

public

Modifier of the method. Because this method will be called by OS. OS is in


other package. So the method should be public to call it from OS.

static

The main will be called by OS without object means before instantiation. So the
main should be a static method.

Page 42 of 660
Java Book - Chidambaram.S

void

It is a return type. main() doesn’t return anything to caller(OS)

main

Method name

String args[]

Arguments can be passed to main, when you run the program. The types of
parameters should be String. The parameters will be stored in args[]. The name
of variable(args) may be differed.

(4)

Opening brace for main

(5)

System

It is the class of java.lang package

System.out

out is the static variable of System. System.out returns java.io.PrintStream


class object. So we call the println() by using PrintStream object.

println()

It is a method of java.io.PrintStream. It is used to print given


statement in console.

(6)

Closing brace for main

(7)

Page 43 of 660
Java Book - Chidambaram.S

Closing brace for class.

Page 44 of 660
Java Book - Chidambaram.S

Chapter 4 - Association, Aggregation,


Composition

These are various standards to define the relationship between objects.

Association defines the "has-a" relationship between objects and


inheritance defines "is-a" relationship between objects.

Aggregation

It is the special form of association. Here the two objects will have own
life cycle and can be related. For example, car has driver. Now driver can be
related to many cars and car may have many drivers, which reveals these two
objects loosely coupled.

Composition

It is the restricted form of Aggregation. Here the two objects can't be


separated and will not have own life cycle. For example car and engine. Engine
will not be useful without Car and vise versa, which reveals these two objects
are tightly coupled.

Using real life example we can explain this one. Consider below two
sentences.

#1) Ford Figo is the car - Inheritance - Here Ford Figo and car are the
objects.

#2) Car has the engine - Association - Composition - Here car and engine are
the objects; they can't live independently

#3) Car has the driver - Association - Aggregation - Here car and driver are
two objects; they live independently.

Page 45 of 660
Java Book - Chidambaram.S

We have seen two different objects in above sentences and their relationships.
Now let's write java classes to create relationships programatically.

class Car

Engine engine; // Association - Composition

Driver driver; // Assocation - Aggregation

// other properties

class Figo extends Car // extends is the way of doing inheritance.

Now Figo automatically derives all the properties of Car class

Page 46 of 660
Java Book - Chidambaram.S

Chapter 5 - Lexical issues

Java Programs are collection of white space, identifiers, literals, comments,


operator, separator and keywords.

White space

White space is a space, tab, new line.

Identifiers

An identifier is the name of class, method and variable.

Identifiers can have uppercase, lowercase letter, numbers, underscore and


dollar sign.

They must not begin with a number.

Keyword must not be an identifier, even though keyword can be a part of an


identifier.

Example

int a

class A

void sum()

(a,sum,A are identifiers)

Literals

A constant value in java can be known as literal.

Page 47 of 660
Java Book - Chidambaram.S

Ex: int a=100(100 is a literal)

Literals can be written with underscores.(added in 1.7)

int x=12_34_56;

Comments

There are three types of comments defined by java

Single line comment //

Multiline Comment /* … */

Documentation Comment /**……*/

Steps to Documentation creation for user defined packages.

We can create documentation for user defined package

Rules to create docs for user defined package

Class and constructor should be public

Methods and variables may be public or protected.

Consider following class.

/** it is A class*/ //Documentation comment

public class A

/** public int variable*/

public int a=10;

/** int variable*/

Page 48 of 660
Java Book - Chidambaram.S

int b=40;

/** protected variable*/

protected int c=20;

/** empty constructor*/

public A()

/** public get method*/

public void get()

/** protected sum method*/

protected void sum()

/** default mul method*/

void mul()

public static void main(String arg[])

A ob=new A();

Page 49 of 660
Java Book - Chidambaram.S

ob.get();

ob.mul();

ob.sum();

Go to dos prompt -> G:\javaprg>javadoc A.java -> G:\javaprg\>start


index.html – to view the documentation of A.java

In your documentation only public, protected members are placed. Why?


Because public, protected are other package modifiers.

Keywords

There are 50 keywords available in java.

48 keywords are in use.

2 keywords are reserved but not in use. These keywords are goto, const.

true, false, null are the values and not keywords.

enum keyword is added in Java 1.5

Separator

{} - braces

[] - brackets

() – parentheses

. – dot or period

, - comma

; - semicolon

Page 50 of 660
Java Book - Chidambaram.S

Escape Sequences

\’ Single quote

\” Double quote

\\ Backslash

\r Carriage return

\n Newline

\f Formfeed

\t Tab

\b Backspace

In below program carriage return character \r just comes to the beginning of


the same line and overwrite.

In below output "Wel" is replaced with "all". So the new sentence is allcome to

"java" states that how the printing statement prints double quote symbol "
using \".In the same way \' prins ' and vice versa.

1. import java.io.*;
2. class EscapeSequence
3. {
4. public static void main(String ars[])
5. {
6. System.out.print("\nWelcome");
7. System.out.print("\tto");
8. System.out.print("\rall");
9. System.out.println();
10. System.out.println("\"java\"");
11. }
12. }
13.

Page 51 of 660
Java Book - Chidambaram.S

14. Output
15.
16. allcome to
17. "java"

Page 52 of 660
Java Book - Chidambaram.S

Chapter 6 - Operators

Operators can be divided into three categories

Unary – requires one operand

Binary – requires two operand

Ternary – requires three operand

Operators can be used to provide meaning between two or more operands,


expressions.

Relational operators check the comparison between two operands and always
returns true or false.

Boolean logical operators check the comparison between two or more relational
expressions.

Bitwise operators work with bits on given expressions.

Some Examples

a>b -> Relational expression

((a>b) & (a>c)) -> Logical expression

(a&b) -> Bitwise expression

(a+b) -> Arithmetic expression

Types of operators.

Basic arithmetic operator

Arithmetic assignment operator

Increment and decrement operator

Page 53 of 660
Java Book - Chidambaram.S

Bitwise operators

Bitwise assignment operators

Relational operators

Boolean logical operators

Ternary operators

Basic arithmetic operator

+ Addition

- Subtraction

* Multiplication

% Modulus

/ Division

Arithmetic Assignment Operator

+=,-=,*=,%=,/=

Increment and decrement Operator

Types of Increment

Post increment (a++)

'a' - value will be incremented with 1 once the tasks are completed

Pre increment (++a)

'a' - value will be incremented first with 1 then the tasks are completed

Types of Decrement

Post Decrement(a--)

Page 54 of 660
Java Book - Chidambaram.S

Pre Decrement (--a)

Example

Post increment

int a=10;

int b;

b=a++; -> b=a, a=a+1

Answer b=10,a=11

Pre increment

b=++a; -> a=a+1,b=a

Answer b=11,a=11

Post decrement

int a=10;

int b;

b=a--; -> b=a, a=a-1

Answer b=10,a=9

Pre decrement

b=--a; -> a=a-1,b=a

Answer b=9,a=9

Bitwise Operator

& Bitwise AND

| Bitwise OR

Page 55 of 660
Java Book - Chidambaram.S

~ Bitwise NOT

^ Bitwise XOR

<< Left shift operator

>> Right shift operator

<<< Left shift with zero fill

>>> Right shift with zero fill

Bitwise Assignment Operator

&= Bitwise and assignment operator

|= Bitwise or assignment operator

<<= Bitwise left shift assignment operator

>>= Bitwise right shift assignment operator

>>>= Bitwise right shift with zero fill assignment

operator

Relational operators

== Equal to

!= Not equal to

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

Boolean Logical operators

Page 56 of 660
Java Book - Chidambaram.S

& Logical and

| Logical or

^ Logical XOR (exclusive or)

|| Short circuit or

&& Short circuit and

! Logical unary not

&= And assignment

|= Or assignment

^= XOR assignment

Ternary operator

?: Ternary if..then..else

Operator precedence

In mixed operators expression, java follows following precedence

() []

++ --

* / %

+ -

>> >>> <<

> >= < <=

== !=

&

Page 57 of 660
Java Book - Chidambaram.S

&&

||

?:

= op=

Note

Operator precedence can be overcome by using parenthesis. Consider following


example

int x=5+2*3 // Ans: 11 because * first, + second

It can be rewritten as

int x=(5+2)*3; // Ans 21

Above example illustrates, we can change the operator precedenc by using


parenthesis.

Difference between Logical and short circuit and

Logical And

It checks the conditions up to last expression, even the first expression is


false.

Short circuit Logical And

If first condition is false, returns false without checking remaining


expressions.

Page 58 of 660
Java Book - Chidambaram.S

Example

class TernaryOp

public static void main(String arg[])

int a=70,b=40;

String str=((a>=35)&&(b>=35))?"Pass": "fail";

System.out.println("str:"+str);

Page 59 of 660
Java Book - Chidambaram.S

Chapter 7 - Data Type

Java has 8 primitive data types. Each one primitive type has wrapper class
available from java.lang(will discuss in java.lang package).

Following list provides the primitive types and their wrapper classes.

Integer based Float based Other

int(Integer) float(Float) char(Character)

long(Long) double(Double) boolean(Boolean)

short(Short)

byte(Byte)

The following table illustrates the data types and their size, ranges.

In true, false can’t be represented as 1,0 in java.

Data Type Width(bit) Range

int 32(4 byte) -2,147,483,648 to


2,147,483,647

long 64(8 byte) -


9,223,372,036,854,775,808
to
9,223,372,036,854,775,807

short 16(2byte) -32,768 to 32,767

byte 8(1 byte) -128 to 127

double 64(8 byte) 4.9e-324 to 1.8e+308

float 32(4 byte) 1.4e-045 to 3.4e+308

char 16(2 byte)

Page 60 of 660
Java Book - Chidambaram.S

boolean true, false

Various types of variable declaration

[modifier] datatype variablename=[value];

Ex

public int a=10;

int x,y,z;

int x=1,y,z=5 ;

char ch=’y’ ;

String str= “Java”;

Note

Usage of uninitialized variables in main() will raise the error “Variable might
not have been initialized”. Those variables declared in main will not have default
values.

The instance variables will have default values even we don’t provide the value.

The following table illustrates data types and their wrapper classes, conversion
methods. (Discussed detailed in java.lang package)

Data type Class Static Method Name

int Integer parseInt(String str)

float Float parseFloat(String


str)

double Double parseDouble(String


str)

Page 61 of 660
Java Book - Chidambaram.S

long Long parseLong(String str)

char Character -

boolean Boolean parseBoolean(String


str)

byte Byte parseByte(String str)

short Short parseShort(Strimg


str)

Note

Difficulties to store range in data types discussed in Type conversion and casting

Three Scopes and Life time of Variable

Instance Variable(Class Scope)

Local Variable(Method Scope)

Static variable

Instance Variables

Instance variables are already discussed

Local Variable (Method Scope)

Variables declared within method can be known as local variable. When run time
invokes the method, the local scope variable has the memory and the memory
destroys after runtime exits from method. Other methods can’t use the local
variables.

Page 62 of 660
Java Book - Chidambaram.S

Block scope is another feature of local scope. Variable declaration within if


block, for block, while block can be known as block scope. The block scope
variables can’t be visible in other blocks.

Example

if (x==5)

int y=10;

S.o.p(y); // error

Page 63 of 660
Java Book - Chidambaram.S

Chapter 8 - Type Conversion

Assigning variables of same data type is normal.

Assigning lower data type value to higher data type value can be known as widening
conversion. Here implicit casting(Automatic type conversion) will be done by java
run time automatically.

Assigning higher data type value to lower data type value can be known as
narrowing conversion. The error will be raised for these statements. Because lower
type can’t have enough memory to accommodate the value from higher type. Here
explicit casting must be needed.

Automatic type conversion

int c=100;

float a=c;//Automatic type conversion

Here RHS (Right Hand Side) data type range is lesser than LHS (Left Hand Side)
data type range. Now automatically conversion will be done by JRE.

Casting

float a=10.5f;

int c=a; // error

int c=(int)a; // Correct bacause explicit casting is must here.

How casting can be made

The following example illustrates one surprise fact.

int x=900;

byte y=(byte)x;

Page 64 of 660
Java Book - Chidambaram.S

This is legal. The compile time error will not be raised. But how 900 can be
stored in y. Becuase y is byte type and it can accommodate the range between -128
to 127. The below program illustrates how java handles this one.

Here java first calculates 900%256. The remainder is 132. 132 can’t be stored in
y. Because byte range is -128 to 127. So JRE stores -124 in y. How?

Run following prg, and analyze carefully.

1. class A
2. {
3. public static void main(String args[])
4. {
5. for (int x=256;x<=1000;x++)
6. {
7. byte y=(byte)x;
8. System.out.println("x="+x+"y="+y);
9. }
10. }
11. }

Automatic type promotion

In mixed expressions, lower data type will be converted to higher data type
automatically if LHS is higher data type.

If LHS is lower than RHS, explicit cast is needed.

Consider following example

byte b=b*2; // error because 2 will be treated as integer.

int x=b*50; // correct. Here b will be promoted to int.

Page 65 of 660
Java Book - Chidambaram.S

long y=x*20; // correct

int z=y*2; // error becuase RHS is larger.

double p=y*z // correct

Type promotion Rules

All byte and short values are promoted to int.

If one expression is long, the whole expression is promoted to long.

If one expression is float, the whole expression is promoted to float.

If one expression is double, the whole expression is promoted to double.

Page 66 of 660
Java Book - Chidambaram.S

Chapter 9 - Selection Statements

Java Selection Statements

Selection statements can be used to change the flow of execution based on


conditional expressions.

The following types of selection statements available.

 simple if
 if..else
 if..else if
 else if ladder
 nested if
 switch

if

if(condition)

//code

if else

if(condition)

//code

else

Page 67 of 660
Java Book - Chidambaram.S

//code

if..else if

if(condition1)

//code

else if(condition2)

//code

else

//code

else if ladder

if(condition1)

//code

Page 68 of 660
Java Book - Chidambaram.S

else if(condition2)

//code

else if(condition3)

//code

else

//code

Nested if

if(condition)

if(condition)

//code

else

//code

Page 69 of 660
Java Book - Chidambaram.S

else

//code

switch

Switch statement is multiway branch statement. It is the better alternative of


else if ladder.

Switch expression must be byte,short,int, char or String(Switch in String added in


1.7)

switch(ch)

case 1:

statements;

break;

case 2:

Statements;

break;

case 3:

statements;

break;

Page 70 of 660
Java Book - Chidambaram.S

case 4:

Statements;

break;

default:

Statements;

Page 71 of 660
Java Book - Chidambaram.S

Chapter 10 - Iteration Statement

 while
 do..while
 for
 for each (added in 1.5)
 Nested for loop
 Entry control loop
for, while
 Exit control loop
do..while

while(condition)

Statements;

do..while

do

Statements;

}while(condition);

for

Type 1

for(initialization;condition;inc/dec part)

Page 72 of 660
Java Book - Chidambaram.S

Type 2

for(initialization;condition;)

inc/dec part;

Type 3

intialization;

for(;condition part;)

inc/dec part;

Type 3 Example

int i=0;

for(;i<5;)

i++;

Type 5

for(;;) // indefinite for loop

Page 73 of 660
Java Book - Chidambaram.S

for each

for each can be used to retrieve the elements from array or collection.(collection
is discussed in java.util)
In this type of loop we don’t need to specify number of iteration and we can’t
change the original value.

for each with one dimensional array syntax

for(variablename:arrayname)

statements;

Example

int a[]={1,2,3,4,5};

//Number of time must be specified

for (int i=0;i<5;i++)

System.out.println(a[i]);

//original value can be changed

a[i]=a[i]+5;

for(int i:a)

Page 74 of 660
Java Book - Chidambaram.S

System.out.println(i);

o/p:

for each two dimensional array syntax

for(onedimensionalarrayname[]:twodimensionalarrayname)

for(variablename:onedimensionalarrayname)

Statements;

Jumping Statements

There are three jumping statements in java.

 break
 continue
 return

Page 75 of 660
Java Book - Chidambaram.S

break

break is used in switch and for to terminate the iteration.

continue

Continue is used to ignore the current iteration and loop will continue with next
iteration.

“Break” terminates all remaining iteration but “continue” terminates current


iteration.

Return

Exits from current method and go back to caller.

This statement comes with or without return value.

It is used to stop the executuin of thread too.

Break as a form of goto

In java goto is a reserved keyword, but it is not available in programs.

We can use break instead of goto.

Page 76 of 660
Java Book - Chidambaram.S

Chapter 11 - Input from user

There are two ways to get input from user.

Command line input

User interactive input

Command line Input

When we start the execution of one program, we can provide the startup values to
the program.

These values will be stored in formal parameter of main.

public static void main(String arg[])

s.o.p(arg[0]);

arg[] is unlimited string array. So the user can provide more than one values.

When we run the program we can give the command line input as like follows.

class CommandLineDemo

public static void main(String args[])

System.out.println("args[0]="+args[0]);

System.out.println("args[1]="+args[1]);

Page 77 of 660
Java Book - Chidambaram.S

E:\>Javaprg>java CommandLineDemo 10 hai

Now arg[0]=”10”, arg[1]=”hai”

Interactive input

In command line we can get the values during the time of starting program. But we
need to get the values from user during the runtime.

It can be achieved by using java.io.DataInputStream class.

Consider following example

1. import java.io.*;
2. class A
3. {
4. public static void main(String args[])
5. {
6. try // 1
7. {
8. DataInputStream dis=new DataInputStream(System.in); // 2
9. System.out.println(“Enter the name”);
10. String name=dis.readLine(); // 3
11. System.out.println(“Enter the code”);
12. int code=Integer.parseInt(dis.readLine()); // 3
13. }//try
14. catch(Exception e) // 4
15. {
16. e.printStackTrace(); //5
17. }//catch
18. }//main
19. }//class

Page 78 of 660
Java Book - Chidambaram.S

try is added in above program, because readLine() raises IOException

Here we create DataInputStream object. DataInputStream class is in java.io


package. So we must import it.

When we create the object, the constructor will be called. For DataInputStream
constructor we must pass java.io.InputStream object.

DataInputStream(is java.io.InputStream)// predefined constructor

To provide InputStream object, we use System.in which returns InputStream object.

System is a class, “in” is a static variable of System class.

System class has three static variables as follows

in - java.io.InputStream

out - java.io.PrintStram (think System.out)

err - java.io.PrintStram (System.err.println)

Simply we can say that, DataInputStream object dis refers InputStream, InputStream
refers console, so reading from dis, simply reading from console.

readLine() always gets the values as String only. We must cast the Strings into
needed types by using parseXxx() of java.lang.Number abstract class.

Each one try must have one ore more catch.

e.printStackTrace() is used to print detailed exception statements(where exception


is raised, line no, caller, called).

Page 79 of 660
Java Book - Chidambaram.S

Chapter 12 - Array

Array is a collection of same data type variables under one name. Array can be
available in following types.

 One dimensional array


 Two dimensional array
 Three or more dimensional array

Ex: int mark[]=new int[5];

Size 5

Lowerbound 0

Upperbound 4

Element mark[0],mark[1],….mark[4]

Array Name mark

Subscript 0,1,2,3,4

Array

One dimensional array

Type 1

datatype variablename[]=new datatype[size];

int n[]=new int[10];

Type 2

datatype[] variablename=new datatype[size];

int[] n=new int[10];

Page 80 of 660
Java Book - Chidambaram.S

Type 3

datatype variablename[]={value….};

int n[]={1,2,3,4};

String name[]={“java”,”j2ee”};

char ch[]={‘a’,’b’,’c’};

Type 4

datatype variablename[]; // step 1

variablename=new datatype[size]; //step 2

int n[];

n=new int[5];

In type 4 the array can be declared as class scope, then it can be resized within
method at more times.

Two dimensional array

Type 1

datatype variablename[][]=new datatype[rowsize][columnsize];

Ex: int a[][]=new int[2][3]; // a has 6 elements (2*3)

0,0 0,1 0,2

1,0 1,1 1,2

Type 2

datatype variablename[][];

Page 81 of 660
Java Book - Chidambaram.S

variablename=new datatype[rowsize][coulmnsize];

int b[][];

b=new int[2][3];

Type 3

datatype variablename[][]={{values},{values}};

int a[][]={{1,2,3},{1,2,3}};

Three dimensional array

Type 1

int a[][][]=new int[2][2][2];

Type 2

int a[][][];

a=new int[2][2][2];

Four dimensional array

Type 1

int a[][][][]=new int[2][2][2][3];

Type 2

int a[][][][];

a=new int[2][2][2][3];

Jagged arrays

Two or more dimensional can be declared as jagged arrays to allocate memory at run
time.

Runtime memory allocation

Page 82 of 660
Java Book - Chidambaram.S

Ex 1

int a[][]=new int[5][];

a[0]=new int[3];

a[1]=new int[10];

It means a[0] has 3 columns, a[1] has 10 columns.

Ex 2

int a[][][]=new int[2][][];

a[0]=new int[2][3];

a[1]=new int[3][4];

It means a[0] has 2*3 array, a[1] has 3*4 array

Assigning arrays

Arrays can be assigned in java. Consider following syntaxes.

Ex 1

int a[]=new int[2];

int b=a[0]; // One value assign

Ex 2

int a[][]=new int[2][2];

int b[]=a[0]; // One dim assign

int c[]=a[1]; // One dim assign

Ex 3

int a[][][]=new int[2][2][3];

int b[][][]=a; // Three dim assign

Page 83 of 660
Java Book - Chidambaram.S

int c[][]=a[0]; // Two dim assign

int d[]=a[0][0]; // One dim assign

Ex 4

int a[][][][]=new int[2][2][2][2] ;

int b[][]=a[0][0]; // Two dim assign

int c[][][]=a[0]; // Three dim assign

int d[][][][]=a;// Four dim assign

Array sample program to ascending order the given numbers

import java.io.*;

class ArrayAscendingOrder {

public static void main(String arg[]) {

int i = 0, j = 0, n = 0;

DataInputStream dis = new DataInputStream(System.in);

int a[] = new int[10]; //to hold max 10 elements

try {

System.out.println("Enter How Many Elements:");

//dis.readLine() gets the input from user and returns String, so conversion is added
below.

n = Integer.parseInt(dis.readLine());

System.out.println("Enter The Elements:");

for (i = 0; i < n; i++) // to get the numbers

Page 84 of 660
Java Book - Chidambaram.S

a[i] = Integer.parseInt(dis.readLine());

for (i = 0; i < n; i++) {

for (j = i + 1; j < n; j++) {

if (a[i] > a[j]) {

// below code swaps the min value to previous position.

int temp = a[i];

a[i] = a[j];

a[j] = temp;

} // if

} // inner for

} // outer

// to print the result

System.out.println("Ascending Order:");

for (i = 0; i < n; i++)

System.out.println(a[i]);

} // try

catch (Exception e) {

e.printStackTrace();

}// main

}// class

Output

Page 85 of 660
Java Book - Chidambaram.S

Enter How Many Elements:

Enter The Elements:

Ascending Order:

Page 86 of 660
Java Book - Chidambaram.S

Chapter 13 - Call by value, Call by reference,


and Constructor

Call by reference - Passing and returning objects

In call by reference formal parameters and actual parameters are working in


same memory. In java, when you pass object to called function it is known as
call by reference. It means the modification of formal will affect actual
parameter’s memory. Array passing is also a call by reference

See following example

1. class A {
2. int x;
3. }
4.
5. class B {
6. A findBigObject(A a1, A a2)// (1)
7. {
8. if (a1.x > a2.x)
9. return a1;
10. else
11. return a2;
12. }
13. }
14.
15. class C {
16. public static void main(String args[]) {
17. A ob1 = new A();

Page 87 of 660
Java Book - Chidambaram.S

18. A ob2 = new A();


19. ob1.x = 100;
20. ob2.x = 200;
21. B b = new B();
22. A big = b.findBigObject(ob1, ob2); // 2
23. big.x = 300; // 3
24. }
25. }

In above program (1) has the statements to accept A’s two objects and return
A’s object.

(2) Sends two objects and receive object. The technique is that,
findBigObject() returns ob2 and ob2 will be stored in big. Now big refers the
memory of ob2 and big doesn’t have separate memory.

(3) Here we change the x to 300 of big, it reflects ob2 also. Because ob2 and
big are having same memory. The big refers the same memory of ob2.

Call by value

Formal parameters will have memory when actual sends value to formal.

These memories of formal will be destroyed after run time exits from the called
method or block.

In simple words, formal and actual are working in separate memory.

The modification of formal parameter will not affect actual parameter.

Example

1. class A
2. {
3. void sum(int x,int y) // formal parameters
4. {
5. x=x+5;

Page 88 of 660
Java Book - Chidambaram.S

6. y=y+5;
7. System.out.println("sum");
8. System.out.println(x);//15
9. System.out.println(y);//10
10. }
11. public static void main(String arg[])
12. {
13. A ob1=new A();
14. int x=10;
15. int y=5;
16. ob1.sum(x,y);//actual
17. System.out.println("main");
18. System.out.println(x);//10
19. System.out.println(y);//5
20. }
21. }
22.
23. Output
24.
25. sum
26. 15
27. 10
28. main
29. 10
30. 5

Default Constructor

If one class doesn’t have constructor, run time creates default constructor,
when creates the object.

A ob=new A();

Page 89 of 660
Java Book - Chidambaram.S

A() is a default constructor.

Default constructor will be created by run time, if we don't add.

Empty Constructor

We can define an empty constructor in our program. It will not have any
argument.

A()

//code

This constructor will be called automatically by using object creation


statement without passing argument.

Constructor with parameters

More than one constructor can be created in one class. But arguments must be
differentiated. This can be also known as constructor overloading.

We must pass the values to parameterized constructors when we create the objects.

Page 90 of 660
Java Book - Chidambaram.S

Chapter 14 - Modifiers, Static block, Anonymous


object and this keyword

Access Modifier

There are four access modifiers available. They provide scope to class members.

public

It can be accessed in same package and other package.

private

It can be accessed in same class.

default

It can be accessed in same package only, it cannot be accessed in other package.


So it is called as package modifier.

protected

It can be accessed in same package and other package other than other package non
subclass.

Non Access Modifiers

There are so many non access modifiers available. Some modifiers are listed below.
Other modifiers are discussed in appropriate places of following chapters.

transient - refer java.io

volatile – refer thread

Page 91 of 660
Java Book - Chidambaram.S

Access Modifier of class

public, default

If you don’t provide the modifier, the class will have default modifier by
default.

Access modifiers of Method

public, private, protected, default

Access Modifiers of variable

public, private, protected, default

Note

The complete usage of access modifiers are discussed in package concepts.

Using final (Non access modifier)

final modifier can be used in three places.

Variable

Method

Class

Variable

If we declare the variable as final, this variable acts as a constant.

Syntax

final int x=10; // here x is constant. x can’t be changed.

Method

Page 92 of 660
Java Book - Chidambaram.S

If we define the method as final, this method cannot be overridden in subclass.

Syntax

final void get()

Class

If we declare the class as final, that class cannot be extended.

final class A

class B extends A//Error will be raised.

Static variable

More than one object can share static variable.

Static variables are common for objects of the class.

Syntax and explanation

1. class A
2. {
3. static int a=10; // syntax
4. int b=20;
5. public static void main(String arg[])

Page 93 of 660
Java Book - Chidambaram.S

6. {
7. A ob=new A();
8. System.out.println("ob.a:"+ob.a);//10 //objectname.staticvarname
9. A ob1=new A();
10. System.out.println("ob1.a:"+ob1.a);//10
11. ob.a=100;
12. System.out.println("ob.a:"+ob.a);//100
13. System.out.println("ob1.a:"+ob1.a);//100
14. ob.b=30;
15. System.out.println("ob.b:"+ob.b);//30
16. System.out.println("ob1.b:"+ob1.b);//20
17. }
18. }
19.
20. Output
21.
22. ob.a:10
23. ob1.a:10
24. ob.a:100
25. ob1.a:100
26. ob.b:30
27. ob1.b:20

Above program illustrates “static variables are common for all objects”. But
modification of instance variable affects only the invoking object not other
objects.

Static variable can be accessed by using following ways

Within class the static variable can be used by using just using the variable
name.

In other classes, the static variable can be accessed by using following


statements

Classname.staticvariablename

Page 94 of 660
Java Book - Chidambaram.S

Objectname.staticvariablename

There are no differences in above two syntaxes

Static variables can be declared in top of all declarations and below of class
name only.

Static method

static returntype methodname()

Example

static void sum()

Instance variables cannot be accessed within static method.

Instance variables can be accessed within static method by using


objectname.instancevariablename. Because objects will not be passed implicitly to
static method.

Static variables can be accessed in static method and instance method.

Static variables cannot be declared within static method and instance method,
because static variables can be declared only in the class scope.

Static method can be called from other methods by using following syntaxes.

methodname(); // if caller is in same class

Classname.methodname(); // if caller is in either same class or other class.

Page 95 of 660
Java Book - Chidambaram.S

Objectname.methodname();// if caller is in either same class or other class.

1. class A
2. {
3. static int a=10;//it is a static variable
4. int b=20;//instance variable
5. static void sum()//static method
6. {
7. //static int c;//Error
8. System.out.println(a);
9. //System.out.println(b);//Error
10. A ob1=new A();
11. System.out.println(ob1.b);
12. }
13. public static void main(String arg[])
14. {
15. sum();
16. A.sum();
17. A ob=new A();
18. ob.sum();
19. }
20. }
21.
22. Output
23.
24. 10
25. 20
26. 10
27. 20
28. 10
29. 20

Page 96 of 660
Java Book - Chidambaram.S

Syntax

static

Statements;

To execute statements before calling main, we can use static block. If static
block and p.s.v.m are placed in same class the static block will be called
automatically before main.

Static block can access only static members.

If static block is included without main(), the static block of class will be
called, when you create the first object(not for other objects) of the class
before calling constructor.

Anonymous Object

new A().get();

new A() - is the anonymous object

get() is a method of A class.

To call one variable by using anonymous object

System.out.println(new A().a);

Here a is a variable of A class.

Arrays of object

We can create more than one objects by using object array.

Syntax

Page 97 of 660
Java Book - Chidambaram.S

ClassName objectname[]=new ClassName[size];

Ex:

A ob[]=new A[10];

Above statement creates 10 references (not objects) ranging from ob[0] to ob[9].

It should be converted to object before invoking class members by using following


statements.

ob[0]=new A();

..... ....

ob[9]=new A();

or

for (int i=0;i<10;i++)

ob[i]=new A();

Instread arrays of objects we can use objects collection techniques defined in


java.util package to manage more objects in one container.

this keyword

It refers current invoking object. When we call one method by using object, the
invoking object will be avialable as implicit parameter to the method. The
implicit parameter can be referred by using “this” keyword.

Usage of this

this.instancevariablename;

Page 98 of 660
Java Book - Chidambaram.S

this.instancemethodname();

Page 99 of 660
Java Book - Chidambaram.S

Chapter 15 - Inheritance and Delegation

Inheritance

Inheritance is the mechanism to create class hierarchies. Using inheritance we can


create parent class. The parent class can be derived from other child classes. The
child class can access the parent’s instance members by using its object. The
parent class can be known as base class or super class, the child class can be
known as derived class or sub class. Sub class object can have the reference of
super class.

Reusability is the benefit of inheritance. Refer inheritance explanation in OOPS


concepts.

Base class or super class

The class which gives its properties to another class that class is known as base
class or super class.

Derived class or sub class

The class which gets the properties from another class that class is known as sub
class or derived class.

Types of Inheritance

 Single Inheritance
 Multilevel Inheritance
 Multiple Inheritance (*)
 Hierarchical Inheritance
 Hybrid Inheritance (*)

Note

(*) Marked inheritance types are not supported by java.

Page 100 of 660


Java Book - Chidambaram.S

Single Inheritance

Multilevel Inheritance

Multiple Inheritance

Hierarchical Inheritance

Page 101 of 660


Java Book - Chidambaram.S

B C

B C D

Page 102 of 660


Java Book - Chidambaram.S

Hybrid Inheritance

B C

Why java does not support multiple

Because sub class can have two or more parents in multiple inheritance. It raises
ambiguity error. See hybrid inheritance diagram. Consider B,C are having get().
When we invoke get() by using D’s object what get() would be called. In C++ to
over come this situation virtual classes are introduced. In java there is no
virtual classes. Because java developers don’t want to add one child two parent
techniques.

About Multilevel

In this type of inheritance, one class can have one direct super class and so many
indirect super classes.

Example

class A

Page 103 of 660


Java Book - Chidambaram.S

class B extends A

class C extends B

In above Example B is direct super class of C, A is indirect super class of C.

Benefits of multilevel

It can extend more than one class indirectly. But it must get only one immediate
super class.

It can access the direct, indirect class members without using its object.

super

super is a keyword to access super class members from sub class.

Usage of super

Access super class variable

If sub class and super class are having same variable names we can use this
technique.

Syntax

super.variablename;

Access super class constructors

Page 104 of 660


Java Book - Chidambaram.S

We never create the super class object. By using sub class object we access the
super class members. When we create the sub class object, run time first invokes
super class empty constructor or default constructor before calling sub class
constructor.

Then how can we call the parameterized constructor in super class. The answer is
super keyword.

But calling super class constructor should be done from only sub class
constructors

Syntax

super();

super(argument);

Access super class methods

If sub class and super class are having same method names we can use this
technique.

Calling super class method by using sub class should be done from sub class
methods.

To call super class variable from subclass by using super keyword

super.methodname();

super.methodname(argument);

Method overriding

Rewrite the method available from super class in sub class can be known as method
overriding.

After overriding, sub class object calls sub class overridden methods. If you
don’t override the methods in sub class, super class method will be called.

Overriding mechanism should have the same signatures in super and sub classes.

Page 105 of 660


Java Book - Chidambaram.S

It is the way to implement runtime polymorphism

Dynamic Method Dispatch

It is the technology of run time polymorphism. Because run time can only decide
about the places of called methods either super class or sub class. Compiler can’t
find the method matching in overriding. It is Dynamic Method Dispatch.

Object creation for super class and sub classes

Consider A is the super class and B is the sub class.

subclassname objectname =new subclassname();

Ex: B ob=new B();

If we define same methods, same variables in super and sub classes, now this
object will access the subclass methods and sub class variables.

superclassname objectname =new subclassname();

A ob1=new B();

This object first calls A’s empty or default constructor and B’s empty or default
constructor.

If we define same method name in super and sub class, now this object will call
sub class method. If the method is not available in sub class, it will call method
from super class.

If we declare same variable name in super and sub class, now this object will
access the super class variable. This object can’t access sub class variable.

Allowed casting syntaxes between sub class and superclass

A ob=new B(); // correct

B ob=new A();// error

A ob=new A(); // correct

Page 106 of 660


Java Book - Chidambaram.S

B ob1=(B)ob;// error

Because sub class can have super class reference. But super class doesn’t have sub
class reference.

How can assign super class object in subclass reference?

B ob=new B();//sub class object

A ob1 =ob; or A ob1=(A)ob;//sub class assign in super

B ob2 =(B)ob1;//again super class object to sub class object

In this way super class object can assign in sub class reference.

Below two statements are illegal. Because sub class object cannot be created from
super class object.

B ob2=(ob2)ob1;

B ob2=new A();

Delegation

It is the alternative of inheritance. One object is placed inside of another class


object can be known as delegation. It can be achieved by using inheritance. It can
be programmatically achieved by using delegation.

Consider following example

1. class A
2. {
3. B ob1=new B();
4. }
5. class B
6. {
7. int x;
8. }

Page 107 of 660


Java Book - Chidambaram.S

9.
10. class C
11. {
12. public static void main(String ar[])
13. {
14. A a1=new A();
15. System.out.println(a1.ob1.x);
16. }
17. }
18.
19. Output
20.
21. 0

Page 108 of 660


Java Book - Chidambaram.S

Chapter 16 - Abstract Classes and Interfaces

Abstract class

Recall, in java there are two types of classes 1.Concrete class 2.Abstract class.

Abstract class provides the format to its subclass

Abstract class defines what to do and not how to do.

It can have instance methods and concrete methods. Abstract method means that it
has only method declaration with abstract modifier.

Abstract class may come with only instance methods collection or even only
abstract methods collection.

Abstract class can extend another one concrete class

Abstract class can extend another one abstract class

Concrete class can extend another one abstract class.

Abstract class can have instance variables.

Abstract class can implement interfaces. In this situation abstract classes need
not to override the methods of interfaces. The sub classes of abstract class must
override all abstract methods in abstract class and its super interface.

Object creation is not possible for abstract class, but object can be created by
using following syntax

Abstractclassname objectname=new subclassname();

1. abstract class A {
2. abstract int sum(int i, int j);
3.

Page 109 of 660


Java Book - Chidambaram.S

4. abstract int mul(int i, int j);


5.
6. abstract void getString(String str);
7.
8. void callMe() {
9. System.out.println("I am callMe() of abstractClass");
10. }
11.
12. }
13.
14. class B extends A {
15. int sum(int i, int j) {
16. return (i + j);
17. }
18.
19. int mul(int i, int j) {
20. return (i * j);
21. }
22.
23. void getString(String str) {
24. System.out.println(str);
25. }
26. }
27.
28. class AbstractClass1 {
29. public static void main(String args[]) {
30. B b = new B();
31. System.out.println(b.sum(5, 6));
32. System.out.println(b.mul(5, 6));
33. b.getString("Java");
34. b.callMe();
35. }
36. }
37.
38. Output

Page 110 of 660


Java Book - Chidambaram.S

39.
40. 11
41. 30
42. Java
43. I am callMe() of abstractClass

Interface

Interface defines what to do and not how to do.

Interface provides format to its subclass.

One class can implement more than one interfaces.

It is the way to implement multiple inheritance in java.

Difference between interface and abstract class:

Abstract Interface

Abstract class can have Interface can have only


instance methods and abstract methods declaration.
methods.

The modifier of abstract Interface can have only public


class methods can be public modifier even we don't specify
or default, protected,
private.

It has the variable and It has only static constants


constants

It can extend one abstract One interface can extend

Page 111 of 660


Java Book - Chidambaram.S

class, concrete class, another interface only.


interface.

Abstract methods must have Abstract keyword should not


abstract keyword. allowed here

Note

One interface can extend one or more interfaces.

One class can implement one or more interfaces.

Object creation for interface

Interfacename objectname =new subclassname();

Page 112 of 660


Java Book - Chidambaram.S

Chapter 17 - Package and Import Statement

Package

What is package?

Package is the collection of classes and interfaces

To classify the classes we can put into packages for understanding purpose only.

Consider you need different classes with same name “Bank”. It is not possible
to provide name “Bank” to two classes. Create two packages and put one “Bank”
class in one package and another “Bank” class in another package.

The above points are not ultimate purpose of package. Consider you are
developing “vehicle Loan Management” project. In this you are having three
entities.

Vehicle

Loan

Buyer

Now you can create three packages “Vehicle” and keep vehicle related classes
into “vehicle” package and so on.

Because of this, if you need to extend or modify any one concept like vehicle
you can concentrate only about vehicle package, you don’t bother about other
packages.

In java all classes are kept in package. java.io has the classes related to
input and output concepts, java.rmi has the classes related to networking. If java
developers need to add some additional functionalities in network concepts, they
can concentrate only java.rmi and not java.io.

There are 5 types of classes based on package.

Page 113 of 660


Java Book - Chidambaram.S

same class(source class)

same package subclass

same package non subclass

other package subclass

other package non subclass

Access Protection Table

Place of Private Default Protected Public


class

Same class Yes Yes Yes Yes

Same package No Yes Yes Yes


subclass

Same package No Yes(with Yes(with Yes(with


non sub object) object) object
class

Other No No Yes Yes


package sub
class

Other No No No Yes(with
package non object)
sub class

Creating Package

Syntax

package packagename;

class classname

Page 114 of 660


Java Book - Chidambaram.S

Save:

Drive:\packagename\classname.java

Ex:

G:\java\pack1\Pack1A.java

Pack1B.java

Pack1C.java

Pack1Main.java

G:\java\pack2\pack2A1.java

Pack2A2.java

Pack2Main.java

Compile Pack1

G:\java\pack1>javac *.java

G:\java\pack1>set classpath=.;G:\java\

Run Pack1Main.java

G:\java\pack1>java pack1.Pack1Main

Compile Pack2

G:\java\pack2>javac *.java

Run

G:\java\pack2>java pack2.Pack2Main

set classpath

Page 115 of 660


Java Book - Chidambaram.S

When your class files are not found in current folder, you must provide class
path

set path

When java system files are not found, you must provide set path command.

G:\java\>set path=c:\java\jdk1.6\bin

Batch file

If you need to execute your program by executing many commands like set classpath,
you can use batch file.

Batch file is a collection of commands.

When you run batch file, the commands of batch file will be run one by one.

Batch file creation

Way1

Create .txt file in any text editor and rename the extenstion to .bat

Type within x.bat

set path=c:\java\jdk1.6\bin

set classpath=g:\java

java pack2.Pack2Main

Date

Then save the file. Double click on the file can be used to execute batch file.

Importing packages

java.util.*; // 1

Page 116 of 660


Java Book - Chidambaram.S

java.util.Date; // 2

1st statement imports all classes available inutil package. 2nd statement only
imports the Date class. Typically we prefer 2nd way, because it import whatever
needed class for our program. By importing the classes, we don't need to
specify the package name again and again in all the places of program.

For example if you use java.util.Date class in your program at 50 times, you
must use java.util.Date in all placesif you are not importing. We don't follow
this practice.

Instead of this just you can import the java.util package or java.util.Date
class and you can use Date class name in all places instead of using
java.util.Date

Static import (added in 1.5)

To Access the static methods in one class without referring the class name. We
can use following syntax.

import static java.lang.Math.*;

Now we can refer pow() in Math class by using following syntax

System.out.println(pow(4,2)); instead of System.out.println(Math.pow(4,2));

Page 117 of 660


Java Book - Chidambaram.S

Chapter 18 - Class Loader

Bootstrap Class Loader

It loads Java API classess, presents in jre/lib/rt.jar. API classes means built
in classes in packages like java.lang, java.util etc. These are classes that
are part of JDK (Java Development Kit).

This is the parent class loader of all other class loaders

Extensions Class Loader

It loads classes from the JDK extensions directory, usually


$JAVA_HOME/jre/lib/ext directory.

It is the child class of Bootstrap Class Loader.

Application class loader / System Class Loader

It is the child of Extension Class Loader

It loads classes from the current classpath.

Classpath by default is availble in environment variable and also we can set


the classpath.

To print the currently available classpath

echo %CLASSPATH%

Set classpath while compiling java program

javac -classpath c:\jars\jackson-core-2.6.4.jar MyJava.java

OR

Page 118 of 660


Java Book - Chidambaram.S

javac -cp c:\jars\jackson-core-2.6.4.jar MyJava.java

Class loader delegation hierarchy

Whenever JVM needs the class to run, it searches the loaded class. If it is not
found it requests the class loader.

Now the class loader delegation hierarchy is started.

ClassLoader searches in Application Class loader.

If it is found, search will be completed. Else the search will go to extension


class loader.

If extension class loader found the class then runtime loads it, else searching
will go the bootstrap class loader.

If bootstrap class loader found the class then runtime loads it otherwise
ClassNotFoundException will be raised.

Clear the classpath

If your CLASSPATH environment variable was set to a value that is not correct,
or if your startup file or script is setting an incorrect path, then you can
unset CLASSPATH with:

set CLASSPATH=

How to set the environment class variable

In windows go to System Properties dialog

To get the dialog go to control panel in windows and search environment


variable in search box.

Page 119 of 660


Java Book - Chidambaram.S

You can get the link to open the System Properties dialog

In this dialog click "Environment Variables" button

Page 120 of 660


Java Book - Chidambaram.S

In System Variables section Click New if CLASSPATH is not added yet. or click
Edit button to edit the class path

New button provides below dialog and type the variable name and variable value
as below. Click ok

Variable name: CLASSPATH

Page 121 of 660


Java Book - Chidambaram.S

Variable value : F:\jars\jackson-core-2.6.4.jar;F:\jars\jstl.jar - the value is


the example only. We can set any number of class files or jar file using ;
separator with the correct path.

Click OK button. Now the value given in dialog will be appeared as like below
and now we are good in class path setup.

Page 122 of 660


Java Book - Chidambaram.S

Chapter 19 - Auto Box and Auto Unbox,


Transient, Volatile and instance of

AutoBox

Binding value into one number based primitive type object by using assignment
operation can be known as AutoBox.

Example - box primitive value(10) to primitive object (ob)

Integer ob=10;

Auto unboxing

Auto unboxing means retrieving value from object and stored it in one variable
by using assignment statement.

Example

Integer i=new Integer(10);

// primitive object (i) assigned to primitive variable (x)

int x=i;

In prior release the statement will raise the error

Autobox and AutoUnbox can be allowed only with 8 wrapper classes)

Page 123 of 660


Java Book - Chidambaram.S

Transient

Transient is a variable modifier to disallow the encryption. During the


encryption of an object, transient variables are not encrypted.

Encryption is the process to convert original data to encrypted data.


Decryption is the process to convert the encrypted data to its original format.

Ex:

class A

transient int a=10;// Not Encrypted

int b=20;//Encrypted

Now you can encrypt ob1. Now JRE encrypts only b. Because transient variable
‘a’ will not be encrypted.

Volatile modifier

It is also a variable modifier. To ensure the master copy of variable always


reflects its current state, we can add volatile modifier for variable only.
This modifier tells the compiler that it must always use the master copy of the
volatile variable.

Consider thousands of threads are accessing the same instance variables. In


this time all threads will ensure to use last modified value from volatile
variable.

instanceof

Page 124 of 660


Java Book - Chidambaram.S

instanceof is a keyword. It checks the object type with class type. If you need
to create one method to receive A’s object or B’s object, you can use formal
parameter type as Object. In such time you must check what type of object we
receive. It is done by instanceof keyword.

Syntax

if(objectname instanceof ClassName)

Example

void get(Object ob)

if(ob instanceof A)

//code

else if(ob instanceof B)

//code

Page 125 of 660


Java Book - Chidambaram.S

Chapter 20 - Generic classes

When you need to define the class with accepting different parameters
dynamically like previous example with Type Safe, you can use Generic class
concepts. Type Safe means, in previous example get() accepts any type, but
generic method only accepts defined types.

Generic Class declaration

class classname<typename>

Ex:

class A<T> // More than one typenames can be given here.

Generic Class Object Creation

classname<Integer> objectname=new classname<Integer>(intvalue);

classname<String> objectname1=new Classname<String>(stringvalue);

Ex

A<Integer> ob=new A<Integer>(50);

Page 126 of 660


Java Book - Chidambaram.S

Diamond Operator <> in Generics (Added in 1.7)

By using diamond operator <>, we don't need to mention the type in both as like
below example.

A<String> ob1=new A<>("Java");

List<String> nameList=new ArrayList<>();

Map<String,List<String>> namesMap = new HashMap<>();

/* Simple Generics Program */

1. class Gen<T>
2. {
3. T ob;
4. Gen(T o)
5. {
6. ob=o;
7. }
8.
9. T getOb()
10. {
11. return ob;
12. }
13. void showType()
14. {
15. System.out.println("Type of T is "+ob.getClass().getName());
16. }
17. }
18. class OneTypeGenDemo
19. {
20. public static void main(String args[])
21. {
22. Gen<Integer> iob=new Gen<Integer>(88);
23. iob.showType();

Page 127 of 660


Java Book - Chidambaram.S

24.
25. int v=iob.getOb();
26. System.out.println("v="+v);
27.
28. Gen<String> iob1=new Gen<String>("Generics");
29. iob1.showType();
30.
31. String s=iob1.getOb();
32. System.out.println("s="+s);
33. Gen<Integer> iob2;
34. // iob=iob1;
35. iob2=iob;
36. }
37. }
38.
39. Output
40. Type of T is java.lang.Integer
41. v=88
42. Type of T is java.lang.String
43. s=Generics

1. class Two<T,V>
2. {
3. T ob1;
4. V ob2;
5. Two(T ob1,V ob2)
6. {
7. this.ob1=ob1;
8. this.ob2=ob2;
9. }
10.
11. void showTypes()
12. {
13. System.out.println("Type of T is ="+ob1.getClass().getName());

Page 128 of 660


Java Book - Chidambaram.S

14. System.out.println("Type of V is ="+ob2.getClass().getName());


15. }
16.
17. T getOb1()
18. {
19. return ob1;
20. }
21.
22. V getOb2()
23. {
24. return ob2;
25. }
26. }
27.
28. class TwoGen
29. {
30. public static void main(String args[])
31. {
32. Two<Integer,String> ob1=new Two<Integer,String>(100,"Two Type Generics");

33. int i=ob1.getOb1();


34. String str=ob1.getOb2();
35. System.out.println("i="+i);
36. System.out.println("str="+str);
37. ob1.showTypes();
38. }
39. }
40.
41. Output
42.
43. i=100
44. str=Two Type Generics
45. Type of T is =java.lang.Integer
46. Type of V is =java.lang.String

Page 129 of 660


Java Book - Chidambaram.S

Bounded and unbounded wildcards in generics

bounded and unbounded wildcards in generics are used to bound any Type.

"? extends T" and "? super T" are bounded wild cards. "?" is unbounded wild
card.

Bounded wild cards can be divided as upper bounded wild card and lower bounded
wild card.

? extends T is the upper bounded wild card where all types should be the super
class of T

? super T is the lower bounded wild card where all types should be the sub
class of T

Lets see the below example to understand practically

In below example, we are using java.lang.Number class as the type. So the sub
classes can be added in lower bound and upper bound will raise the compile time
error.

import java.util.*;
public class GenericDemo {

public static void main(String[] args) {


// TODO Auto-generated method stub
// upper bound - super classes can only be added
List<? extends Number> numbersList1 = new ArrayList<>();
numbersList1.add(new Integer(4)); // This line will raise compile time
error

//lower bound - sub classes can only be added


List<? super Number> numbersList2 = new ArrayList<>();

Page 130 of 660


Java Book - Chidambaram.S

numbersList2.add(new Integer(4));

Page 131 of 660


Java Book - Chidambaram.S

Chapter 21 - Inner Class, A variable can return


an object and Factory Method

Inner Class

It is possible to define a class within another class; such classes are known
as nested classes.

The scope of nested class is bounded by the scope of its enclosing class. If
class Y is defined within class X, then Y is known to X and not outside of X. A
nested class can access the members of its enclosing class, how ever the
enclosing class does not have access to the members of the nested class.

X – Enclosing class

Y – Nested class

Example

class X

class Y

Types of inner class

static inner class

non static inner class.

Page 132 of 660


Java Book - Chidambaram.S

static inner classes can use enclosing members by using object only. So this
method will be seldom used.

Non static inner classes can use enclosing members directly without object
including private members.

In program printout various inner class examples explain the complete real time
basis techniques.

Example of Non Static Inner Class

Page 133 of 660


Java Book - Chidambaram.S

1. class Outer
2. {
3. int outer_x=100;
4. void test()
5. {
6. Inner inner=new Inner();
7. inner.display();
8. }
9. class Inner
10. {
11. int inner_y=10;
12. void display()
13. {
14. System.out.println("dispaly : outer_x="+outer_x);
15. System.out.println("dispaly : inner_y="+inner_y);
16. }
17. }//inner
18. }//outer
19.
20. class InnerClassDemo
21. {
22. public static void main(String args[])
23. {
24. Outer outer=new Outer();
25. outer.test();
26. Outer.Inner inner = outer.new Inner();
27. inner.display();
28. System.out.println("dispaly : outer_x="+outer.outer_x);
29. }
30. }
31.
32. Output
33.
34. dispaly : outer_x=100
35. dispaly : inner_y=10

Page 134 of 660


Java Book - Chidambaram.S

36. dispaly : outer_x=100


37. dispaly : inner_y=10
38. dispaly : outer_x=100

Example of Static Inner Class

1. class Outer
2. {
3. int x=100;
4. Outer()
5. {
6. System.out.println("I am Outer class Constructor");
7. }
8. static class Inner
9. {
10. int y=200;
11. void sum()
12. {
13. System.out.println("I am sum() of Inner");
14. System.out.println("y="+y);
15. }
16. }//inner
17. void outersum()
18. {
19. System.out.println("I am outer sum() of Outer");
20. System.out.println("x="+x);
21. //System.out.println("y="+y);
22. }
23. }//outer
24.
25. class InnerNewMain2
26. {
27. public static void main(String args[])
28. {

Page 135 of 660


Java Book - Chidambaram.S

29. Outer outer=new Outer();


30. outer.outersum();
31. Outer.Inner oi=new Outer.Inner();
32. oi.sum();
33. }
34. }
35.
36. Output
37.
38. I am Outer class Constructor
39. I am outer sum() of Outer
40. x=100
41. I am sum() of Inner
42. y=200

Page 136 of 660


Java Book - Chidambaram.S

A Variable can return an object

How one variable returns the object. Consider System.out returns


java.io.PrintStream object, how is it possible.

You can also create variable to return the object in your class by using
following syntax.

class B

static A getA;

A ob=B.getA; // to get the object for A by using B’s static variable.

Factory Method

Those which method can be used to create object, this method can be known as
Factory method.

Example

static A getA() // Factory method

return (new A()); // Returns A’s object

calling a Factory method

A ob1=A.getA();

Page 137 of 660


Java Book - Chidambaram.S

Chapter 22 - Java internationalization and


Regular expression concepts

Internationalization is also known as I18N because there are total 18


characters in this word.

Resource Bundle
To add the internationalization to your program, java.util.ResourceBundle class can be
used.

Let's see the below example to understand more better.


Java Program to read the labels from resource
files

Resource properties under src folder

1. package com.book.resourceprgs;
2.
3. import java.util.Locale;
4. import java.util.ResourceBundle;
5.
6. public class ResourceBundleDemo {

Page 138 of 660


Java Book - Chidambaram.S

7.
8. public static void main(String[] args) {
9.
10. // en_US
11. System.out.println("Current Locale: " + Locale.getDefault());
12. ResourceBundle resourceBundleEnUS = ResourceBundle.getBundle("reso
urce");
13.
14. // read en_US.properties
15. System.out.println("Username : " + resourceBundleEnUS.getString("u
sername"));
16. System.out.println("Password : " + resourceBundleEnUS.getString("p
assword"));
17.
18. Locale.setDefault(new Locale("fr", "FR"));
19.
20. // read fr_FR.properties
21. System.out.println("Current Locale: " + Locale.getDefault());
22.
23. ResourceBundle resourceBundlefrFR = ResourceBundle.getBundle("reso
urce");
24. System.out.println("Username : " + resourceBundlefrFR.getString("u
sername"));
25. System.out.println("Password : " + resourceBundlefrFR.getString("p
assword"));
26.
27. }
28.
29. }
30.
31. Output
32.
33. Current Locale: en_US
34. Username : Username
35. Password : Password

Page 139 of 660


Java Book - Chidambaram.S

36. Current Locale: fr_FR


37. Username : Username-French
38. Password : Password-French

Page 140 of 660


Java Book - Chidambaram.S

ListResourceBundle

public abstract class ListResourceBundle

extends ResourceBundle

ListResourceBundle is the abstract class and its sub class must override the
getContents() with return type of an array, where each item in the array is a
pair of objects.

It is the another one way to manage resources for the applications.

ResourceBundle reads the labels from resource files whereas ListResourceBundle


reads the labels from java class.

The implementation of a ListResourceBundle subclass must be thread-safe if it's


simultaneously used by multiple threads. The default implementations of the
methods in this class are thread-safe

Lets see the example to understand more better.

1.
2. import java.util.ListResourceBundle;
3. import java.util.Locale;
4.
5. class MyResources extends ListResourceBundle {
6. protected Object[][] getContents() {
7. return new Object[][] {
8. { "username", "username-eng" }, { "password", "password-
eng" }
9. };
10. }
11. }
12.

Page 141 of 660


Java Book - Chidambaram.S

13. class MyResourcesFr extends ListResourceBundle {


14. protected Object[][] getContents() {
15. return new Object[][] { { "username", "username-
fr" }, { "password", "password-fr" } };
16. }
17. }
18.
19. public class ListResourceBundleDemo {
20.
21. public static void main(String[] args) {
22. // TODO Auto-generated method stub
23.
24. ListResourceBundle myResources = new MyResources();
25.
26. System.out.println(myResources.getString("username"));
27.
28. ListResourceBundle myResourcesFr = new MyResourcesFr();
29.
30. System.out.println(myResourcesFr.getString("username"));
31.
32. }
33.
34. }
35.
36. Output
37.
38. username-eng
39. username-fr

Page 142 of 660


Java Book - Chidambaram.S

Regular Expressions

Regular Expression is a string, to validate the value against with regular


expression.

java.util.regex.Pattern is the java class to compile the regular expressions.


Then Matcher class matcher() will be used to get the string to validate and
matches() method checks the given value with regular expression and returns
true if given value matched with regular expression else it returns false.

Let's see the example below

// Regular expression should be passed to compile method and it is the static


method of Pattern class and returns Pattern object

Pattern p = Pattern.compile("^[a-z]");

//matcher() accepts string to validate

Matcher m = p.matcher("abcd");

/* matches() validates the given string with regular expression and returns
boolean value

*/

boolean b = m.matches();

Regular Expression example

Regular Expression Usage

[abc] a,b, or c only allowed

[^abc] Any character except abc ^ negation


operator in regular expression

Page 143 of 660


Java Book - Chidambaram.S

[a-zA-Z] Allows a-z and A-Z all alphabets

[a-dm-p] Allows a to d and m to p alphabets

[a-z&&[^bc]] Allows all alphabets a to z small


letters except b and c

\d Accepts only number

Regular Expression example

Username regular expression ^[a-z0-9_-]{6,12}$

^ - Starting of regular expression

[] - Allowed ranges we mentioned

{6,12} - Min and max characters allowed

$ - End of regular expression

Password regular expression ((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})

In password regular expression () defines one group and the characters within
each one group is required().

?=.* indicates one or more characters allowed

Page 144 of 660


Java Book - Chidambaram.S

Chapter 23 - Exception Handling

Exception

Runtime Error can be known as Exception. A java exception is an object that


describes an exceptional status. When an exception is raised JRE crates object
for appropriate exception type and throw it to console or appropriate program
block(catch).

All Exception types are the sub classes of java.lang.Throwable. It has two
immediate sub classes, Error and Exception. The immediate sub class of
Exception is RuntimeException. The sub classes of RuntimeException will be
raised at runtime. The sub classes of Error will be raised by runtime like
VirtualMachineErrorNormally you need not to manage these errors in your
program.

Benefits of Exception

If any exception is raised at runtime, the whole program will be terminated if


you don’t handle exception.

By handling exception, only runtime terminates try block and calls catch block.
So that the remaining part will be executed without disturbance.

Key Benefits

Preventing whole program termination.

Log the exception message to track the message by developer to figuer out
when, where and why this exception, so that we can find out root cause and
the solution.

Make useful tasks such as providing clean message to user about exception
instead of runtime’s exception message.

Page 145 of 660


Java Book - Chidambaram.S

Alternative programming can be done when the time of exception.

Types of Exception

 Unchecked Runtime Exception


 Checked Compile time Exception

Unchecked Runtime Exception

These exceptions are the subclasses of RuntimeException.


Compiler doesn’t know and unable to check these exception in program at
compile time.

Checked Compile time Exception

Compiler verifies these exceptions about handling in your program. For example,
IOException, CloneNotSupportedException. These exceptions are the direct sub
classes of Exception.

Caught Exception

Handled exceptions in program.

Uncaught Exception

Unhandled exceptions in program.

Sub classes of RuntimeException

ArithmeticException

S.o.p(5/0); // Infinity

ArrayIndexOutOfBoundsException

Ex: int a[]=new Int[10];

Page 146 of 660


Java Book - Chidambaram.S

For (int i=0;i<=10;i++)

System.out.println(a[i]); // a[10] not available

ArrayStoreException

int a[]=new int[3];

a[0]=”Rama”; // String is invalid

ClassCastException

Ex: A a =new A();

B b=a;// Invalid casting

IllegalArgumentException

Class A

Void sum(int a)

public static void main(String arg[])

A ob=new A();

ob.sum(“Ram”); //”Ram” is not a integer.

IllegalMonitorStateException

Refer in Thread

Page 147 of 660


Java Book - Chidambaram.S

IllegalStateException

Refer in Thread

IllegalThreadStateException

Refer in Thread

IndexOutOfBoundsException

Refer in util

NegativeArraySizeException

int a[]=new int[-5]; // negative number can’t be a array size.

NullPointerException

A ob; // ob is a reference

ob.sum(); // reference can’t invoke the class members.

NumberFormatException

int i=Integer.parseInt(arg[0]); // Consider arg[0]=”Ram”, Ram can’t be converted


to integer.

int j=Integer.parseInt(“10”);//correct

SecurityException

Refer in applet package.

StringIndexOutOfBoundsException

String str=”Rama”;

S.o.p(str.charAt(4)); // 4th character is not found in str.

UnSupportedOperationException

Thrown to indicate that the requested operation is not supported.

Page 148 of 660


Java Book - Chidambaram.S

Checked Exception classes

ClassNotFoundException

Given class file is not found in given path. Refer in Package concepts

CloneNotSupportedException

Refer java.lang package.(clone concept)

IllegalAccessException

Accessing corrupted class file.

InstansitationException

Attempt to create the object for abstract class or interface.

InterruptedException

Refer Thread

NoSuchFieldException

A required field is not found in class.

NoSuchMethodException

A required method is not found in class.

Five keywords to manage exceptions

try

catch

finally

throw

Page 149 of 660


Java Book - Chidambaram.S

throws

try .. catch

Exception blocks can be constituted by using try block. It means one method can
have one or more try blocks.

Each one try block should have one catch and more than one catch is also allowed.

If any exception is raised at runtime, JRE created Exception object (For example,
if we add the calculation like 5/0 in program, JRE creates an object for
java.lang.ArithmeticException) and the object will be handed over to appropriate
catch block.

If catch block is not found, it will be thrown to console and program execution
continues after the try block.

syntax

try{}

catch(Exception e){}

finally

This block will be executed all time either exception is raised or not. If you
need to do some tasks such as closing database connections, closing opened files,
the tasks can be written within finally block.

Syntax

try{}

catch(Exception e){}

finally{}

throw

Page 150 of 660


Java Book - Chidambaram.S

To throw the exception explicitly. Because exception will be thrown by runtime. We


can create our own exception, In such time we can use throw keyword to raise our
own exception. throw can also be used to throw predefined exceptions.

Syntax

throw ThrowableObject;

Example

throw new ArithmeticException();

throws

It tells compiler, the called function doesn’t have try catch to handle exception
and if exception is raised go to caller to search catch blocks.

It is the mechanism to manage following two things

To manage exceptions at common method

To terminate the common method if any method raises exception.

Syntax

void m1() throws Exception

void m2() throws Exception

{
}

void caller() // common method

try

Page 151 of 660


Java Book - Chidambaram.S

m1();

m2();

catch(Exception e)

Try usage types

Nested Try

try can be nested. Consider following example.

outer try

try

try

catch(Exception e){}

catch(Exception e){//2.3}

catch(Exception e){//1.3}

Page 152 of 660


Java Book - Chidambaram.S

Above example illustrates how try can be nested. More number of nested is allowed.

If 1.1 portion raises exception all inner try and 1.2 also terminated and 1.3
catch block will be called.

If 1.2 portion raises exception, control exits from try and 1.3 catch block calls.

If 2.1 portion raises exception, only 3 try will be terminated, but code 1.2 will
be executed and 2.3 catch will be called.

If 3 try portion raises exception, 1.1,2.1,2.2,1.2 will be executed and 3.1 is


terminated. 3.2 catch will be called.

Multiple try

In one method we can add more than one try.. catch blocks like follows

void m1()

try{//1}catch(Exception e){}

try{//2}catch(Exception e){}

try{//3}catch(Exception e){}

The benefit is that, if 1 block raises exception, 2,3 will be executed and so on.

Try and Finally

Like try..catch..finally, we can add try..fianlly block like follows.

try

finally

Page 153 of 660


Java Book - Chidambaram.S

{
}

If any exception is raised within the try block, exception will be sent to
console, and finally block will be called.

The benefit is that, if we need to do following things, we can use this method.

Exception should be sent to console.

If exception is raised, other statements of method should be executed.

In exception time, we can do some other tasks in finally.

Try with multiple catch

One try can have more than one catch blocks like follows.

try{}

catch(ArrayIndexOutOfBoundsException ai){}

catch(StringIndexOutOfBoundsException si){}

catch(NumberFormatException nfe){}

The benefit of above technique is that, if any one of three exception is raised
the appropriate catch block will be called at run time.

But other than handled exception is raised, the exception goes to console. To
avoid this, just add following catch block at last.

catch(Exception e){}

It means, if any exception other than handled three exception is raised, the
catch(Exception e){} block will be called by runtime. Because all exception
classes are the sub classes of Exception.

try catch - with multiple exception in one catch (Added in


1.7)

Page 154 of 660


Java Book - Chidambaram.S

Since java 1.7, we can add more that one exception in catch block instead writing
many catch blocks. Let's see the below example to understand how the block can be
written.

int a=10, b =0;

try

int c = a/b;

catch(ArithmeticException | ArrayIndexOutOfBoundsException |
NullPointerException e)

e.printStackTrace();

try with resources (Added in 1.7)

try with resources is used to close the resources of files or sockets or JDBC
objects etc. The resources (say objects) opened in try block automatically will be
closed when the execution control passes out try block. No need to write separate
code to close the objects. The notable thing is that an object which implements
java.lang.AutoCloseable method is eligible to close automatically.

public interface java.lang.AutoCloseable {

public abstract void close() throws java.lang.Exception;

Example :

public static void main(String args[]) {

Page 155 of 660


Java Book - Chidambaram.S

try ( // below two objects are eligible to close when try block execution
completed.

FileReader fr = new FileReader("abc.txt");

FileWriter fw = new FileWriter("def.txt");

{//try block started here

// some file copying code

} // at this point fr and fw are closed

catch (IOException e)

e.printStackTrace();

Own Exceptions

We can define our own exceptions like predefined exceptions. Our own exception
class should be the sub class of Exception class.

The benefit is that we can handle our application based run time exceptions like
AgeExceededException, InvalidRupeesFormatException. The name of exceptions can be
defined as per your need and willingness.

Because of you can define your exceptions in separate package and you can separate
the exception handling part from your application.

Once we create the exception handling part it can be used in many applications.

Sample program

Page 156 of 660


Java Book - Chidambaram.S

Above two classes illustrate how exception should be defined and how the exception
can be thrown. Listen, the AgeExceededException overrides toString() Object class.
It means when GetAge class prints AgeExceededException class object, the
toString() of AgeExceededException class will be called.

Throwable class methods

String getMessage()

It returns the small description of exception message.

void printStackTrace(PrintStream stream)

It sends the Exception to specified Stream.

void printStackTrace(PrintWriter stream)

It sends the Exception to specified Stream.

void printStackTrace()

It prints detailed exception message in console with Caller, called method,


exception message, line number.

Page 157 of 660


Java Book - Chidambaram.S

Chapter 24 - Multithreaded Programming and


ThreadGroup

Thread

A multithreaded program contains two or more parts that can run concurrently
(Parallel). Each part of such a program is called a thread, and each thread
defines a separate path of execution.

Multithreading is the mechanism to implement multitasking.

Threads are executed in parallel way and not simultaneously.

States of Thread
A thread state. A thread can be in one of the following states:
NEW
A thread that has not yet started is in this state.

RUNNABLE
A thread executing in the Java virtual machine is in this state.

BLOCKED
A thread that is blocked waiting for a monitor lock is in this state.

WAITING
A thread that is waiting indefinitely for another thread to perform a
particular action is in this state.

Page 158 of 660


Java Book - Chidambaram.S

TIMED_WAITING
A thread that is waiting for another thread to perform an action for up to a
specified waiting time is in this state.

TERMINATED
A thread that has exited is in this state.

public Thread.State getState() - added in Java 1.55

Returns the state of this thread. This method is designed for use in monitoring
of the system state, not for synchronization control.

Returns: this thread's state.

Benefits of Threads

To utilize the CPU’s idle time threads can be used. For example your program
waits to get file path form user. The user takes some seconds to provide the
file path. In the seconds, your program waits, it wastes CPU’s process. In mean
time you can do other tasks in your program by using other threads.

The execution of one thread will not affect another thread’s process.

Single threaded system

Single threaded system can be known as Event polling system.

Types of multitasking

Process based or Multitasking Processed

Thread based or Multitasking threads

Page 159 of 660


Java Book - Chidambaram.S

Process based or Multitasking Processed

Process based multitasking is the feature to enable to run two or more


different applications in one system. (running calculator and Msword at same
time)

Thread based or Multitasking threads

Thread based multitasking is the feature to run two or more parts in one
application. (Running spell check in Msword, and printing the document)

Difference between thread based and process based

Multitasking threads require less overhead than multitasking processes. In


process based threads Processes are heavyweight tasks that require their own
separate address space. Interprocess communication is expensive and limited.
Context switching from one process to another is also costly. In Thread based
threads Interthread communication is inexpensive, and context switching form
one thread to the next is low cost.

In java thread based multitasking can be done.

Thread creation

There are two ways to create a new thread.

One is to declare a class to be a subclass of Thread. This subclass should


override the run method of Thread class.

The other way to create a thread is to declare a class that implements the
Runnable interface. The class then override the run method.

Way 1

Page 160 of 660


Java Book - Chidambaram.S

class A extends Thread

public void run()

public static void main(String arg[])

A ob=new A();

ob.start(); //or ob.run();// // to start thread.

Way 2

class A implements Runnable

public void run()

public static void main(String arg[])

A ob=new A();

Thread t=new Thread(ob); // ob is the Runnable object

t.start(); //or t.run();// to start thread

Page 161 of 660


Java Book - Chidambaram.S

In way 1, we extend Thread class and override run(). The technique is that the
tasks of thread should be given within run(). The problem of way 1 is that we
can’t extend no other classes. Because java supports multilevel only.

If you need to create Applet, your class must be the sub class of Applet. In
this situation, you can’t do it, if your class is the sub class of Thread.

In way 2, we implement Runnable interface. Thread is the sub class of Runnable.


In such time we can extend another one class.

2nd way is the best way to create thread.

Thread Priorities and Context switching

Java assigns to each thread a priority that determines how that thread should
be treated with respect to others.

A higher priority thread doesn’t run faster than lower priority thread.

A thread’s priority is used to decide when to switch from one running thread to
the next. This is called as context switch.

Default thread priority is 5

Thread priority ranges between 1 and 10

If more than one thread has same priority. Then OS follows Round Robin
fashion(Time Slicing). By using this method, same priority threads have
particular time to utilize the CPU resource.

Preemptive multitasking

Page 162 of 660


Java Book - Chidambaram.S

A Thread can be preempted by a higher priority Thread. In this case a lower


priority Thread that does not yield the processor is simply preempted.

A higher priority thread wants to run it does. This is called preemptive


multitasking.

Synchronization

Multithreading is asynchronous process. Some times we need to do ensure only


one thread executes at one time.

For example GetItem thread gets items from user. In same time Bill thread must
wait to finish the tasks of GetItem thread. After completion of GetItem thread,
the Bill thread makes billing then GetItem thread starts its work to get items
from next customer.

To implement above need, java provides clean solution “Monitor”. Monitor is


nothing but, it is an object. Once a thread is inside a synchronized method of
one object, now the object becomes monitor and no other thread can’t enter to
call other synchronized methods of same object.

This is synchronization.

Synchronization can be achieved by using two ways.

1) synchronized as a keyword

synchronized(obj){}

2) synchronized as a modifier

class A

synchronized void getItem(){}

synchronized void bill(){}

Page 163 of 660


Java Book - Chidambaram.S

Messaging or Inter Thread communication

In synchronization diagram we can understand following things

T1, T2 are threads and ob1 is the object which has two methods getItems(),
bill().

T1 enters into getItem() and T2 tries to call bill and it waits until the
completion of T1. Because getItems(), bill() are synchronized methods.

Now ob1 is a monitor after entering T1 into ob1.

In Messaging or Inter thread communication diagram we can understand about


following things.

T1 enters into getItem() and finishes 75% code.

After wait() statement occurs and it goes to waiting state.

T2 enters into bill and complete 100% code and notifies T1 then it goes to
waiting state.

T1 reenters getItem() and completes 25% code.

Here inter thread communication is that cooperation of T1 and T2 by using


wait() and notify() of Object class.

Page 164 of 660


Java Book - Chidambaram.S

Synchronization diagram

ob1

synchronized getItem()

{
T1
//code

synchronized bill()
Waits here to
call bill() after t1 {
T2 exits from ob1
//code

Page 165 of 660


Java Book - Chidambaram.S

Messaging or Inter thread communication diagram

ob1

T1 1 synchronized getItem()

{
Waiting state
//75%code
2
wait();

notify triggered 4 //25%code

noifty();

synchronized bill()
T2 3 {

//100% code

notify();

wait();

Page 166 of 660


Java Book - Chidambaram.S

Deadlock diagram

ob1

synchronized m1()
T1 Waits to call
{ m2()

//code

synchronized m2()

//code

ob2

synchronized n1()

{
T2 Waits to call n2()
//code

synchronized n2()

//code

Page 167 of 660


Java Book - Chidambaram.S

Above diagram illustrates

 T1 enters into ob1 and calls m1() then it tries to call n2() of ob2.

 T2 enters into ob2 and calls n1() then it tries to call m2() of ob1.

 T1 waits to enter into ob2 and T2 waits to enter into ob1.

 Now you can understand the problem.

 T1 never comes from ob1 and T2 never comes from ob2.

 This is deadlock

 Deadlock occurs when two threads have a circular dependency on a pair of synchronized objects.

Page 168 of 660


Java Book - Chidambaram.S

Deadlock Sample Program.

1. import java.io.*;
2. class A
3. {
4. B b;
5. void getObject(B b)
6. {
7. this.b=b;
8. }
9. synchronized void m1()
10. {
11. System.out.println("I am m1 method");
12. try
13. {
14. Thread.sleep(1000);
15. }
16. catch(Exception e){}
17. b.n2();
18. }
19. synchronized void m2()
20. {
21. System.out.println("I am m2");
22. }
23. }
24.
25. class B
26. {
27. A ob1;
28. void getObject(A ob1)
29. {
30. this.ob1=ob1;
31. }
32. synchronized void n1()
33. {

Page 169 of 660


Java Book - Chidambaram.S

34. System.out.println("I am n1 method");


35. try
36. {
37. Thread.sleep(1000);
38. }
39. catch(Exception e){}
40. ob1.m2();
41. }
42. synchronized void n2()
43. {
44. System.out.println("I am n2");
45. }
46. }
47.
48. class GetItemThread implements Runnable
49. {
50. A ob1;
51. Thread t1=new Thread(this);
52. GetItemThread(A ob1)
53. {
54. this.ob1=ob1;
55. t1.start();
56. }
57. public void run()
58. {
59. //while(true)
60. for(int i=0;i<3;i++)
61. ob1.m1();
62. }//run
63. }//class
64.
65. class BillThread implements Runnable
66. {
67. B ob2;
68. Thread t2=new Thread(this);

Page 170 of 660


Java Book - Chidambaram.S

69. BillThread(B ob2)


70. {
71. this.ob2=ob2;
72. t2.start();
73. }
74. public void run()
75. {
76. //while(true)
77. for(int i=0;i<3;i++)
78. ob2.n1();
79. }//run
80. }//class
81.
82. class DeadLockDemo
83. {
84. public static void main(String args[])
85. {
86. A ob1=new A();
87. B ob2=new B();
88. ob1.getObject(ob2);
89. ob2.getObject(ob1);
90. GetItemThread git=new GetItemThread(ob1);
91. BillThread bill=new BillThread(ob2);
92. }
93. }
94.
95. Output
96.
97. I am m1 method
98. I am n1 method

Constructors of Thread class

Thread()

Page 171 of 660


Java Book - Chidambaram.S

Allocates new Thread object

Thread(Runnable target)

Creates a new Thread object with given target. Here target should be a sub class
of Runnable object. It means starting thread calls target’s run().

Thread(Runnable target,String name)

Same as above constructor but we can provide the name for our thread.

Thread(String name)

Creates thread with given name.

Thread(ThreadGroup group,Runnable target)

Creates Thread object with target and this thread becomes a member of specified
group.

Thread(ThreadGroup group,Runnable target,String name)

Same as above method with given name.

Methods of Thread class

static void activeCount()

Returns the number of active threads in the current thread's thread group.

static Thread currentThread()

Main is also thread. When you start one program first main() will be called by OS.
It means one thread will be started by default.

To obtain the main thread the currentThread() can be used.

Main is also a thread. It means, When you start one new prg , java really starts one
new thread. Below program explains how to obtain the current thread and its usage.

Page 172 of 660


Java Book - Chidambaram.S

1. class CurrentThread
2. {
3. public static void main(String args[])
4. {
5. Thread ct=Thread.currentThread(); // obtain current thread
6. System.out.println("ct="+ct);
7. System.out.println("ct.getName()="+ct.getName());
8. System.out.println("ct.getPriority()="+ct.getPriority());
9. ct.setName("My Thread");
10. ct.setPriority(10);
11. System.out.println("After Set Priority");
12. System.out.println("ct.getName()="+ct.getName());
13. System.out.println("ct.getPriority()="+ct.getPriority());
14. }
15. }
16.
17. Output
18.
19. ct=Thread[main,5,main]
20. ct.getName()=main
21. ct.getPriority()=5
22. After Set Priority
23. ct.getName()=My Thread
24. ct.getPriority()=10

void sleep(long milliseconds ) throws InterruptedException

void sleep(long milliseconds, int nanosecond) throws InterruptedException

103 Milliseconds = 1 second

109 Nanoseconds = 1 second

To stop one thread temporary at given seconds. It is static method, so we can call
this method in any program other than thread program.

Page 173 of 660


Java Book - Chidambaram.S

void setName(String name)

By default thread has one name by JRE. You can provide your needed name to
thread by using this method.

String getName()

To get the name of Thread

void setPriority(int priority)

To set the new priority for one thread. The default priority is 5.

The priority value should be between 1 and 10.

You can alternatively use following Thread class constants instead of provide
the integer numbers. There is no difference between providing integers and
providing following constants of Thread class.

static int MIN_PRIORITY=1

static int MAX_PRIORITY=5

static int NORM_PRIORITY=10

for example

t.setPriority(Thread.MIN_PRIORITY) (or)

t.setPriority(1) // both are same.

void join() throws InterruptedException

To ensure only one thread utilizes the CPU and other joined threads must wait to
completion of first thread.

Here you can recall the synchronization, synchronization ensures no other thread
exits into monitor, if one thread enters into monitor.

But join ensures no other joined threads started until the completion of all tasks
of first thread.

Page 174 of 660


Java Book - Chidambaram.S

Syncronization Program Example - Without Syncronization

1. class Item {
2. int x;
3.
4. synchronized void get() {
5. System.out.println("I am get");
6. try {
7. Thread.sleep(1000);
8. } catch (Exception e) {
9. e.printStackTrace();
10. }
11. System.out.println("I am get after sleep");
12. }
13.
14. synchronized void put() {
15. System.out.println("I am put");
16. }
17. }
18.
19. class Thread1 implements Runnable {
20. Item ob;
21. Thread t;
22.
23. Thread1(Item ob) {
24. this.ob = ob;
25. t = new Thread(this);
26. t.start();
27. }
28.
29. public void run() {
30. for (int i=0;i<5;i++) {
31. ob.get();
32. try {

Page 175 of 660


Java Book - Chidambaram.S

33. Thread.sleep(1000);
34. }
35. catch (Exception e) {
36. e.printStackTrace();
37. }
38. }
39. }
40. }
41.
42. class Thread2 implements Runnable {
43. Item ob;
44. Thread t;
45.
46. Thread2(Item ob) {
47. this.ob = ob;
48. t = new Thread(this);
49. t.start();
50. }
51.
52. public void run() {
53. for (int i=0;i<5;i++) {
54. ob.put();
55. try {
56. Thread.sleep(1000);
57. }
58. catch (Exception e) {
59. }
60. }
61. }
62. }
63.
64. class SynchronizedDemo {
65. public static void main(String args[]) {
66. Item ob = new Item();
67. Thread1 t1 = new Thread1(ob);

Page 176 of 660


Java Book - Chidambaram.S

68. Thread2 t2 = new Thread2(ob);


69. }
70. }
71.
72. Output
73.
74. I am get
75. I am get after sleep
76. I am put
77. I am get
78. I am get after sleep
79. I am put
80. I am put
81. I am get
82. I am get after sleep
83. I am put
84. I am put
85. I am get
86. I am get after sleep
87. I am get
88. I am get after sleep

Program explanation to understand about synchronization

1. Item is the class and ob is an object for Item class.


2. Thread1, Thread2 are the threads.
3. In main method the same ob object is shared to Thread1 and Thread2.
4. Thread1 and Thread2 calls get() and get() prints "I am get" and gets interval
by calling sleep(1000). 1000 means 1 sec.
5. During this time, runtime waits and calls the remaining statement of get().
6. Once get() is completely executed the put() is invoked.
7. The 5th statement is achieved by using synchronized modifier. If we remove
the synchronized, instead of waiting runtime invokes the put()

final ThreadGroup getThreadGroup()

Page 177 of 660


Java Book - Chidambaram.S

Returns the ThreadGroup object of invoking thread object.

final void suspend()- Deprecated

To stop thread temporarily until calls resume(). The suspended thread can only
be resumed but not restarted, if we try to restart the suspended thread,
java.lang.IllegalThreadStateException will be raised.

final void stop() – Deprecated

The running Thread can be stopped by using stop(). After stopped resume()
cannot be used, but you can call this method. start() cannot be worked after
calling stop(), if so java.lang.IllegalThreadStateException will be raised.

stop() cannot work properly. Use return() statement to stop thread properly.

final void resume()- Deprecated

A suspended Thread can be released by using this method, before using resume()
the thread should be suspended.

void start()

To start one Thread.

static void yield()

To allow temporarily other thread to utilize the CPU, invoking thread should
have normal priority to work yield() properly.

final boolean isAlive()

If this thread is alive, it returns true

java.lang.Object provides following three methods to manages inter thread


communication instead of suspend() resume() methods.

final void wait() throws InterruptedException

It tells the calling thread to give up the monitor and go to sleep until some
other thread enters into same monitor and calls notify.

Page 178 of 660


Java Book - Chidambaram.S

final void notify()

Wakes up a sleeping thread that called wait() of the same object.

final void notifyAll()

Wakes up all sleeping threads that called wait() of the same object.

java.util.concurrent based threads (1.5)

1.CountDownLatch

2.Semephore

3.CyclicBarrier

CountDownLatch

It is a class to ensure set of code should be waited until some threads finishes
their execution.

For example main() starts 5 threads to download the file from server. main() needs
to start another one thread to assemble the downloaded file from server after 5
threads execution complete. In this situation you can use this class.

Constructors

CountDownLatch(int count)

Here count can be used to specify number of threads should be finished to start
the code after await().

The below program explains the usage of

CountDownLatch

Synchonized

wait(), notify()

Page 179 of 660


Java Book - Chidambaram.S

1. import java.io.*;
2. import java.util.concurrent.*;
3.
4. class Shop {
5. String itemname[] = new String[10];
6. double qty[] = new double[10];
7. double rpu[] = new double[10];
8. int choice;
9. int q = 0;
10. double total[] = new double[10];
11.
12. synchronized void getItemDetails() {
13. try {
14. DataInputStream dis = new DataInputStream(System.in);
15. System.out.println("Enter Item Name");
16. itemname[q] = dis.readLine();
17. System.out.println("Enter Qty");
18. qty[q] = Double.parseDouble(dis.readLine());
19. System.out.println("Enter Rate Per Unit");
20. rpu[q] = Double.parseDouble(dis.readLine());
21. try {
22. /* invoking wait() gives up cpu to another waiting thread now bill thread
will be invoked
23. */
24. wait(); // Object class
25. } catch (Exception e) {
26. }
27. notify();
28. } catch (Exception e) {
29. }
30. }
31.
32. synchronized void bill() {

Page 180 of 660


Java Book - Chidambaram.S

33. try {
34. total[q] = qty[q] * rpu[q];
35. q++;
36. /* notify wake up another waiting thread of same object. Here same object
is Shop object*/
37.
38. notify();
39. wait();
40. } catch (Exception e) {
41. }
42. }
43.
44. synchronized void printFormat() {
45. int i = 0;
46. double granttotal = 0;
47. System.out.println("----------------------------------------------
--------------------");
48. System.out.print("S.No ");
49. System.out.print("\t ITEM NAME ");
50. System.out.print("\t ITEM RATE ");
51. System.out.print("\tQUANTITY ");
52. System.out.println("\tTOTAL ");
53. System.out.println("----------------------------------------------
--------------------");
54. for (i = 0; i < 4; i++) {
55. System.out.print(i);
56. System.out.print("\t" + itemname[i]);
57. System.out.print("\t\t" + rpu[i]);
58. System.out.print("\t\t" + qty[i]);
59. System.out.println("\t\t" + total[i]);
60. granttotal = granttotal + total[i];
61. }
62. System.out.println("\t \t \tGRANT TOTAL :" + granttotal);
63. System.out.println("----------------------------------------------
--------------------");

Page 181 of 660


Java Book - Chidambaram.S

64. }
65. }
66.
67. class GetItemThread implements Runnable {
68. Shop s;
69. Thread t1 = new Thread(this);
70. CountDownLatch cdl;
71.
72. GetItemThread(Shop s, CountDownLatch cdl) {
73. this.s = s;
74. this.cdl = cdl;
75. t1.start();
76. }
77.
78. public void run() {
79. while (true) {
80. System.out.println("Item Thread :" + cdl.getCount());
81. s.getItemDetails();
82. cdl.countDown();
83. }
84. }
85. }
86.
87. class BillThread implements Runnable {
88. Shop s;
89. Thread t2 = new Thread(this);
90. CountDownLatch cdl;
91.
92. BillThread(Shop s, CountDownLatch cdl) {
93. this.s = s;
94. this.cdl = cdl;
95. t2.start();
96. }
97.
98. public void run() {

Page 182 of 660


Java Book - Chidambaram.S

99. while (true) {


100. System.out.println("Bill Thread :" + cdl.getCount());
101. s.bill();
102. cdl.countDown();
103. try {
104. Thread.sleep(1000);
105. } catch (Exception e) {
106. System.out.println(e);
107. }
108. }
109. }
110. }
111.
112. class PrintFormatThread implements Runnable {
113. Shop d;
114. Thread t3 = new Thread(this);
115.
116. PrintFormatThread(Shop d) {
117. this.d = d;
118. t3.start();
119. }
120.
121. public void run() {
122. System.out.println("printthread=" + 1);
123. d.printFormat();
124. System.out.println("printthread=" + 2);
125. }
126. }
127.
128. class CountDownLatchWithSynchonizedDemo {
129. public static void main(String args[]) {
130. Shop s = new Shop();
131. CountDownLatch cdl = new CountDownLatch(8);
132. GetItemThread git = new GetItemThread(s, cdl);
133. BillThread bill = new BillThread(s, cdl);

Page 183 of 660


Java Book - Chidambaram.S

134. try {
135. /*
136. * Runtime waits here to call below statement until countDownL
atch value reaches
137. * 8 The 8 is given in CountDownLatch Constructor
138. */
139. cdl.await();
140. } catch (Exception e) {
141. System.out.println(e);
142. }
143. git.t1.stop();
144. bill.t2.stop();
145. git.t1 = null;
146. bill.t2 = null;
147. System.out.println("Both Threads Finished");
148. PrintFormatThread pri = new PrintFormatThread(s);
149. System.out.println("Printing Threads Finished");
150. }
151. }
152.
153. Output
154.
155. Item Thread :8
156. Bill Thread :8
157. Enter Item Name
158. item1
159. Enter Qty
160. 2
161. Enter Rate Per Unit
162. 50
163. Item Thread :6
164. Enter Item Name
165. Bill Thread :6
166. item2
167. Enter Qty

Page 184 of 660


Java Book - Chidambaram.S

168. 3
169. Enter Rate Per Unit
170. 45
171. Item Thread :5
172. Enter Item Name
173. iBill Thread :4
174. tem3
175. Enter Qty
176. 5
177. Enter Rate Per Unit
178. 60
179. Item Thread :3
180. Enter Item Name
181. Bill Thread :2
182. item4
183. Enter Qty
184. 4
185. Enter Rate Per Unit
186. 30
187. Item Thread :1
188. Enter Item NameBoth Threads Finished
189. Printing Threads Finished
190. printthread=1
191. ------------------------------------------------------------------
192. S.No ITEM NAME ITEM RATE QUANTITY TOTAL
193. ------------------------------------------------------------------
194. 0 item1 50.0 2.0 100.0
195. 1 item2 45.0 3.0 135.0
196. 2 item3 60.0 5.0 300.0
197. 3 item4 30.0 4.0 120.0
198. GRANT TOTAL :655.0
199. ------------------------------------------------------------------
200. printthread=2

Page 185 of 660


Java Book - Chidambaram.S

Methods

public void await()

The statements found after await() will not executed until count reaches 0.

void countdown()

To decrease 1 with count.

long getCount()

Returns the current count.

Semaphore

To ensure particular number of threads can utilize the CPU’s resource at one
time.

Constructors

Semaphore(int permits)

permits defines number of threads can be allowed at one time.

Methods

void acquire()

This method gets permit from semaphore.

void release()

It releases the permit from semaphore, and semaphore will provide the
permit to another one thread.

CyclicBarrier

Page 186 of 660


Java Book - Chidambaram.S

To execute one thread whenever particular number of threads tasks are completed.

Constructors

CyclicBarrier(int nos,Runnable t1)

After completion of nos threads , t1 will be evaluated. If nos is 5, then


JRE calls t1 after completion of 5 threads.

Methods

int await()

To tell JRE that one thread finishes its work.

int getParties()

To get number of parties assigned in CyclicBarrier constructor.

1. /*
2. public CyclicBarrier(int parties,
3. java.lang.Runnable r)
4. public int await()
5. throws java.lang.InterruptedException,
6. BrokenBarrierException
7. public int getParties()
8. */
9. import java.util.concurrent.*;
10.
11. class CyclicBarrierDemo {
12. public static void main(String args[]) {
13. BarAction obj = new BarAction();
14. /*
15. First argument of CyclicBarrierConstructor instructs runtime to invoke obj
thread(second argument) whenever two threads are completed
16. */

Page 187 of 660


Java Book - Chidambaram.S

17. CyclicBarrier cb = new CyclicBarrier(2, obj); System.out.pri


ntln("Starting...");
18. Thread1 t1 = new Thread1(cb, "Thread1");
19. Thread2 t2 = new Thread2(cb, "Thread2");
20. Thread3 t3 = new Thread3(cb, "Thread3");
21. Thread4 t4 = new Thread4(cb, "Thread4");
22. System.out.println(cb.getParties());
23. }
24. }
25.
26. class Thread1 implements Runnable {
27. CyclicBarrier cbar;
28. String name;
29.
30. Thread1(CyclicBarrier cbar, String name) {
31. this.cbar = cbar;
32. this.name = name;
33. new Thread(this).start();
34. }
35.
36. public void run() {
37. try {
38. System.out.println(name);
39. cbar.await();
40. } catch (Exception e) {
41. }
42. }
43. }
44.
45. class Thread2 implements Runnable {
46. CyclicBarrier cbar;
47. String name;
48.
49. Thread2(CyclicBarrier cbar, String name) {
50. this.cbar = cbar;

Page 188 of 660


Java Book - Chidambaram.S

51. this.name = name;


52. new Thread(this).start();
53. }
54.
55. public void run() {
56. try {
57. System.out.println(name);
58. cbar.await();
59. } catch (Exception e) {
60. }
61. }
62. }
63.
64. class Thread3 implements Runnable {
65. CyclicBarrier cbar;
66. String name;
67.
68. Thread3(CyclicBarrier cbar, String name) {
69. this.cbar = cbar;
70. this.name = name;
71. new Thread(this).start();
72. }
73.
74. public void run() {
75. try {
76. System.out.println(name);
77. cbar.await();
78. } catch (Exception e) {
79. }
80. }
81. }
82.
83. class Thread4 implements Runnable {
84. CyclicBarrier cbar;
85. String name;

Page 189 of 660


Java Book - Chidambaram.S

86.
87. Thread4(CyclicBarrier cbar, String name) {
88. this.cbar = cbar;
89. this.name = name;
90. new Thread(this).start();
91. }
92.
93. public void run() {
94. try {
95. System.out.println(name);
96. cbar.await();
97. } catch (Exception e) {
98. }
99. }
100. }
101.
102. class BarAction implements Runnable {
103. public void run() {
104. System.out.println("Barrier Reached");
105. }
106. }
107.
108. Output
109.
110. Starting...
111. Thread1
112. Thread2
113. Barrier Reached
114. Thread3
115. 2
116. Thread4
117. Barrier Reached

Page 190 of 660


Java Book - Chidambaram.S

ThreadGroup

It is the class of java.lang package. It is used to manage the thread groups.

Consider following example,

You need to create threads for each one client, those joins in network. In such
time your program uses some other threads to manage other works.

Here you can group the client threads to avoid the complication with other
threads.

The benefit is that you can supend(), resume(), stop(), list() the threads by
using single command.

Constructor

ThreadGroup(String name) - Creating one thread group with given name

Methods

int activeCount()

Returns number of active threads in ThreadGroup.

void destroy()

Destroy the thread group.

Static int enumerate(Thread[] array)

Copies into the specified array every active thread in this thread group.

void list()

Prints information about this thread group to the standard output.

Page 191 of 660


Java Book - Chidambaram.S

Chapter 25 - BigDecimal, String and String


Buffer

BigDecimal is the Immutable, arbitrary-precision (handling bignum) signed


decimal numbers.

Consider following example to illustrate how BigDecimal works than Double. We


have more control in BigDecimal calculation and it comes with built in methods
to do the math operations such as add, subt, mult, divide.

In the below example using java.math.MathContext and java.math.RoundingMode we


add the control to resultant value's precision.

1. import java.math.BigDecimal;
2. import java.math.MathContext;
3. import java.math.RoundingMode;
4.
5. public class BigDecimalDemo {
6.
7. public static void main(String[] args) {
8. // TODO Auto-generated method stub
9. double d1=2.434534345345d;
10. double d2=5.23453434345345d;
11. System.out.println(d1*d2);
12.
13. BigDecimal b1=new BigDecimal(d1);
14. BigDecimal b2=new BigDecimal(d2);
15. /*
16. * 4 defines number of degits in results
17. * CEILING defines rounding mechanism
18. */
19. BigDecimal b3=b1.multiply(b2,new MathContext(4,RoundingMode.CEILING));

Page 192 of 660


Java Book - Chidambaram.S

20.
21. System.out.println(b3);
22. }
23.
24. }
25.
26. Output
27.
28. 12.743653641025363
29. 12.75

String and StringBuffer Handling

java.lang.String

It is the class to manage Strings. String is the collection alphanumeric


characters.

String comes with a literal within double quotes.

StringBuffer is also the class to manage strings.

Differences between String and StringBuffer

Difference 1

In String invoking object can’t be modified. String is immutable.

In StringBuffer invoking object will be affected. StringBuffer is mutable.

For example

String str=”Java”;

str.concat(“Prg”);

Now str is “Java”.

Page 193 of 660


Java Book - Chidambaram.S

It means the invoking object str is never modified.

In contrast,

StringBuffer sb=new StringBuffer(“Java”);

sb.insert(4,”Prg”);

now sb=”JavaPrg”

Because invoking object will be affected.

Difference 2

In string we can assign the value, it is not possible with StringBuffer.

Constructor

String()

It creates empty String object

String(byte[] a)

The byte array will be converted to String by using this constructor.

String(byte[] a,int start ,int length)

Works like above method, but we can also specify start of byte array and
length of byte array.

String(char[] char)

To convert char[], we can use this method.

String(char[] char,int offset,int length)

Works like above method, but we can also specify start of char array and
length of char array.

String(StringBuffer sb)

Page 194 of 660


Java Book - Chidambaram.S

It Converts the StringBuffer to String.

String(String str)

To create String object with given str

String Methods

char charAt(int index)(12)

Returns the char value at the specified index.

int indexOf(char ch)(28)

Returns the index of first occurrence of ch from invoking string.

int indexOf(String str)(28)

Returns the index of first occurrence of str from invoking string.

int indexOf(char ch,int start)

Returns the index of first occurrence of ch from invoking string. But searching
starts with given start.

int indexOf(String str ,int start)

Returns the index of first occurrence of str from invoking string. But searching
starts with given start.

int lastIndexOf(char ch)

Returns the index within this string of the last occurrence of the specified
character.

int lastIndexOf(char ch,int start)

Returns the index within this string of the last occurrence of the specified
character, searching backward starting at the specified start.

int lastIndexOf(String str,int start)

Page 195 of 660


Java Book - Chidambaram.S

Returns the index within this string of the last occurrence of the specified
character, searching backward starting at the specified start.

int length()

Returns the length of invoking string.

int compareTo(String str)

Compares two Strings

If invoking string is greater than other string

It returns +1

If invoking String is less than the other String

It returns -1

If invoking string and other string are equal, it returns 0.

String concat(String str)

Concatenates the specified string to the end of invoking string.

boolean equals(Object obj)

Compares invoking string with given obj with case sensitive checking.
Returns true if both are same other wise false.

boolean equalsIgnoreCase(String str)

Similar to above method without case.

String trim()

Returns a copy of the string, after removing the white spaces occurred left
and right side.

String replace(char original,char replace)

Page 196 of 660


Java Book - Chidambaram.S

Returns a new string resulting from replacing all occurrences of oldChar in


this string with newchar.

String substring(int startindex, int endindex)

Returns a new string from invoking string between startindex and endindex-1.

String substring(int startindex)

Returns a new string from start index to last from invoking string.

byte[] getBytes()

Encodes this String into a sequence of bytes storing the result into a new
byte array. We can use this method to convert string to byte[].

void getChars(int sourcestart,int sourceend,char target[],int targetstart)

Copies characters from this string into the target character array.

sourcestart : starting place of invoking object

sourceend : ending place of invoking object

target[] : Target char[] to store data from invoking

object.

targetstart : target char array starting place.

boolean regionMatches(boolean ignorecase,int str1startindex, String str2,


int str2startindex,int length)

To check the portions of two strings we can use this method. If ignorecase
is true, this method will not see case, other wise it checks case also.

boolean regionMatches(int str1startindex, String str2, int str2startindex,int


length)

Same as above except first argument.

char[] toCharArray()

Page 197 of 660


Java Book - Chidambaram.S

Converts this string to a new character array.

String toLowerCase()

Converts all of the characters in this String to lower case

String toUpperCase()

Converts all of the characters in this String to upper case

static String valueOf(boolean b)

static String valueOf(int a)

static String valueOf(float f)

static String valueOf(char[] ch)

static String valueOf(char[] ch,int startindex,int length)

static String valueOf(Object ob)

All above valueOf() can be used to convert given data type to string.

String toString()

It is very important method overridden from Object class, to covert any type to
String.

boolean startsWith(string str)

Tests if invoking string starts with given str.

boolean startsWith(string str, int startindex)

Works like above method but checking will be started from given start
index.

boolean endsWith(String str)

Tests if invoking string ends with given str.

Page 198 of 660


Java Book - Chidambaram.S

StringBuffer

Constructors

SringBuffer()

Creates StringBuffer object with default capacity 16 and length 0.

SringBuffer(int capacity)

Creates StringBuffer object with given capacity and length 0.

StringBuffer(String str)

Creates StringBuffer with given str.

What is capacity and length of StringBuffer?

Consider following example

StringBuffer sb=new StringBuffer(“Java”);

It means sb=”Java”. The length of sb is 4. But the capacity sb is 20(Default


capacity+4). Because JRE reserves 16 bytes for StringBuffer.

Methods

int capacity()

Returns the current capacity.

int length()

Returns the current length (character count).

StringBuffer delete(int startindex,int endindex)

Removes the characters between startindex and endindex-1 from invoking


object.

StringBuffer deleteCharAt(int index)

Page 199 of 660


Java Book - Chidambaram.S

Removes the char at the specified position

StringBuffer replace(int start ,int end ,String str)

Replaces the characters in a substring of this sequence with characters in


the specified String.

StringBuffer append(boolean b)

Appends given boolean with invoking StringBuffer. Instead of b you can also
give int,object,float,long,char[],double,String

StringBuffer reverse()

To reverse the invoking object.

void setCharAt(int index, char ch)

The character at the specified index is set to ch

void setLength(int newlen)

Sets the length of the character sequence.

If newlen is greater with current length, null values are added, otherwise you
will loss data.

void ensureCapacity(int maxcapacity)

Ensures that the capacity is at least equal to the specified minimum.

It performs following three ways

If given capacity is greater than (currentcapapcity*2)+2, given capacity becomes


new capacity,

If given capacity is lesser than (currentcapapcity*2)+2, (currentcapapcity*2)+2


becomes new capacity.

If given capacity is lesser than current capacity, no action takes place.

Example 1

Page 200 of 660


Java Book - Chidambaram.S

StringBuffer sb=new StringBuffer(“java prg”);

System.out.println(sb.capacity());//24(16+8)

Sb.ensureCapacity(60);

System.out.println(sb.capacity())//60

Example 2

StringBuffer sb=new StringBuffer(“java prg”);

System.out.println(sb.capacity());//24(16+8)

sb.ensureCapacity(40);

System.out.println(sb.capacity())//50

Example 3

StringBuffer sb=new StringBuffer(“java prg”);

System.out.println(sb.capacity());//24(16+8)

Sb.ensureCapacity(22);

System.out.println(sb.capacity())//24

StringBuffer insert(int startindex ,xxx value)

Inserts value at given start index.

void trimTosize()

To trim extra bytes allocated for the invoking object. It means current length
becomes new capacity.

Page 201 of 660


Java Book - Chidambaram.S

Chapter 26 - Java Database Programming

In this chapter we will see about database programming using java.sql and
javax.sql.

Database concepts
Table

Table is a collection of records and Fields or collection of rows and columns.

Each row is a record

Each column is a Field

Database

Database is a collection of tables and other related files such as reports, views….

DBMS

Data Base Management System

It is a s/w to manage Database without relationship facility. DBMS : DBase

RDBMS

Like DBMS with relationship facility. Relationship means master table and child table
relationship.

(Oracle, SQL Server)

Entity

Entity is an object which can provide or consume data.

Normalization

Normalization is the process to divide the tables from the collection of entity data.
Entity data is the collection of fields about entity.

Page 202 of 660


Java Book - Chidambaram.S

When dividing entity data, we must take care about master tables, child tables,
primary key, unique key and foreign key concepts.

Primary key

Duplicate and null not allowed

Unique key

Duplicate not allowed null allowed

Front End

It is the s/w to visualize the screens to get the inputs and show the outputs and also
having the ability to connect other systems to get and retrieve the data and It can't
store the data itself.

Ex: VB, Java,.Net

Back End

It is the s/w to store and retrieve data.

Ex: Foxpro, Access, Oracle, SQL server.

Driver or Provider

It acts as interface between frontend and backend.

It sends request to back end sent by front end and receives the response from back
end and submits to front end.

SQL
DDL – Data Definition Language

Create, Alter, Truncate, drop

DML – Data Manipulation Language

Insert, Delete, Update, Select

DCL – Data Control Language

Page 203 of 660


Java Book - Chidambaram.S

grant,revoke

TCL – Transaction Control Language

Commit, rollback, savepoint

Let's start with java.sql and its classes and interfaces.

ResultSet

It is resultant records of your query and it is the buffer memory of frontend


s/w to reflect backend table.

Statements

Statement

PreparedStatement

CallableStatement

Four types of JDBC Drivers

JDBC-ODBC Bridge Driver (Type-1)

Native-API Driver (Type-2)

Net-Protocol Pure Java Driver (Type-3)

Native-Protocol Pure Java Driver (Type-4)

1. JDBC-ODBC Bridge Driver (Type-1):

This driver comes with JDK itself in sun.jdbc.odbc package. This type of driver
is purely implemented in ‘C’ language and this is platform dependent in nature.

Page 204 of 660


Java Book - Chidambaram.S

So Java creators create JDBC – Odbc Driver to avoid programmer can connect
directly ODBC driver.

This driver is removed since java 1.8

Example to load the driver and create the connection using Type 1 driver

Database connection without password like access database

1. // specifies the driver name as the type1.


2. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
3. // Specifies the DSN name as mydsn and jdbc is the protocol and odbc is the subp
rotocol.
4. Connection con=DriverManager.getConnection("jdbc:odbc:mydsn");

Database connection with password like oracle database

1. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
2. /* Specifies the DSN name as mydsn and jdbc is the protocol and odbc is the subp
rotocol. scott is the
3. * username and tiger is the password for oracle database
4. */
5. Connection con=DriverManager.getConnection("jdbc:odbc:mydsnorc","scott","tiger")
;

Advantages of Type 1 Driver

No need to install Type-1 driver separately, since it comes as part of the JDK.

ODBC driver is available in windows environment by default.

Drawbacks of Type-1 Driver

The Type-1 driver is very slow, because of JDBC-ODBC transactions.

The Type-1 driver is the dependent driver since its depending on ODBC support.

The Type-1 driver is not suitable for real-time applications.

Page 205 of 660


Java Book - Chidambaram.S

2. Native-API Driver (Type-2)

Type -2 driver uses native API supplied by a database vendor to connect with a
database. Type 2 driver converts the JDBC calls into native calls, to connect
with the database.

Oracle OCI driver is the example for Type 2

we need to add the ojdbc.jar in our classpath to use OCI driver

Advantages Of Type -2 Driver

Type – 2 driver is comparatively faster than the Type -1 driver.

Drawbacks Of Type-2 Driver

The Type-2 driver is both platform and database dependent. Hence it is not
suitable for real-time applications.

This driver is slower than the Type-3 and Type-4 drivers.

3. Net-Protocol Pure Java Driver (Type-3)

Net Protocol is a Type-3 JDBC driver. It was written in Java programming. This
network protocol driver uses the middle software like an application server.
The JDBC clients use the standard network sockets to communicate with the
middleware application server.

The middleware application server internally converts the JDBC calls to the
vendor’s specific database protocol.

Advantages of Type-3 Driver

While using the Type – 3 Driver, it is not required to maintain libraries at


the client side, since the application server itself can perform the tasks.

Drawbacks of Type - 3 Driver

Page 206 of 660


Java Book - Chidambaram.S

Since it is a network driver, the middle ware layer may reduce the performance.

Database specific coding is required for middle layer application. Hence it


requires more maintenance.

4. Native-Protocol Pure Java Driver (Type-4)

Type-4 drivers are supplied by Oracle Corporation by developing into Java


language. OracleDriver is the name of Type-4 driver which is released by Oracle
Corporation in the form of classes111.jar. In order to work with the Type-4
driver, we need to add the classes111.jar to our classpath.

The Type-4 driver uses native protocol accepted by the database server to
establish a connection between a java program and database.

It is a pure Java driver because it completely implemented by the Java


programming language

Example to get the connection

Connection con=DriverManager.getConnection (“jdbc : oracle : thin :@ localhost


: 1521 : chandrashekhar”, “scott”, “tiger”);

On the above connection syntax, “THIN” is a driver name. The thin driver
converts the JDBC calls to the vendor’s specific database calls.

Advantages of Type -4 Driver

It is the fastest driver among all types of drivers.

It is a platform independent driver.

This Type-4 driver is suitable for developing real-time applications.

Drawbacks of Type-4 Driver

The only drawback of Type-4 driver is, it is database dependent.

Page 207 of 660


Java Book - Chidambaram.S

DSN Creation(Data Source Name)

Access

Start -> Settings -> Control Panel -> Administrative Tools -> Data Sources -> ADD ->
Select Microsoft Access Driver -> Finish -> Type DSN Name in Data Source Name text box
-> Click Select Button -> Select Path of mdb file name -> OK

Oracle

Start -> Settings -> Control Panel -> Administrative Tools -> Data Sources -> ADD ->
Select Microsoft ODBC for Oracle -> Finish -> Type DSN Name in Data Source Name text
box -> OK

What is Procedure

Procedure is the collection of SQL statements.

By running procedure, you can execute collection of sql statements in stored


procedure one by one.

Procedure can accept more parameters and it can return more than one values to
caller.

Procedure parameters can be available as in parameter and out parameter.

OUT parameters are the returned parameters IN parameters are the argument
parameters.

Steps to Create Procedure

Open SQL * Plus

SQL>ed Pro1.sql

Now you can get one notepad to type the program.

Page 208 of 660


Java Book - Chidambaram.S

Type program as per CH4/2 Pro1.sql

Save the file and exit from file.

Now you will come back to SQL>

SQL>@ pro1.sql (Compile)

If any errors, you will get following message

Procedure Created With Compilation Errors.

In this time you can list the error by providing following command

SQL> show errors

Above command list the errors and you must correct the errors

Methods of Statement(I)

boolean execute(String query)

It executes all types of query. If result is true, query is select query and
you can get ResultSet object by using below method.

ResultSet getResultSet()

To get the resultset, which has resultant records of executed select query

ResultSet executeQuery(String query)

Select query will be executed using this method and returns the resultant
records as a ResultSet object.

int executeUpdate(String query)

Query should be other than select query. Returns no of records are affected.

Page 209 of 660


Java Book - Chidambaram.S

int getMaxRows()

Returns no of rows in ResultSet.

Three statements in java.sql

Statement

PreparedStatement

CallableStatement

Difference between Statement and PreparedStatement

Statement hands over the query before the compilation to back end. So the query
should be completed with necessary values.

PreparedStatement compiles the query first and hands over the query to back
end.

For Example

stmt.executeQuery(“select * from emp where dob=#12-JAN-2007#”) –Access

stmt.executeQuery(“select * from emp where dob=’12-JAN-2007’”) –Oracle

3) In PreparedStatement the above query can be given as follows

select * from emp where dob=? Both for access and oracle.

In (2) and (3) points we conclude that usage prepared statement is easier and
when we need to pass sql query as the same as we received we can use Statement.

4) The query given by PreparedStatement will be compiled by java then it will


be backend.

In (1) and (4) we conclude that Statement query will not be compiled by java
PreparedStatement query will be compiled by java.

Page 210 of 660


Java Book - Chidambaram.S

Scrollable PreparedStatement

PreparedStatement ps=con.prepareStatement(“
Query”,ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);

ResultSet rs=ps.executeQuery();

Non Scrollable PreparedStatement

PreparedStatement ps=con.prepareStatement(“ Query”);

ResultSet rs=ps.executeQuery();

Scrollable Statement (createStatement() with argument)

Statement
s=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABL
E);

ResultSet rs=s.executeQuery(“Select * from marklist”);

Non scrollable Statement (createStatement() without argument)

Statement s=con.createStatement();

ResultSet rs=s.executeQuery(“Select * from marklist”);

ResultSet Cursor Types

TYPE_SCROLL_INSENSITIVE: The cursor can scroll forward and backward and the
database changes will not be reflected in result set and the resultset contains
the records at the time of opening.

TYPE_SCROLL_SENSITIVE: The cursor can scroll forward and backward, and the Result
set reflects the changes made to the underlying data source while the result
set remains open.

Page 211 of 660


Java Book - Chidambaram.S

TYPE_FORWARD_ONLY: The result set cannot be scrolled; its cursor moves forward
only,

The default ResultSet type is TYPE_FORWARD_ONLY.

Note:

Not all databases and JDBC drivers support all ResultSet types. The method
DatabaseMetaData.supportsResultSetType returns true if the specified ResultSet
type is supported and false otherwise.

ResultSet Concurrency

The concurrency of a ResultSet object determines what level of update


functionality is supported when multiple access happens in database.

There are two concurrency levels:

CONCUR_READ_ONLY: The ResultSet object cannot be updated using


the ResultSet interface.

CONCUR_UPDATABLE: The ResultSet object can be updated using


the ResultSet interface.

The default ResultSet concurrency is CONCUR_READ_ONLY.

Note: Not all JDBC drivers and databases support concurrency. The method
DatabaseMetaData.supportsResultSetConcurrency returns true if the specified
concurrency level is supported by the driver and false otherwise

ResultSet Methods(I)

boolean absolute(int row)

Moves record pointer in ResultSet from beginning.

int getRow()

Returns pointer position

Page 212 of 660


Java Book - Chidambaram.S

void afterLast()

Moves the pointer to EOF

void beforeFirst()

Moves the cursor to BOF

boolean isBeforeFirst()

If ResultSet pointer is in BOF it returns true.

boolean isAfterLast()

If result set pointer is in EOF it returns true.

boolean isFirst()

If result set pointer is in First Record it returns true.

boolean isLast()

If result set pointer is in Last Record it returns true.

boolean next()

Moves pointer to next record, if successfully moved it returns true.

boolean previous()

Moves pointer to previous record and returns true, if successfully moved.

void cancelRowUpdates()

Cancel the updation in current row.

void close()

Page 213 of 660


Java Book - Chidambaram.S

To close the ResultSet Object.

void deleteRow()

Deletes current record.

int findColumn(String column)

Returns column no

Blob getBlob(int i)

Blob getBlob(String str)

Returns Blob object(Binary Large Object)

xxx getXxx(int index) or (String columnname)

Returns the value of given column name of current record.

void insertRow()

to create blank row of ResultSet

boolean last()

Move to last record and returns true.

boolean relative(int rows)

Moves the record set pointer from pointer’s current position.

void updateXxx(int col,String value)

To update the value in col.

void updateRow()

Page 214 of 660


Java Book - Chidambaram.S

Below program creates the table using dsnname in access data base.
In above notes, refer to create the DSN.

1. import java.sql.*;
2. class CreateTable
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
9. //mydsn is the dsnname
10. Connection con=DriverManager.getConnection("jdbc:odbc:mydsn");
11. PreparedStatement ps=con.prepareStatement("create table customer(cusname t
ext(30),company text(30),pur_amt number,bal_amt number)");
12. ps.executeUpdate();
13. System.out.pirntln(“Table has been created”);
14. ps.close();
15. con.close();
16. }
17. catch(Exception e)
18. {
19. e.printStackTrace();
20. }
21. }
22. }
23. Output
24. Table has been created

Create table using by user input in oracle


Page 215 of 660
Java Book - Chidambaram.S

1. import java.sql.*;
2. import java.io.*;
3. class CreateTableFromUser
4. {
5. public static void main(String args[])
6. {
7. DataInputStream dis=new DataInputStream(System.in);
8. String tablename;
9. String str;
10. String cn,type,size;
11. try
12. {
13. int x,more=0,choice=0;
14. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
15. //mydsnorc is the dsnname and scott is the username,tiger is the password
of oracle database
16. Connection con=DriverManager.getConnection("jdbc:odbc:mydsnorc","scott","t
iger");
17. System.out.println("Enter Table Name");
18. tablename=dis.readLine();
19. str="create table "+tablename+"(";
20. do
21. {
22. System.out.println("Enter the Column Name");
23. cn=dis.readLine();
24. System.out.println("Enter the Data Type ");
25. type=dis.readLine();
26. System.out.println("Enter the Size ");
27. size=dis.readLine();
28. System.out.println("Add More Yes - 1 No -0");
29. if (more==1)
30. str=str+","+cn+ " "+type+"("+size+")";
31. else
32. System.out.println("1");
33. str=str+cn+ " "+type+"("+size+")";

Page 216 of 660


Java Book - Chidambaram.S

34. choice=Integer.parseInt(dis.readLine());
35. }while(choice==1);
36. str=str+")";
37. System.out.println(str);
38. PreparedStatement ps=con.prepareStatement(str,ResultSet.TYPE_SCROLL_SENSIT
IVE,ResultSet.CONCUR_UPDATABLE);
39. ps.executeUpdate();
40. }
41. catch(Exception e)
42. {
43. System.out.println(e);
44. }
45. }
46. }
47. Output
48.
49. Table has been created in oracle

Select the records from deptmaster using PreparedStatement and


ResultSet

1. import java.sql.*;
2. class Select
3. {
4. public static void main(String args[])
5. {
6. try{
7. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
8. Connection con=DriverManager.getConnection("jdbc:odbc:mydsn");
9. PreparedStatement ps=con.prepareStatement("select * from deptmaster");
10. ResultSet rs=ps.executeQuery();
11. System.out.println("Dno"+"\t\t\t"+"DName"+"\t\t "+"Head");
12. while(rs.next())
13. {

Page 217 of 660


Java Book - Chidambaram.S

14. System.out.println(rs.getString(1)+"\t\t"+rs.getString(2)+"\t\t"+rs.getStr
ing(3));
15. }
16. ps.close();
17. con.close();
18. }
19. catch(Exception e)
20. {
21. e.printStackTrace();
22. }
23. }
24. }
25.
26. Output
27.
28. Dno DName Head
29. d0001 production ramprasath
30. d0002 purchase sivaramKumar
31. d0003 marketing sathish
32. d0004 accounts ram prasath

Insert into deptmaster, using executeUpdate() method of


PreparedStatement

1. import java.sql.*;
2. class Insert
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
9. Connection con=DriverManager.getConnection("jdbc:odbc:mydsn");

Page 218 of 660


Java Book - Chidambaram.S

10. PreparedStatement ps=con.prepareStatement("insert into deptmaster values(?


,?,?)");
11. ps.setString(1,"d0005");
12. ps.setString(2,"Salary");
13. ps.setString(3,"shiva");
14. ps.executeUpdate();
15. ps=con.prepareStatement("insert into deptmaster values(?,?,?)");
16. ps.setString(1,"d0006");
17. ps.setString(2,"fund");
18. ps.setString(3,"shivaKumar");
19. ps.executeUpdate();
20. System.out.println("value Inserted");
21. ps.close();
22. con.close();
23. }
24. catch(Exception e)
25. {
26. e.printStackTrace();
27. }
28. }
29. }
30.
31. Output
32.
33. value Inserted

Insert into deptmaster, using executeUpdate() method of


PreparedStatement for selected columns

1. import java.sql.*;
2. class HowValuesInsertedForSelectedColumn
3. {
4. public static void main(String args[])

Page 219 of 660


Java Book - Chidambaram.S

5. {
6. try
7. {
8. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
9. Connection con=DriverManager.getConnection("jdbc:odbc:mydsn");
10. PreparedStatement ps=con.prepareStatement("insert into marklist(sno,name)
values(?,?)");
11. ps.setInt(1,102);
12. ps.setString(2,"Shiva");
13. System.out.println(ps.executeUpdate());
14. }
15. catch(Exception e)
16. {
17. System.out.println(e);
18. }
19. }
20. }
21.
22. Output
23.
24. 1 //number of affected row

Below program illustrates the updation

1. import java.sql.*;
2. class Update
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
9. Connection con=DriverManager.getConnection("jdbc:odbc:mydsn");

Page 220 of 660


Java Book - Chidambaram.S

10. PreparedStatement ps=con.prepareStatement("select * from deptmaster where


dno=?");
11. ps.setString(1,"d0006");
12. ResultSet rs=ps.executeQuery();System.out.println("Before Update");
13. while(rs.next())
14. {
15. System.out.println(rs.getString(1)+"\t\t"+rs.getString(2)+"\t\t"+rs.getStr
ing(3));
16. }
17. ps=con.prepareStatement("update deptmaster set head=? where dno=?");
18. ps.setString(1,"sivakumar");
19. ps.setString(2,"d0006");
20. ps.executeUpdate();
21. ps=con.prepareStatement("select * from deptmaster where dno=?");
22. ps.setString(1,"d0006");
23. rs=ps.executeQuery();
24. System.out.println("After Update");
25. while(rs.next())
26. {
27. System.out.println(rs.getString(1)+"\t\t"+rs.getString(2)+"\t\t"+rs.getStr
ing(3));
28. }
29. ps.close();
30. con.close();
31. }
32. catch(Exception e)
33. {
34. System.out.println(e);
35. }
36. }
37. }
38.
39. Output
40. d0006 Fund shivaKumar
41. After Update

Page 221 of 660


Java Book - Chidambaram.S

42. d0006 Fund sivakumar

Below program illustrates the deletion

1. import java.sql.*;
2. class Delete
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
9. Connection con=DriverManager.getConnection("jdbc:odbc:mydsn");
10. PreparedStatement ps=con.prepareStatement("delete from deptmaster where dn
o=?");
11. ps.setString(1,"d0005");
12. ps.executeUpdate();
13. ps=con.prepareStatement("delete from deptmaster where dno=?");
14. ps.setString(1,"d0006");
15. ps.executeUpdate();
16. ps=con.prepareStatement("select * from deptmaster");
17. ResultSet rs=ps.executeQuery();
18. while(rs.next())
19. {
20. System.out.println(rs.getString(1)+"\t"+rs.getString(2)+"\t"+rs.getString(
3));
21. }
22. ps.close();
23. con.close();
24. }
25. catch(Exception e)
26. {
27. e.printStackTrace();
28. }

Page 222 of 660


Java Book - Chidambaram.S

29. }
30. }
31.
32. Output
33. d0001 production ramprasath
34. d0002 purchase sivaramkumar
35. d0003 marketing sathish
36. d0004 accounts ramprasath

Below program illustrates to drop the table

1. import java.sql.*;
2. class DropTable
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
9. Connection con=DriverManager.getConnection("jdbc:odbc:mydsn");
10. PreparedStatement ps=con.prepareStatement("drop table customer");
11. ps.executeUpdate();
12. System.out.println("Table has been Droped");
13. ps.close();
14. con.close();
15. }
16. catch(Exception e)
17. {
18. System.out.println(e);
19. }
20. }
21. }
22.
23. Output

Page 223 of 660


Java Book - Chidambaram.S

24. Table has been Dropped

Below program illustrates how the execute() Statement works and


obtain the ResultSet after the execute() completed successfully

1. import java.sql.*;
2. class StatementMethods
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. ResultSet resultset=null;
9. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
10. Connection con=DriverManager.getConnection("jdbc:odbc:mydsn");
11. Statement st=con.createStatement();
12. boolean flag=st.execute("select * from deptmaster");
13. if (flag==true)
14. {
15. resultset=st.getResultSet();
16. System.out.println(resultset.getType());
17. }//if
18. resultset.first();
19. }//try
20. catch(Exception e)
21. {
22. System.out.println(e);
23. }
24. }//main
25. }//class
26.
27. Output
28. 1003

Page 224 of 660


Java Book - Chidambaram.S

29. Result set type is TYPE_FORWARD_ONLY

Below program illustrates getString(int) method of ResultSet. Here


int argument reperesents the column index. Column index starts from
1.

1. import java.sql.*;
2. class SelectDemo
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
9. Connection con=DriverManager.getConnection("jdbc:odbc:mydsn");
10.
11. Statement st=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet
.CONCUR_UPDATABLE);
12. ResultSet rs=st.executeQuery("select * from empmaster where dob=#23-OCT-
1973#");
13. while (rs.next())
14. {
15. System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(
3)+" "+rs.getDate(4)+" "+rs.getDate(5)+" "+rs.getString(6)+" "+rs.getInt(7)
+" "+rs.getString(8)+" "+rs.getString(9));
16. }
17. }
18. catch(Exception e)
19. {
20. System.out.println(e);
21. }
22. }
23. }

Page 225 of 660


Java Book - Chidambaram.S

24.
25. Output
26. e0005 priya f 1973-10-23 1998-01-12 n 0 dindigul d0004

Below program illustrates getString(String) method of ResultSet.


Here String argument reperesents the column name.

1. import java.sql.*;
2. class SelectDemoUsingPreparedStatement
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
9. Connection con=DriverManager.getConnection("jdbc:odbc:mydsn");
10. PreparedStatement ps=con.prepareStatement("select * from empmaster where d
no in(?,?,?)");
11. ps.setString(1,"d0001");
12. ps.setString(2,"d0002");
13. ps.setString(3,"d0004");
14. ResultSet rs=ps.executeQuery();
15. while (rs.next())
16. {
17. System.out.println(rs.getString("ename"));
18. }
19. }
20. catch(Exception e)
21. {
22. System.out.println(e);
23. }
24. }

Page 226 of 660


Java Book - Chidambaram.S

25. }
26.
27. Output
28. surya narayanan
29. dorio solamon
30. sai ram
31. priya
32. ashok kumar
33. vidhya

Below program illustrates absolute(int) method of ResultSet. Here


int argument reperesents the row number to be moved. absolute(3)
means ResultSet cursor moves to 3rd record and calculates from 1st
record.

1. import java.sql.*;
2. class AbsoluteDemo
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
9. Connection con=DriverManager.getConnection("jdbc:odbc:mydsn");
10. PreparedStatement ps=con.prepareStatement("select * from empmaster",Result
Set.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
11. ResultSet rs=ps.executeQuery();
12. rs.absolute(4); //calculates from first record
13. System.out.println("rs.getRow()="+rs.getRow());
14. rs.absolute(-1); // To Go to last record
15. System.out.println("rs.getRow()="+rs.getRow());
16. rs.last();
17. System.out.println("rs.getRow()="+rs.getRow());

Page 227 of 660


Java Book - Chidambaram.S

18. rs.absolute(4);
19. System.out.println("rs.getRow()="+rs.getRow());
20. rs.absolute(-5); // calculates from last record
21. System.out.println("rs.getRow()="+rs.getRow());
22.
23. }
24. catch(Exception e)
25. {
26. System.out.println(e);
27. }
28. }
29. }
30.
31. Output
32. rs.getRow()=4
33. rs.getRow()=10
34. rs.getRow()=10
35. rs.getRow()=4
36. rs.getRow()=6

Below program illustrates getXXX(int) and updateXXX(int) method of


ResultSet. Here int argument reperesents the column number starts
from 1.

Below program illustrates setAutoCommit(boolean) of Connection. In


this program setAutoCommit(false) is called to rollback the
deletion. So the deletion of record won't affect.

1. import java.sql.*;
2. class DataType
3. {
4. public static void main(String args[])

Page 228 of 660


Java Book - Chidambaram.S

5. {
6. try
7. {
8. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
9. Connection con=DriverManager.getConnection("jdbc:odbc:javadsn");
10. Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,Resul
tSet.CONCUR_UPDATABLE);
11. ResultSet rs=stmt.executeQuery("select * from datatype");
12. rs.first();
13. System.out.println("rs.getString(1)="+rs.getString(1));
14. System.out.println("rs.getInt(2)="+rs.getInt(2));
15. System.out.println("rs.getLong(3)="+rs.getLong(3));
16. System.out.println("rs.getByte(4)="+rs.getByte(4));
17. System.out.println("rs.getFloat(5)="+rs.getFloat(5));
18. System.out.println("rs.getDouble(6)="+rs.getDouble(6));
19. System.out.println("rs.getDate(7)="+rs.getDate(7));
20. System.out.println("rs.getTime(8)="+rs.getTime(8));
21. rs.updateString(1,"Text111");
22. rs.updateInt(2,2);
23. rs.updateLong(3,30);
24. rs.updateByte(4,(byte)100);
25. rs.updateFloat(5,100.1f);
26. rs.updateDouble(6,100.123);
27. rs.updateDate(7,new Date(System.currentTimeMillis()));
28. rs.updateTime(8,new Time(System.currentTimeMillis()));
29. rs.updateRow();
30. System.out.println("rs.getString(1)="+rs.getString(1));
31. System.out.println("rs.getInt(2)="+rs.getInt(2));
32. System.out.println("rs.getLong(3)="+rs.getLong(3));
33. System.out.println("rs.getByte(4)="+rs.getByte(4));
34. System.out.println("rs.getFloat(5)="+rs.getFloat(5));
35. System.out.println("rs.getDouble(6)="+rs.getDouble(6));
36. System.out.println("rs.getDate(7)="+rs.getDate(7));
37. System.out.println("rs.getTime(8)="+rs.getTime(8));
38. rs.moveToInsertRow();

Page 229 of 660


Java Book - Chidambaram.S

39. rs.updateString(1,"Text111");
40. rs.updateInt(2,2);
41. rs.updateLong(3,30);
42. rs.updateByte(4,(byte)100);
43. rs.updateFloat(5,100.1f);
44. rs.updateDouble(6,100.123);
45. rs.updateDate(7,new Date(System.currentTimeMillis()));
46. rs.updateTime(8,new Time(System.currentTimeMillis()));
47. rs.insertRow();
48. }
49. catch(Exception e)
50. {
51. e.printStackTrace();
52. }
53. }
54. }
55. Output
56. rs.getString(1)=Text111
57. rs.getInt(2)=2
58. rs.getLong(3)=30
59. rs.getByte(4)=100
60. rs.getFloat(5)=100.1
61. rs.getDouble(6)=100.123
62. rs.getDate(7)=2006-10-08
63. rs.getTime(8)=16:48:29
64. rs.getString(1)=Text111
65. rs.getInt(2)=2
66. rs.getLong(3)=30
67. rs.getByte(4)=100
68. rs.getFloat(5)=100.1
69. rs.getDouble(6)=100.123
70. rs.getDate(7)=2006-10-14
71. rs.getTime(8)=19:20:49

Instead roleback, we can call commit() to commit the transaction.

Page 230 of 660


Java Book - Chidambaram.S

1. import java.sql.*;
2. class DeleteRowDemo
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
9. Connection con=DriverManager.getConnection("jdbc:odbc:mydsn");
10. con.setAutoCommit(false);
11. PreparedStatement ps=con.prepareStatement("select * from empmastercopy",Re
sultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
12. ResultSet rs=ps.executeQuery();
13. rs.absolute(2)
14. rs.deleteRow();
15. con.rollback();
16. }
17. catch(Exception e)
18. {
19. e.printStackTrace();
20. }
21. }
22. }

Below program illustrates relative(int) of ResultSet, which moves


the cursor ResultSet to the specified position from the current
position. Postive number moves forward and negative number moves
backward direction

Relative is only works if the cursor is in except bof or eof

Page 231 of 660


Java Book - Chidambaram.S

1. import java.sql.*;
2. class RelativeDemo
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
9. Connection con=DriverManager.getConnection("jdbc:odbc:mydsn");
10. PreparedStatement ps=con.prepareStatement("select * from empmaster",Result
Set.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
11. ResultSet rs=ps.executeQuery();
12. rs.first();
13. rs.relative(5);
14. System.out.println("Get Row="+rs.getRow());
15. rs.relative(1);
16. System.out.println("Get Row="+rs.getRow());
17. rs.relative(10);
18. System.out.println(rs.isAfterLast());
19. System.out.println("Get Row="+rs.getRow());
20. rs.first();
21. System.out.println("Get Row="+rs.getRow());
22. rs.relative(10);
23. System.out.println("Get Row="+rs.getRow());
24. rs.relative(-2);
25. }
26. catch(Exception e){
27. e.printStackTrace();
28. }
29. }//main
30. }//class

Page 232 of 660


Java Book - Chidambaram.S

Below two programs illustrate ResutlSetMetaData. Its methods are


useful to know about ResultSet. Below methods are used in below
program.

1. String getColumnName(int column)


2. int getColumnType(int column)
3. String getColumnTypeName(int column)
4. int getPrecision(int column)
5. int getScale(int column)
6.
7. import java.sql.*;
8. import java.io.*;
9. class GetColumnList
10. {
11. public static void main(String args[])
12. {
13. DataInputStream dis=new DataInputStream(System.in);
14. String tablename;
15. String str;
16. String cn,type,size;
17. try
18. {
19. int x,choice=0;
20. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
21. Connection con=DriverManager.getConnection("jdbc:odbc:mydsn");
22. System.out.println("Enter Table Name");
23. tablename=dis.readLine();
24. PreparedStatement ps=con.prepareStatement("select * from "+tablename,Resul
tSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
25. ResultSet rs=ps.executeQuery();
26. ResultSetMetaData md=rs.getMetaData();
27. int cc;
28. cc=md.getColumnCount();
29. for (int i=1;i<=cc;i++)

Page 233 of 660


Java Book - Chidambaram.S

30. System.out.println(md.getColumnName(i) +" "+md.getColumnTypeNam


e(i)+" "+md.getPrecision(i)+" "+md.getScale(i));
31. for (int i=1;i<=cc;i++)
32. System.out.println(md.getColumnName(i) +" "+md.getColumnTypeNam
e(i)+" "+md.getColumnType(i));
33. }
34. catch(Exception e)
35. {
36. System.out.println(e);
37. }
38. }
39. }
40. Output
41. Enter Table Name
42. deptmaster
43.
44. dno VARCHAR 5 0
45. dname VARCHAR 15 0
46. head VARCHAR 15 0
47. dno VARCHAR 12
48. dname VARCHAR 12
49. head VARCHAR 12

1. import java.sql.*;
2. import java.io.*;
3. class All
4. {
5. public static void main(String args[])
6. {
7. try
8. {
9. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
10. Connection con=DriverManager.getConnection("jdbc:odbc:mydsn");

Page 234 of 660


Java Book - Chidambaram.S

11. PreparedStatement ps=con.prepareStatement("select * from emppay",ResultSet


.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
12. ResultSet rs=ps.executeQuery();
13. ResultSetMetaData md=rs.getMetaData();
14. System.out.println(md.columnNoNulls);
15. System.out.println(md.columnNullable);
16. System.out.println(md.columnNullableUnknown);
17. System.out.println("getColumnClassName(2)="+md.getColumnClassName(2));
18. System.out.println("getColumnCount()="+md.getColumnCount());
19. System.out.println("getColumnDisplaySize(6)="+md.getColumnDisplaySize(6));

20. System.out.println("getColumnLabel(1)="+md.getColumnLabel(1));
21. System.out.println("getColumnName(1)="+md.getColumnName(1));
22. System.out.println("getColumnType(1)="+md.getColumnType(1));
23. System.out.println("getColumnType(5)="+md.getColumnType(5));
24. System.out.println("getColumnType(3)="+md.getColumnType(3));
25. System.out.println("getColumnTypeName(1)="+md.getColumnTypeName(1));
26. System.out.println("getColumnTypeName(3)="+md.getColumnTypeName(3));
27. System.out.println("getPrecision(7)="+md.getPrecision(7));
28. System.out.println("getScale(7)="+md.getScale(7));
29. System.out.println("isAutoIncrement(7)="+md.isAutoIncrement(7));
30. System.out.println("isCaseSensitive(2)="+md.isCaseSensitive(2));
31. System.out.println("isNullable(1)="+md.isNullable(1));
32. System.out.println("isNullable(5)="+md.isNullable(5));
33. }
34. catch(Exception e)
35. {
36. e.printStackTrace();
37. }
38. }
39. }
40.
41. Output
42. 0
43. 1

Page 235 of 660


Java Book - Chidambaram.S

44. 2
45. getColumnClassName(2)=java.lang.String
46. getColumnCount()=8
47. getColumnDisplaySize(6)=50
48. getColumnLabel(1)=ccode
49. getColumnName(1)=ccode
50. getColumnType(1)=12
51. getColumnType(5)=-6
52. getColumnType(3)=5
53. getColumnTypeName(1)=VARCHAR
54. getColumnTypeName(3)=SMALLINT
55. getPrecision(7)=50
56. getScale(7)=0
57. isAutoIncrement(7)=false
58. isCaseSensitive(2)=false
59. isNullable(1)=1
60. isNullable(5)=1

Below program illustrates about DatabaseMetaData

1. import java.sql.*;
2. import java.io.*;
3. class Methods
4. {
5. public static void main(String args[])
6. {
7. try
8. {
9. int x,choice=0;
10. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
11. Connection con=DriverManager.getConnection("jdbc:odbc:mydsn");
12. DatabaseMetaData meta=con.getMetaData();
13. System.out.println("User Name="+meta.getUserName());
14. System.out.println("Url="+meta.getURL());
15. con=DriverManager.getConnection("jdbc:odbc:mydsnorc","scott","tiger");

Page 236 of 660


Java Book - Chidambaram.S

16. meta=con.getMetaData();
17. System.out.println("User Name="+meta.getUserName());
18. System.out.println("Url="+meta.getURL());
19. }
20. catch(Exception e)
21. {
22. e.printStackTrace();
23. }
24. }
25. }

Below program illustrates how stored procedure is executed using


CallableStatement

1. import java.sql.*;
2. import java.io.*;
3. class CallableStatementDemo2
4. {
5. public static void main(String args[])
6. {
7. try
8. {
9. DataInputStream dis=new DataInputStream(System.in);
10. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
11. Connection con=DriverManager.getConnection("jdbc:odbc:javadsn","scott","ti
ger");

Page 237 of 660


Java Book - Chidambaram.S

12. CallableStatement cs=con.prepareCall("{call pro(?,?,?,?)}");


13. PreparedStatement ps=con.prepareStatement("select * from emp");
14. ResultSet rs=ps.executeQuery();
15. cs.setInt(1,7369);
16. cs.setInt(2,20);
17. cs.registerOutParameter(3,Types.VARCHAR);
18. cs.registerOutParameter(4,Types.INTEGER);
19. cs.execute();
20. System.out.print(" Ename= "+cs.getString(3));
21. System.out.print(" Sal= "+cs.getInt(4));
22. System.out.println();
23. }//try
24. catch(Exception e)
25. {
26. System.out.println(e);
27. }//catch
28. }//main
29. }//class
30. Pro2.sql
31. create or replace procedure pro2(tempno in number,tdeptno in number,tename
out varchar2,tsal out number) is
32. e varchar2(40);
33. s number(8,2);
34. begin
35. select ename,sal into e,s from empcopy where empno=tempno and deptno=tdept
no;
36. tename:=e;
37. tsal:=s;
38. end;

Page 238 of 660


Java Book - Chidambaram.S

1. import java.sql.*;
2. import java.io.*;
3. class CallableStatementDemo1
4. {
5. public static void main(String args[])
6. {
7. try
8. {
9. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
10. Connection con=DriverManager.getConnection("jdbc:odbc:javadsn","scott","ti
ger");
11. CallableStatement cs=con.prepareCall("{call pro()}");
12. System.out.println(cs.execute());
13. PreparedStatement ps=con.prepareStatement("select * from empcopy");
14. ResultSet rs=ps.executeQuery();
15. while(rs.next())
16. {
17. System.out.println(" sal= "+rs.getString("sal"));
18. }
19. }//try
20. catch(Exception e)
21. {
22. System.out.println(e);
23. }
24. }
25. }
26. Pro1.sql
27. create or replace procedure pro() is
28. begin
29. update emppay set basic=basic+1000 where eno='e0001'
30. end;

Page 239 of 660


Java Book - Chidambaram.S

Jdbc\CallableStatement\CallableStatementDemo3.java

1. import java.sql.*;
2. import java.io.*;
3. class CallableStatementDemo3
4. {
5. public static void main(String args[])
6. {
7. try
8. {
9. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
10. Connection con=DriverManager.getConnection("jdbc:odbc:javadsn","scott","ti
ger");
11. CallableStatement cs=con.prepareCall("{call pro(?)}");
12. cs.setInt(1,7369);
13. cs.registerOutParameter(1,Types.INTEGER);
14. cs.execute();
15. System.out.println(cs.getInt(1));
16. }//try
17. catch(Exception e)
18. {
19. System.out.println(e);
20. }
21. }
22. }
23. Pro3.sql

Page 240 of 660


Java Book - Chidambaram.S

24. create or replace procedure pro(tempno in out number) is


25. s number(8,2);
26. begin
27. select sal into s from empcopy where empno=tempno;
28. tempno:=s;
29. end;

Below program illustrates CLOB(Character Large Object) and


BLOB(Binary Large Object). CLOB is used to store text and
documents. BLOB is used other than text like media files.

1. import java.sql.*;
2. import java.io.*;
3. class LobDemo
4. {
5. public static void main(String args[])
6. {
7. /* -------------------------------------------- Writing ------------------------
-------------------- */
8. try
9. {
10. System.out.println("1");
11. FileInputStream fis=new FileInputStream("resume.doc");
12. System.out.println("2");
13. byte b[]=new byte[fis.available()];
14. System.out.println("3");
15. fis.read(b);
16. System.out.println("4");
17. FileInputStream fis1=new FileInputStream("photo.jpg");
18. System.out.println("5");
19. byte b1[]=new byte[fis1.available()];

Page 241 of 660


Java Book - Chidambaram.S

20. System.out.println("6");
21. fis1.read(b1);
22. System.out.println("7");
23.
24. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
25. System.out.println("8");
26. Connection con=DriverManager.getConnection("jdbc:odbc:javaoracledsn","scot
t","tiger");
27. System.out.println("9");
28. CallableStatement cs=con.prepareCall("{call proc1(?,?,?)}");
29. System.out.println("9a");
30. Clob clob=cs.getClob(2);
31. System.out.println("10");
32. Blob blob=cs.getBlob(3);
33. System.out.println("11");
34.
35. OutputStream os=clob.setAsciiStream(0);
36. System.out.println("15");
37. os.write(b);
38. System.out.println("16");
39.
40. OutputStream os1=blob.setBinaryStream(0);
41. System.out.println("17");
42. os1.write(b1);
43. System.out.println("18");
44.
45. cs.setString(1,"Ram.s");
46. System.out.println("19");
47. cs.setClob(2,clob);
48. System.out.println("20");
49. cs.setBlob(3,blob);
50. cs.execute();
51. /*------------------ Reading -------------------------*/
52. PreparedStatement ps=con.prepareStatement("select * from blobtable");
53. ResultSet rs=ps.executeQuery();

Page 242 of 660


Java Book - Chidambaram.S

54. Clob clob1=rs.getClob(2);


55. Blob blob1=rs.getBlob(3);
56.
57.
58. InputStream is1=clob1.getAsciiStream();
59. byte b2[]=new byte[is1.available()];
60. is1.read(b2);
61. FileOutputStream fos=new FileOutputStream("resultresume.doc");
62. fos.write(b2);
63.
64. InputStream is2=blob1.getBinaryStream();
65. byte b3[]=new byte[is2.available()];
66. is2.read(b3);
67. FileOutputStream fos1=new FileOutputStream("resultphoto.jpg");
68. fos.write(b3);
69. }
70. catch(Exception e)
71. {
72. System.out.println(e);
73. }
74. }
75. }
76. Procedure:
77. create or replace procedure proc1(name in varchar2,resume in clob,photo in
blob) is
78. tname varchar2(40);
79. tresume clob;
80. tphoto blob;
81. begin
82. tname:=name;
83. tresume:=resume;
84. tphoto:=photo;
85. insert into blobtable values(tname,tresume,tphoto);
86. end;

Page 243 of 660


Java Book - Chidambaram.S

Below program illustrates Connection interface methods

1. import java.sql.*;
2. class ConnectionMethods
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
9. Connection con=DriverManager.getConnection("jdbc:odbc:mydsn");
10. System.out.println(con.getAutoCommit());
11. System.out.println(con.isClosed());
12. con.close();
13. System.out.println(con.isClosed());
14. con=DriverManager.getConnection("jdbc:odbc:mydsn");
15. System.out.println(con.getAutoCommit());
16. PreparedStatement ps=con.prepareStatement("insert into deptmaster values('
d0005','stores','ram')");
17. System.out.println("No of Records Affected="+ps.executeUpdate());
18. ps=con.prepareStatement("select * from deptmaster");
19. ResultSet rs=ps.executeQuery();
20. while (rs.next())
21. {
22. System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(
3));
23. }
24. }
25. catch(Exception e)

Page 244 of 660


Java Book - Chidambaram.S

26. {
27. System.out.println(e);
28. }
29. }
30. }
31. Output
32. true
33. false
34. true
35. true
36. No of Records Affected=1
37. d0001 production ram prasath
38. d0005 stores ram
39. d0002 purchase siva ram kumar
40. d0003 marketing sathish
41. d0004 accounts ram prasath

Below program illustrates GUI illustration with JDBC

1. import java.sql.*;
2. import java.util.*;
3. class ProcessQuery
4. {
5. int columncount=0;
6. int x=0;
7. String query;
8. Vector datavector=new Vector();;
9. Vector columnvector=new Vector();
10. Object getQuery(String query)
11. {
12. Object o=null;
13. this.query=query;
14. defineType();

Page 245 of 660


Java Book - Chidambaram.S

15. if (x==1)
16. {
17. processSelect();
18. o=(Object)selectAnswer();
19. }
20. else if(x==2)
21. {
22. o=(Object)new Integer(otherAnswer());
23. }
24. return o;
25. }
26.
27. void defineType()
28. {
29. if (query.startsWith("select"))
30. {
31. x=1;
32. }
33. else
34. {
35. x=2;
36. }
37. }
38. void processSelect()
39. {
40. try
41. {
42. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
43. Connection con=DriverManager.getConnection("jdbc:odbc:javadsn","javauser",
"javauser");
44. PreparedStatement ps=con.prepareStatement(query);
45. ResultSet rs=ps.executeQuery();
46. ResultSetMetaData meta=rs.getMetaData();
47. columncount=meta.getColumnCount();
48. for (int i=1;i<=columncount;i++)

Page 246 of 660


Java Book - Chidambaram.S

49. {
50. columnvector.addElement(meta.getColumnName(i));
51. }
52.
53. while (rs.next())
54. {
55. Vector rowvector=new Vector();
56. for (int i=1;i<=columncount;i++)
57. {
58. rowvector.addElement(rs.getString(i));
59. }//for
60. datavector.addElement(rowvector);
61. }//while
62. }//try
63. catch(Exception e)
64. {
65. System.out.println("From prcoessSelect ="+e);
66. }
67. }//method
68.
69. Vector selectAnswer()
70. {
71. Vector resultvector=new Vector();
72. resultvector.addElement(columnvector);
73. resultvector.addElement(datavector);
74. return (resultvector);
75. }
76.
77. int otherAnswer()
78. {
79. try
80. {
81. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
82. Connection con=DriverManager.getConnection("jdbc:odbc:javadsn","javauser",
"javauser");

Page 247 of 660


Java Book - Chidambaram.S

83. PreparedStatement ps=con.prepareStatement(query);


84. return (ps.executeUpdate());
85. }//try
86. catch(Exception e)
87. {
88. System.out.println("From otherAnswer ="+e);
89. return 0;
90. }
91. }
92. }//class

Output

1. import javax.swing.*;
2. import java.awt.event.*;
3. import javax.swing.border.*;
4. import java.awt.*;
5. import java.util.*;
6. class GUI extends JFrame implements ActionListener
7. {
8. JPanel northpanel,centerpanel;
9. JButton submitcmd;
10. JTextField text;
11. JScrollPane scrollpane;
12. JTable table;
13. GUI()
14. {
15. super("Data Table");
16. setExtendedState(JFrame.MAXIMIZED_BOTH);
17. northpanel=new JPanel();
18. centerpanel=new JPanel();
19. text=new JTextField(50);
20. submitcmd=new JButton("Submit");
21. register();

Page 248 of 660


Java Book - Chidambaram.S

22. effectsProvider();
23. layoutProvider();
24. addControls();
25.
26. }
27. void register()
28. {
29. submitcmd.addActionListener(this);
30. }
31. void effectsProvider()
32. {
33. northpanel.setBorder(new LineBorder(Color.blue,10));
34. centerpanel.setBorder(new LineBorder(Color.blue,10));
35. }
36. void layoutProvider()
37. {
38. northpanel.setLayout(new FlowLayout());
39. centerpanel.setLayout(new BorderLayout());
40. setLayout(new BorderLayout());
41. }
42. void addControls()
43. {
44. northpanel.add(text);
45. northpanel.add(submitcmd);
46. add(northpanel,BorderLayout.NORTH);
47. add(centerpanel,BorderLayout.CENTER);
48. show();
49. }
50. public void actionPerformed(ActionEvent ae)
51. {
52. ProcessQuery pq=new ProcessQuery();
53. Object o=pq.getQuery(text.getText());
54. if (o instanceof Vector)
55. {
56. int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;

Page 249 of 660


Java Book - Chidambaram.S

57. int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;


58. Vector v1=(Vector)o;
59. Vector column=(Vector)v1.get(0);
60. Vector data=(Vector)v1.get(1);
61. table=new JTable(data,column);
62. scrollpane=new JScrollPane(table,v,h);
63. centerpanel.add(scrollpane,BorderLayout.CENTER);
64. show();
65. }
66. else
67. {
68. Integer i=(Integer)o;
69. text.setText(i.toString());
70. }
71. }
72.
73. public static void main(String args[])
74. {
75. new GUI();
76. }
77. }

Page 250 of 660


Java Book - Chidambaram.S

Below program illustrates executeBatch(). This method can be used to execute the group
of queries.

1. import java.sql.*;
2. class ExecuteBatchDemo
3. {
4. void m1()
5. {
6. Connection con=null;
7. try
8. {

Page 251 of 660


Java Book - Chidambaram.S

9. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
10. con=DriverManager.getConnection("jdbc:odbc:oracledsn","scott","tiger");
11. con.setAutoCommit(false);
12. Statement stmt=con.createStatement();
13. stmt.addBatch("update t1 set amount=amount+100");
14. stmt.addBatch("update t2 set amount=amount+100");
15. stmt.addBatch("update t3 set amount=amount+100");
16. int res[]=stmt.executeBatch();
17. for (int i=0;i<res.length;i++)
18. {
19. System.out.println(res[i]);
20. }
21. con.close();
22. }
23. catch(Exception e)
24. {
25. try
26. {
27. //con.rollback();
28. con.commit();
29. }catch(Exception e1){}
30. e.printStackTrace();
31. }
32. }
33. void m2()
34. {
35. try
36. {
37. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
38. Connection con=DriverManager.getConnection("jdbc:odbc:oracledsn","scott","
tiger");
39. Statement stmt=con.createStatement();
40. stmt.execute("create table t1(amount number(4))");
41. stmt.execute("create table t2(amount number(4))");
42. stmt.execute("create table t3(aamount number(4))");

Page 252 of 660


Java Book - Chidambaram.S

43. stmt.execute("insert into t1 values(1000)");


44. stmt.execute("insert into t2 values(1000)");
45. stmt.execute("insert into t3 values(1000)");
46. con.close();
47. }
48. catch(Exception e)
49. {
50. e.printStackTrace();
51. }
52. }
53. public static void main(String args[])
54. {
55. ExecuteBatchDemo ebd=new ExecuteBatchDemo();
56. //ebd.m2();
57. ebd.m1();
58. }
59. }
60. O/P
61. 1
62. 1
63. 1

Page 253 of 660


Java Book - Chidambaram.S

Below program illustrates BLOB (Binary Large Object), which requires Type3 or Type4
driver. Add classes111.jar in your classpath.

1. import java.sql.*;
2. import java.io.*;
3. import oracle.jdbc.driver.*;
4. import oracle.sql.*;
5. class BLobDemo
6. {
7. public static void main(String args[])
8. {
9. try
10. {
11. Class.forName("oracle.jdbc.driver.OracleDriver");
12. OracleConnection con=(OracleConnection)DriverManager.getConnection("jdbc:o
racle:thin:@localhost:1521:sbit","scott","tiger");
13. con.setAutoCommit(false);
14. // Empty Lob Insertion
15. OraclePreparedStatement ops0=(OraclePreparedStatement)con.prepareStatement
("Insert into map values(?,?)");
16. ops0.setString(1,"India");
17. ops0.setBLOB(2,BLOB.empty_lob());
18. ops0.executeUpdate();
19. // preparing byte[]
20. FileInputStream fis=new FileInputStream("photo.jpg");
21. byte b[]=new byte[fis.available()];
22. fis.read(b);
23. fis.close();
24. // Writing
25. OraclePreparedStatement ops=(OraclePreparedStatement)con.prepareStatement(
"select photo from map for update of photo");
26. OracleResultSet ors=(OracleResultSet)ops.executeQuery();
27. ors.next();
28. BLOB blob=ors.getBLOB(1);
29. OutputStream os=blob.getBinaryOutputStream();

Page 254 of 660


Java Book - Chidambaram.S

30. os.write(b);
31. ops=(OraclePreparedStatement)con.prepareStatement("update map set photo=?
where country=?");
32. ops.setBLOB(1,blob);
33. ops.setString(2,"India");
34. ops.executeUpdate();
35. ops.close();
36. con.commit();
37. // Reading
38. OraclePreparedStatement opsr=(OraclePreparedStatement)con.prepareStatement
("select * from map");
39. OracleResultSet orsr=(OracleResultSet)opsr.executeQuery();
40. orsr.next();
41. BLOB blobr=orsr.getBLOB("photo");
42. System.out.println(blobr.length());
43. InputStream in=blobr.getBinaryStream();
44. byte br[]=blobr.getBytes(((long)1),((int)blobr.length()));
45. System.out.println(br.length);
46. FileOutputStream fos=new FileOutputStream("newphoto.jpg");
47. fos.write(br);
48. fos.close();
49. opsr.close();
50. con.commit();
51. con.close();
52. }//try
53. catch(Exception e)
54. {
55. e.printStackTrace();
56. }
57. }
58. }
59.
60. O/P
61. Photo.jpg will be stored in oracle table.
62. newphoto.jpg will be created.

Page 255 of 660


Java Book - Chidambaram.S

Clobdemo.java

1. import java.sql.*;
2. import java.io.*;
3. import oracle.jdbc.driver.*;
4. import oracle.sql.*;
5. class ClobDemo
6. {
7. public static void main(String args[])
8. {
9. try
10. {
11. Class.forName("oracle.jdbc.driver.OracleDriver");
12. OracleConnection con=(OracleConnection)DriverManager.getConnection("jdbc:o
racle:thin:@localhost:1521:sbit","scott","tiger");
13. con.setAutoCommit(false);
14. // Empty Lob Insertion
15. OraclePreparedStatement ops0=(OraclePreparedStatement)con.prepareStatement
("Insert into resumes values(?,?)");
16. ops0.setString(1,"Rama");
17. ops0.setCLOB(2,CLOB.empty_lob());
18. ops0.executeUpdate();
19. // preparing char[]
20. FileInputStream fis=new FileInputStream("Text.txt");
21. FileDescriptor fd=fis.getFD();
22. FileReader fr=new FileReader(fd);
23. int totallen=fis.available();
24. char ch[]=new char[totallen];
25. fr.read(ch,0,ch.length);
26. fr.close();
27. // Writing

Page 256 of 660


Java Book - Chidambaram.S

28. OraclePreparedStatement ops=(OraclePreparedStatement)con.prepareStatement(


"select resume from resumes for update of resume");
29. OracleResultSet ors=(OracleResultSet)ops.executeQuery();
30. ors.next();
31. CLOB clob=ors.getCLOB(1);
32. Writer writer=clob.getCharacterOutputStream();
33. writer.write(ch);
34. writer.close();
35. ops=(OraclePreparedStatement)con.prepareStatement("update resumes set resu
me=? where name=?");
36. ops.setCLOB(1,clob);
37. ops.setString(2,"Rama");
38. ops.executeUpdate();
39. ops.close();
40. con.commit();
41. // Reading
42. OraclePreparedStatement opsr=(OraclePreparedStatement)con.prepareStatement
("select * from resumes");
43. OracleResultSet orsr=(OracleResultSet)opsr.executeQuery();
44. orsr.next();
45. CLOB clobr=orsr.getCLOB("resume");
46. Reader reader=clobr.getCharacterStream();
47. char chr[]=new char[totallen];
48. reader.read(chr);
49. System.out.println(chr.length);
50. reader.close();
51. //Writing into file
52. FileWriter fw=new FileWriter("NewText.txt");
53. fw.write(chr);
54. fw.close();
55. //closing
56. opsr.close();
57. con.commit();
58. con.close();
59. }//try

Page 257 of 660


Java Book - Chidambaram.S

60. catch(Exception e)
61. {
62. e.printStackTrace();
63. }
64. }
65. }
66.
67. Output
68. The data of Text.txt will be written into oracle table.
69. The output will be in NewText.txt file.

Page 258 of 660


Java Book - Chidambaram.S

Chapter 27 - javax.sql

It is added in java 1.4 version

The DriverManager is still valid, and it will continue to run. The


newer DataSource mechanism is preferred because it offers many advantages over
the DriverManager.

These are the main advantages of using a DataSource object to make a


connection:

It is not necessary to make changes in application code when something about


the data source or driver changes.

Connection and Statement pooling and distributed transactions are available


through a DataSource object. Connections made through the DriverManager do not
have connection and statement pooling or distributed transaction capabilities.

Oracle Connection

To establish the connection with oracle the connection string can be specified
in two ways.

Using Service name

URL - jdbc:oracle:thin:@//localhost:1521/XE

Here we are using thin driver and localhost system. Port no is 1521. XE is the
service name.

Using SID name

URL - jdbc:oracle:thin:@localhost:1521:XE

In DataSourceManager class getOracleDataSource() returns OracleDataSource.

getMysqlDataSource() returns MySqlDataSource.

Page 259 of 660


Java Book - Chidambaram.S

In DataSourceDemo class printOracleData() prints data in oracle.

printMySQLData() prints data in MySQL.

In DataSourceDemo class, we are using javax.sql.DataSource and


oracle.jdbc.pool.OracleDataSource, com.mysql.cj.jdbc.MysqlDataSource are
implementing DataSource interface. So we get DataSource interface object when
we return OracleDataSource and MysqlDataSource. It is commonize the code.

DataSourceManager.java

1. import oracle.jdbc.pool.OracleDataSource;
2.
3. import com.mysql.cj.jdbc.*;
4.
5. public class DataSourceManager {
6.
7. public static OracleDataSource getOracleDataSource()
8. {
9. try
10. {
11. OracleDataSource dataSource=new OracleDataSource();
12. dataSource.setURL("jdbc:oracle:thin:@localhost:1521/XE");
13. dataSource.setUser("system");
14. dataSource.setPassword("admin");
15. return dataSource;
16.
17. }
18. catch(Exception e)
19. {
20. e.printStackTrace();
21. return null;
22. }
23. }
24.

Page 260 of 660


Java Book - Chidambaram.S

25. public static MysqlDataSource getMysqlDataSource()


26. {
27. try
28. {
29. MysqlDataSource dataSource=new MysqlDataSource();
30. dataSource.setURL("jdbc:mysql://localhost:3306");
31. // In MySQL world database is by default available
32. dataSource.setDatabaseName("world");
33. //User name is root
34. dataSource.setUser("root");
35. //admin is the password
36. dataSource.setPassword("admin");
37. return dataSource;
38.
39. }
40. catch(Exception e)
41. {
42. e.printStackTrace();
43. return null;
44. }
45. }
46.
47. }

1. import java.sql.Connection;
2. import java.sql.PreparedStatement;
3. import java.sql.ResultSet;
4.
5. import javax.sql.DataSource;
6.
7. class DataSourceDemo {
8. void printOracleData() {

Page 261 of 660


Java Book - Chidambaram.S

9. try {
10. System.out.println("***** ORACLE DATA *****");
11. //javax.sql.DataSource is the interface
12. DataSource dataSource = DataSourceManager.getOracleDataSource(
);
13. Connection con = dataSource.getConnection();
14. PreparedStatement ps = con.prepareStatement("select * from dep
t");
15. ResultSet rs = ps.executeQuery();
16. while (rs.next()) {
17. System.out.println(rs.getString(1) + " " + rs.getString(2
) + " " + rs.getString(3));
18. }
19.
20. } catch (Exception e) {
21. e.printStackTrace();
22. }
23.
24. }
25.
26. void printMysqlData() {
27. try {
28. System.out.println("***** MYSQL DATA *****");
29. DataSource dataSource = DataSourceManager.getMysqlDataSource()
;
30. Connection con = dataSource.getConnection();
31. PreparedStatement ps = con.prepareStatement("select * from wor
ld.city");
32. ResultSet rs = ps.executeQuery();
33. while (rs.next()) {
34. System.out.println(rs.getString(1) + " " + rs.getString(2
) + " " + rs.getString(3));
35. }
36.
37. } catch (Exception e) {

Page 262 of 660


Java Book - Chidambaram.S

38. e.printStackTrace();
39. }
40.
41. }
42.
43. public static void main(String args[]) {
44.
45. DataSourceDemo dataSourceDemo = new DataSourceDemo();
46. dataSourceDemo.printOracleData();
47. dataSourceDemo.printMysqlData();
48. }
49. }
50.
51. ***** ORACLE DATA *****
52. 10 ACCOUNTING NEW YORK
53. 20 RESEARCH DALLAS
54. 30 SALES CHICAGO
55. 40 OPERATIONS BOSTON
56. ***** MYSQL DATA *****
57. 1 Kabul AFG
58. 2 Qandahar AFG
59. 3 Herat AFG
60. 4 Mazar-e-Sharif AFG
61. 5 Amsterdam NLD

Page 263 of 660


Java Book - Chidambaram.S

Connection pool is the cache of connection and it is the mechansm to manage


mulitple connections in the pool, so that we can reuse the connection whenever
required.

GlassFish server

Install GlassFish server

In this example, we are using GlassFish 4.1.2. We can download it from


https://javaee.github.io/glassfish/download and click GlassFish 4.1.2 - Full
Platform. It will download the GlassFish 4.1.2 folder zip file and unzip the
folder. That's it.. now we are good in installation.

Domain Creation in GlassFish Server

Let's see the how we create the domain using asadmin command.

Go to following path in dos prompt where you extracted glassfish.

> asadmin create-domain mydomain1.

Here mydomain1 is a name of domain. After entering this command press enter.
Now it will ask the username. Type admin, and press enter. It may be anything
.. for this example .. just we are following this name.

F:\Servers\glassfish-4.1.2\glassfish4\bin>asadmin create-domain mydomain1

Enter admin user name [Enter to accept default "admin" / no password]>admin

Now it will ask password as like below. Type admin and press enter.

F:\Servers\glassfish-4.1.2\glassfish4\bin>asadmin create-domain mydomain1

Enter admin user name [Enter to accept default "admin" / no password]>admin

Enter the admin password [Enter to accept default of no password]>admin (press


enter)

Page 264 of 660


Java Book - Chidambaram.S

Enter the admin password again>admin (press enter)

Now we can see the following results.

F:\Servers\glassfish-4.1.2\glassfish4\bin>asadmin create-domain mydomain1

Enter admin user name [Enter to accept default "admin" / no password]>admin

Enter the admin password [Enter to accept default of no password]>

Enter the admin password again>

Using default port 4848 for Admin.

Using default port 8080 for HTTP Instance.

Using default port 7676 for JMS.

Using default port 3700 for IIOP.

Using default port 8181 for HTTP_SSL.

Using default port 3820 for IIOP_SSL.

Using default port 3920 for IIOP_MUTUALAUTH.

Using default port 8686 for JMX_ADMIN.

Using default port 6666 for OSGI_SHELL.

Using default port 9009 for JAVA_DEBUGGER.

Distinguished Name of the self-signed X.509 Server Certificate is:

[CN=Chidambaram-PC,OU=GlassFish,O=Oracle Corporation,L=Santa
Clara,ST=California,C=US]

Distinguished Name of the self-signed X.509 Server Certificate is:

[CN=Chidambaram-PC-instance,OU=GlassFish,O=Oracle Corporation,L=Santa
Clara,ST=California,C=US]

Page 265 of 660


Java Book - Chidambaram.S

Domain mydomain1 created.

Domain mydomain1 admin port is 4848.

Domain mydomain1 admin user is "admin".

Command create-domain executed successfully.

Now mydomain1 is created successfully.

Start the domain

In the same dos window, type the command as below

F:\Servers\glassfish-4.1.2\glassfish4\bin>asadmin start-domain mydomain1

Waiting for mydomain1 to start ..............

Successfully started the domain : mydomain1

domain Location: F:\Servers\glassfish-


4.1.2\glassfish4\glassfish\domains\mydomain1

Log File: F:\Servers\glassfish-


4.1.2\glassfish4\glassfish\domains\mydomain1\logs\server.log

Admin Port: 4848

Command start-domain executed successfully.

Now mydomain1 started successfully.

server startup in eclipse

Go to eclipse

Window -> Show View -> Others -> type servers and click servers and click OK
button

Page 266 of 660


Java Book - Chidambaram.S

In Servers pane, click the link "No servers are available. Click this link to
create a new server" as in above image to select the server

Now we will get the below dialog.

Select GlassFish and click Next button

Page 267 of 660


Java Book - Chidambaram.S

Enter GlassFish location and Java Location, the path in the system.

Click Next button

Now we will get below dialog and we need to enter the below values.

In Name text box enter the domain name just we created as like below

Name : GlassFish 4 [mydomain1]

Host name : localhost

In Domain Path text box, enter the domain path which is available in dos prompt
when we create the domain.

Page 268 of 660


Java Book - Chidambaram.S

Domain path : F:\Servers\glassfish-4.1.2\glassfish4\glassfish\domains\mydomain1

Admin name : admin - We entered the username when we create the domain

Admin password : admin - We entered the password when we create the domain

That's it .. remaining part leave it as it is..

Click Next button.

If any project is needed to add we can add using Add button. Otherwise click
Finish button and we can add the project later.

Then select the server name in the servers pane and right click and select the
Start option in the popup menu.

Now GlassFish server is stared as like below

GlassFish Server Admin console

Go to chrome and type http://localhost:4848, press enter

Page 269 of 660


Java Book - Chidambaram.S

Type the username and password.. admin and admin. Click Login button.

Now we will get the admin conslole as like below.

Page 270 of 660


Java Book - Chidambaram.S

Chapter 28 - java.util package

java.util packages contains collections framework (including legacy collection


classes) and miscellaneous utility classes such as a string tokenizer, a
random-number generator.

Collection

A collection is an object that represents a group of objects such as the


classic Vector class. Collection framework must be studied with the
understanding of two types Legacy Collection Framework and Modern Collection
Framework. Each one of these two types comes with two broad types of
collections as below.

Object based collections - Only objects are stored into the collection

Keyvalue based collections - Key value combination like name="rama"; age=23 like
these type of objects wil be stroed in key value based collection.

Let's discuss about above topics in more detail

Legacy Classes

It was introduced with original java release. All legacy classes are synchronized and
thread safe.

Synchronized and thread safe means, only one thread can access the legacy class object
at a time.

Legacy classes are extended the new collections framework to use the new
functionalites with legacy classes.

In below we can see Vector implements List - Vector is the legacy classe and List is
the new collection interface.

Page 271 of 660


Java Book - Chidambaram.S

Dictionary implements Map - Dictionary is the legacy class and Map is the new
collection interface.

In Legacy classes there are object based classes and Key value based classes as below.

Object based classes

Vector implements List

Stack extends Vector

Key value based

Dictionary implements Map

Hashtable extends Dictionary

Modern Collections Framework

It was released since java 1.2. This is modern framework and high performance
also non synchronized. In Collections Framework, there are Object based
collection interfaces, Object based collection classes, Key value based collection
interfaces and Key value based collection classes

Let's discuss more detail.

Object based collection interfaces

java.util.Collection is the inferface and below interfaces are sub interface of


Collection

java.util.Set extends Collection

java.util.SortedSet extends Set

java.util.NavigableSet extends NavigableSet

java.util.Queue extends Collection

Key value based collection interfaces

Page 272 of 660


Java Book - Chidambaram.S

java.util,.Map is the interface and following interfaces are sub interface of


Map

java.util.SortedMap

java.util.NavigableMap

java.util.concurrent.ConcurrentMap

java.util.concurrent.ConcurrentNavigableMap

java.util,.Map is the interface and following interfaces are sub interface of


Map

java.util.SortedMap

java.util.NavigableMap

java.util.concurrent.ConcurrentMap

java.util.concurrent.ConcurrentNavigableMap

Object based collection classes

LinkedList Implements a linked list by extending AbstractSequentialList.

ArrayList Implements a dynamic array by extending AbstractList.

ArrayDeque Implements a dynamic double-ended queue by extending


AbstractCollection

and implementing the Deque interface.

AbstractSet Extends AbstractCollection and implements most of the Set


interface.

EnumSet Extends AbstractSet for use with enum elements.

HashSet Extends AbstractSet for use with a hash table.

LinkedHashSet Extends HashSet to allow insertion-order iterations.

Page 273 of 660


Java Book - Chidambaram.S

PriorityQueue Extends AbstractQueue to support a priority-based queue.

Key value based collection classes

We will discuss about each of them to understand more better and based on real
time usage.

All Modern Collection Framework classes are not synchronized. If multiple


threads try to modify the collection at the same time, then the final outcome
will be non-deterministic.

We need to take care about this and we will discuss about this in separate
topic.

ArrayList

ArrayList implements List

It is the dynamic Array. Array is the fixed length. ArrayList is a variable length
collection. ArrayList can dynamically increase or decrease in size based on objects
added and removed.

It allows duplicates

It allows null values

Constructors

ArrayList()

Constructs an empty list with an initial capacity of ten.

ArrayList(Collection<? extends E> c) - Constructs with existing collection.

public ArrayList(int initialCapacity)

Constructs an empty list with the specified initial capacity.

Page 274 of 660


Java Book - Chidambaram.S

ArrayList example program.

1. import java.util.ArrayList;
2. class ArrayListDemo
3. {
4. public static void main(String args[])
5. {
6. //ArrayList object created with a generic way to store String only
7. ArrayList<String> arrayList1=new ArrayList<>();
8. arrayList1.add("One");
9. arrayList1.add("Two");
10. arrayList1.add("Four");
11. //arrayList2 is created and it has all the elements of arrayList1
12. ArrayList<String> arrayList2=new ArrayList<>(arrayList1);
13. System.out.println("arrayList1="+arrayList1);
14. System.out.println("arrayList2="+arrayList2);
15. System.out.println("arrayList1.size()="+arrayList1.size());
16. System.out.println("arrayList2.size()="+arrayList2.size());
17.
18. arrayList1.remove("Two");
19. System.out.println("After Removal from arrayList1");
20. System.out.println("arrayList1.size()="+arrayList1.size());
21. System.out.println("arrayList2.size()="+arrayList2.size());
22. }
23. }
24.
25. Output
26.
27. arrayList1=[One, Two, Four]
28. arrayList2=[One, Two, Four]
29. arrayList1.size()=3
30. arrayList2.size()=3
31. After Removal from arrayList1
32. arrayList1.size()=2
33. arrayList2.size()=3

Page 275 of 660


Java Book - Chidambaram.S

ListIterator

ListIterator is the interface to iterate the list based collections. It means


those classes implement List interface such as ArrayList, LinkedList can use
this interface.

List interface provides below method to get the ListIterator

ListIterator listIterator()

Iterator

We can use Iterator too to list the items in the collection

Collection interface provides the below method to get the Iterator.

Iterator iterator().

ListIterator extends Iterator

Iterator methods

boolean hasNext() Returns true if the iteration has more elements.

Object next() - Returns next element of the collection

void remove() - remove the element of collection where the iterator cursor is
currently positioned.

ListIterator can use the same above methods. In addition


ListIterator has below methods.

boolean hasPrevious()-Returns true if this list iterator has more elements in


previous

Object previous() - > Returns the previous object

int previousIndex() - Returns the index number of previous object

Page 276 of 660


Java Book - Chidambaram.S

int nextIndex()- Returns the index number of next object

void set(E e) - Replaces the last element returned by next() or previous() by


given object.

Let's see the ListIterator example

Program 1

1. import java.util.ArrayList;
2. import java.util.ListIterator;
3. class ListIteratorDemo
4. {
5. public static void main(String args[])
6. {
7. //ArrayList object created with a generic way to store string only
8. ArrayList<String> arrayList1=new ArrayList<>();
9. arrayList1.add("One");
10. arrayList1.add("Two");
11. arrayList1.add("Four");
12. ListIterator<String> listIterator= arrayList1.listIterator();
13. //add() adds "Five" in 0th index. Because ListIterator cursor now points i
n 0th index
14. listIterator.add("Five");
15. System.out.println("arrayList1="+arrayList1);
16. System.out.println("List Iterator hasNext iteration results");
17. while (listIterator.hasNext())
18. System.out.println(listIterator.next().toString());
19. //add() adds "Six" in last position. Because ListIterator cursor now point
s in last position
20. listIterator.add("Six");
21. System.out.println("arrayList1="+arrayList1);
22. System.out.println("List Iterator hasPrevious iteration results");
23. while (listIterator.hasPrevious())
24. System.out.println(listIterator.previous().toString());

Page 277 of 660


Java Book - Chidambaram.S

25. }
26. }

Program 2

1. import java.util.*;
2. class ListIteratorDemo
3. {
4. public static void main(String args[])
5. {ArrayList al=new ArrayList();
6. al.add("A");
7. al.add("B"); // duplicate allowed
8. al.add("C");
9. System.out.println(al.add("D"));
10. System.out.println(al.add("D"));
11. System.out.println(al);
12. ListIterator li=al.listIterator();
13. while (li.hasNext())
14. {
15. if (li.nextIndex()==2)
16. {
17. /*
18. set() overwrites the existing data where the iterator cursor is poistioned

19. */
20. li.set("z"); }
21. //next() - returns the element where the cursor is positioned
22. System.out.println("Next ="+li.next());
23. //nextIndex() - returns the index number where the cursor is positioned
24. System.out.println("Next index ="+li.nextIndex());
25. }
26. System.out.println(al);
27. }
28. }

Page 278 of 660


Java Book - Chidambaram.S

29.
30. Output
31.
32. [A, B, C, D]
33. Next =A
34. Next =1
35. Next =B
36. Next =2
37. Next =C
38. Next =3
39. Next =D
40. Next index =4
41. [A, z, C, D]

LinkedList
LinkedList uses doubly linked list data structure to store the elements. It contains
the nodes where it stores data along with reference link of next node and previous
node.

LinkedList implements List, Queue, Deque

LinkedList Constructor

public LinkedList()

Constructs an empty list.

public LinkedList(Collection c)

Constructs a list containing the elements of the specified collection

1. class LinkedListDemo
2. {
3. public static void main(String args[])

Page 279 of 660


Java Book - Chidambaram.S

4. {
5. LinkedList ll=new LinkedList();
6. ll.add(5);
7. ll.add(50);
8. System.out.println(ll.add(75));
9. System.out.println(ll.add(75));
10. System.out.println(ll);
11. ll.addFirst(1);
12. System.out.println(ll);
13. ll.addLast(1);
14. System.out.println(ll);
15. System.out.println("Remove First Content of ll ="+ll.removeFirst().toStrin
g());
16. System.out.println("After Removing First ="+ll);
17. ll.removeLast();
18. System.out.println("After Removing Last ="+ll);
19. }//main
20. }//class

LinkedList vs ArrayList

LinkedList internally manages linked list data structure to store elements.

Each one element links with previous and next element. So adding, removing
elements are not working index based.

When you remove or add the element it will change internal structure of
LinkedList.

ArrayList is working index based. Index starts from 0. The size will be growing
or shrinking based on add or remove operations. In below table you can see the
log value of search, delete and add performance between two.

As you see, the search and add functions of ArrayList are good performance than
LinkedList. Search of LinkedList is good performance than ArrayList. Both
allow duplicate and nulls.

Page 280 of 660


Java Book - Chidambaram.S

In addition with ArrayList, LinkedList comes with following methods.

addFirst(Object) - adds the element at first position

addLast(Object) - adds the element at last position

public Iterator<E> descendingIterator() - Method is available from Deque to get


the iterator to list the elements from tail to head (reverse order).

LinkedList implements Deque, Queue and ArrayList not.

Allow
Class Search Delete Add Allow Nulls
Duplicates

ArrayList O(1) O(n) O(1) Yes Yes

LinkedList O(n) O(1) O(n) Yes Yes

LinkedHashSet

LinkedHashSet implements Set interface. LinkedHashSet uses doubly linked list


data structure to store the elements like LinkedList, where as LinkedList is
the list based collection; LinkedHashSet is the set based collection.

LinkedHashSet constructors

LinkedHashSet()

Constructs a linked hash set with the default initial capacity (16) and load
factor (0.75).

LinkedHashSet(Collection c)

Page 281 of 660


Java Book - Chidambaram.S

Constructs a new linked hash set with the same elements as the specified
collection.

LinkedHashSet(int initialCapacity)

Constructs a new linked hash set with the specified initial capacity and the
default load factor (0.75).

LinkedHashSet(int initialCapacity, float loadFactor)

Constructs a linked hash set with the specified initial capacity and load
factor.

LinkedHashSetDemo example program

1. import java.util.*;
2. class LinkedHashSetDemo
3. {
4. public static void main(String args[])
5. {
6. LinkedHashSet linkedHashSet=new LinkedHashSet();
7. linkedHashSet.add("a");
8. linkedHashSet.add("b");
9. linkedHashSet.add("e");
10. linkedHashSet.add("d");
11. //LinkedHashSet doen't allow duplicates
12. System.out.println("linkedHashSet.add(\"c\") added c first time ="+linkedH
ashSet.add("c"));
13. System.out.println("linkedHashSet.add(\"c\") added c second time ="+linked
HashSet.add("c"));
14. System.out.println("***** linkedHashSet *****");
15. System.out.println(linkedHashSet);
16. //HashSet object created with the initial elements of linkedHashSet
17. HashSet hashSet1=new HashSet(linkedHashSet);
18. /*
19. * HashSet object created with assigning linkedHashSet

Page 282 of 660


Java Book - Chidambaram.S

20. * Now hashset2 refers the same memory of linkedHashSet


21. */
22. HashSet hashSet2=linkedHashSet;
23. //adding in hashSet2 also affects linkedHashSet
24. hashSet2.add("f");
25. System.out.println("***** linkedHashSet after adding element \"f\" in hash
set2 *****");
26. System.out.println(linkedHashSet);
27. }
28. }
29.
30. Output
31.
32. linkedHashSet.add("c") added c first time =true
33. linkedHashSet.add("c") added c second time =false
34. ***** linkedHashSet *****
35. [a, b, e, d, c]
36. ***** linkedHashSet after adding element "f" in hashset2 *****
37. [a, b, e, d, c, f]

Page 283 of 660


Java Book - Chidambaram.S

Hashtable

This class implements a hash table, which maps keys to values. Any non-
null object can be used as a key or as a value.

Hashtable Constructors

Hashtable()

Constructs a new, empty hashtable with a default initial capacity (11) and load factor
(0.75).

Hashtable(int initialCapacity)

Constructs a new, empty hashtable with the specified initial capacity and default load
factor (0.75).

Hashtable(int initialCapacity, float loadFactor)

Constructs a new, empty hashtable with the specified initial capacity and the
specified load factor.

Hashtable(Map<? extends K,? extends V> t)

Constructs a new hashtable with the same mappings as the given Map.

HashSet
HashSet extends AbstractSet and implements the Set interface. It creates a collection
that uses a hash table for storage.

The following constructors are defined:

HashSet( ) - default capacity is 16

Page 284 of 660


Java Book - Chidambaram.S

HashSet(Collection c) - creates HashSet with initial values from c

HashSet(int capacity) - creates HashSet with specified capacity

HashSet(int capacity, float fillRatio) - creates HashSet with specified capacity and
fillRatio.

The fill ratio must be between 0.0 and 1.0. Default value 0.75. It determines the new
capacity when Hashtable reaches its capacity

HashSet does not have any methods and it can use the methods from its super classes
and interfaces

HashSet does not guarantee the order of its elements.,

PriorityQueue
PriorityQueue extends AbstractQueue

AbstractQueue implements Queue and Collection. So we can use Queue and Collection and
AbstractQueue methods here.

By using this class we can implement queue concept in our application.

If we prints or lists the elements it will not print the order as we inserted.

Instead we can use peek() or poll() to get the head of the queue.

Let's see the below program and inline comments to understand each method.

1. import java.util.Arrays;
2. import java.util.PriorityQueue;
3.
4. class PriorityQueueDemo
5. {
6. public static void main(String args[])
7. {
8. PriorityQueue<Integer> pq=new PriorityQueue<>();

Page 285 of 660


Java Book - Chidambaram.S

9. // add() Collection interface method adds given element to the queue


10. pq.add(2);
11. pq.add(1);
12. pq.add(3);
13. // add() returns true or false. Just we printed here
14. System.out.println("Add 6 is ="+pq.add(6));
15. System.out.println("Add 6 is ="+pq.add(6));
16. // the elements of pq will be printed
17. System.out.println(pq);
18. /*
19. retrieves elemet head of the queue but doesn't remove
20. Throws: NoSuchElementException - if this queue is empty
21. */
22. System.out.println("Head of Element Using element()="+pq.element().toStrin
g());
23. System.out.println(pq);
24. //retrieves elemet head of the queue but doesn't remove. null returned if
no elements
25. System.out.println("Head of Element Using peek()="+pq.peek());
26. System.out.println(pq);
27. /*
28. retrieves elemet head of the queue and remove that element. null returned
if no elements
29. */
30. System.out.println("Head of Element Using poll()="+pq.poll());
31.
32. System.out.println(pq);
33. System.out.println("Head of Element Using remove()="+pq.remove());
34. System.out.println("pq="+pq);
35. }
36. }
37.
38. Output
39.
40. Add 6 is =true

Page 286 of 660


Java Book - Chidambaram.S

41. Add 6 is =true


42. [1, 2, 3, 6, 6]
43. Head of Element Using element()=1
44. [1, 2, 3, 6, 6]
45. Head of Element Using peek()=1
46. [1, 2, 3, 6, 6]
47. Head of Element Using poll()=1
48. [2, 6, 3, 6]
49. Head of Element Using remove()=2
50. pq=[3, 6, 6]
51.

TreeSet
TreeSet implements NavigableSet and stores the objects in ascening order. Its
performance of storage and retrieval are quite fast.

By using Comparator we can define the order. Let's see the examples and constructors.

TreeSet Constructors

TreeSet()

Constructs a new, empty tree set

TreeSet(Collection c)

Constructs TreeSet with elements in c

TreeSet(SortedSet s)

Constructs a new tree set containing the same elements and using the same ordering as
the specified sorted set.

TreeSet(Comparator comparator)

Constructs a new, empty tree set. By default TreeSet makes ascedning order. By using
this constructor, we can change the logic like descending by using Comparator.

Page 287 of 660


Java Book - Chidambaram.S

Below example illustrates the Comparator

ComparatorDemo is the sub class of Comparator and it overrides int compare().

Wheneven the objects are stored in TreeSet, the compare method will be called by
runtime by passing the two objects.

Let's see program with inline comments to understand more better.

1. import java.util.*;
2. class ComparatorDemo implements Comparator
3. {
4. int val=0;
5. //runtime calls this method automatically.
6. public int compare(Object ob1,Object ob2)
7. {
8. String str1=(String)ob1;
9. String str2=(String)ob2;
10. /*
11. compareTo() is String class method returns ascii different between str1 an
d str2
12. str1.compareTo(str2) - To make ascending
13. str2.compareTo(str1) - To make descending
14. Nothing else we need to do; returning value is enough and runtime takes ca
re to make the order in TreeSet.
15. */
16. val=str1.compareTo(str2);
17. return val;
18. }
19. }
20. class TreeSetDemo
21. {
22. public static void main(String args[])
23. {
24. ComparatorDemo cd=new ComparatorDemo();
25. /*

Page 288 of 660


Java Book - Chidambaram.S

26. Here ComparatorDemo object is passed to TreeSet constructor. This enables


runtime to call compare method of Comparator's sub class to define the order to
store the elements in TreeSet.
27. If we create the empty constructor for TreeSet the compare method will not
be called and make the order as ascending.
28. */
29. TreeSet ts=new TreeSet(cd);
30. ts.add("Rama.S");
31. ts.add("Raj");
32. ts.add("Arvinth");
33. ts.add("Subbu");
34. System.out.println(ts);
35. }
36. }
37.
38. Output
39.
40. [Arvinth, Raj, Rama.S, Subbu]

Class Allow Allow Nulls


Duplicates

HashSet No Yes

LinkedHashSet No Yes

TreeSet No No

PriorityQueue Yes No

Page 289 of 660


Java Book - Chidambaram.S

HashMap
HashMap extends AbstractMap implement Map

Constructors

HashMap()

Constructs an empty HashMap with the default initial capacity (16) and the default
load factor (0.75).

HashMap(int initialCapacity)

Constructs an empty HashMap with the specified initial capacity and the default load
factor (0.75).

The capacity is the number of buckets in the hash table.

HashMap(int initialCapacity, float loadFactor)

Constructs an empty HashMap with the specified initial capacity and load factor.

When the number of entries in the hash table exceeds the product of the load factor
and the current capacity will be the measure to increase the size

HashMap(Map<? extends K,? extends V> m)

HashMap internal structure


Constructs a new HashMap with the same mappings as the specified Map.

HashMap is used to store and retrieve key value pairs. Allows null key and null value.
Internally it uses hashtable based on hashing principle to store elements. HashMap
stores internally key value pair as a Map.Entry object. Entry is the sub class of Map.
Each Map.Entry object is considered as a Node.

Node contains following elements

hash - hash value of key

Page 290 of 660


Java Book - Chidambaram.S

key - actual key passed in put()

value - actual value passed in put()

next - points next object - using linked list concept.

Step by step explanations

When put(key,value) is called to store key value pair in HashMap, the int hashCode()
method is called for key.

HashMap stores key values in hash table as like below and the default capacity is 16,
ranges 0 to 15. In the hash table each one storage can be known as bucket.

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

HashMap calulates hash for hash code.

When put(key,value) is called to store key value pair in HashMap, the Map.Entry will
be mapped with Key's hashcode. Hashcode is the unique identifer for each one object
created by runtime.

Here we need to understand that to minmize the storage of lengthy hash code, HashMap
finds the hash. Hash is nothing but it is also the integer and it will be act as the
identity for each node.

Now HashMap puts the node object in hashtable. So it means one bucket will have one
node. Each one node, LinkedList is used to store the elements and each one element is
the Map.Entry object.

In continuous put() call, the same flow is working to store the nodes.

If sometimes hash value is duplicated the same bucket will be used to store the nodes
and the next of node points to the next node.

The get() will be used retrieve the value of key. get(key) returns corresponding
value.

Page 291 of 660


Java Book - Chidambaram.S

get() finds the hash for key and based on the hash value it checks the bucket. If
node's hash and the key's hash are matched then the value will be returned.

In some cases if one bucket has more than one nodes then the equals() will be called
to find out the correct key.

In Java 8, HashMap replaces linked list with a binary tree when the number of elements
in a bucket reaches certain threshold to ensure a performance. Based on this change
the below benfit we will have.

Typically binary tree has the branches left and right side , where hashcode is
used as a branching variable. If there are two different hash in the same
bucket, one is considered bigger and goes to the right of the tree and other
one to the left. Above changes ensure search performance of O(1) instead the
O(log(n)) in worst case scenarios.

Lets see the example program of HashMap

1. import java.util.HashMap;
2. import java.util.Iterator;
3. import java.util.Map;
4.
5. public class HashMapDemo {
6. public static void main(String args[])
7. {
8. HashMap<String,String> hashMap = new HashMap<>();
9. hashMap.put("name","Rama");
10. hashMap.put("age","27");
11. hashMap.put("salary","35000");
12. /*
13. *Way 1 to list the HashMap
14. *hashMap.keySet() -
returns Set interface object (keys of HashMap) the iterator() of Set class retu
rns Iterator object
15. */
16. Iterator<String> iterator=hashMap.keySet().iterator();
17. //iterator.hasNext() - returns true if next element can be read

Page 292 of 660


Java Book - Chidambaram.S

18. while (iterator.hasNext())


19. {
20. //iterator.next() returns object of key and toString() -
we use to convert Object to String
21. String key=iterator.next().toString();
22. //to get the value get() HashMap we used below
23. String value=hashMap.get(key).toString();
24. System.out.println("key="+key+" value="+value);
25. }
26.
27. /*
28. *Way 2 to list the HashMap
29. *hashMap.entrySet() -
returns Map.Entry object Entry is the sub class of Map
30. * Each Entry is the object contains the key value pair
31. */
32. Iterator<Map.Entry<String, String>> iterator1=hashMap.entrySet().i
terator();
33. while (iterator1.hasNext())
34. {
35. //iterator.next() returns Map.Entry object
36. Map.Entry<String, String> entry=(Map.Entry<String,String>)iter
ator1.next();
37. /*
38. * to get the key and value we use the getKey() and
39. * getValue() of Map.Entry
40. */
41. String key=entry.getKey();
42. String value=entry.getValue();
43. System.out.println("key="+key+" value="+value);
44. }
45. }
46. }
47.
48. Output

Page 293 of 660


Java Book - Chidambaram.S

49.
50. key=name value=Rama
51. key=salary value=35000
52. key=age value=27
53. key=name value=Rama
54. key=salary value=35000
55. key=age value=27

TreeMap
TreeMap extends AbstractMap implements NavigableMap

TreeMap provides the result in sorted order in asceding by using keys. We can change
the order using Comparator.

TreeMap( ) - Creates TreeMap without elements

TreeMap(Comparator comp) - Comparator object defines the order of the lelements in


TreeMap

TreeMap(Map m) - creates TreeMap with initial elements Map

TreeMap(SortedMap sm) - creates TreeMap with initial elements SortedMap

1. import java.util.Comparator;
2. import java.util.TreeMap;
3.
4. class CompareDemo implements Comparator
5. {
6. public int compare(Object ob1,Object ob2)
7. {
8. String st1=(String)ob1;
9. String st2=(String)ob2;
10. // For Ascending
11. //return (st1.compareTo(st2));
12. //// For Descending
13. return (st1.compareTo(st2));

Page 294 of 660


Java Book - Chidambaram.S

14. }
15. }
16. class TreeMapDemo
17. {
18. public static void main(String args[])
19. {
20. TreeMap<String,Double> treeMap=new TreeMap<>(new CompareDemo());
21. treeMap.put("Ragav",new Double(1000.00));
22. treeMap.put("Rajesh",new Double(1000.00));
23. treeMap.put("Amir",new Double(1000.00));
24. treeMap.put("Yashota",new Double(1000.00));
25. treeMap.put("Sankar",new Double(1000.00));
26. treeMap.put("Balu",new Double(1000.00));
27. System.out.println(treeMap);
28. }
29. }
30.
31. Output
32.
33. {Amir=1000.0, Balu=1000.0, Ragav=1000.0, Rajesh=1000.0, Sankar=1000.0, Yas
hota=1000.0}

LinkedHashMap

LinkedHashMap extends HashMap implements Map

LinkedHashMap ensures the insertion order retrieval. This implementation differs


from HashMap in that it maintains a doubly-linked list running through all of its
entries. It permits null key and nullvalue.

LinkedHashMap()

Constructs an empty instance with the default initial capacity (16) and load factor
(0.75).

Page 295 of 660


Java Book - Chidambaram.S

LinkedHashMap(int initialCapacity)

Constructs an empty instance with the specified initial capacity and a default load
factor (0.75).

LinkedHashMap(int initialCapacity, float loadFactor)

Constructs an empty insertion-ordered LinkedHashMap instance with the specified


initial capacity and load factor.

LinkedHashMap(Map m)

Constructs instance with the elements of specified map.

1. import java.util.*;
2. class LinkedHashMapDemo
3. {
4. public static void main(String args[])
5. {
6. LinkedHashMap<String,Double> linkedHashMap=new LinkedHashMap<String,Double>();
7. linkedHashMap.put("Ragav",new Double(1000.00));
8. linkedHashMap.put("Rajesh",new Double(1000.00));
9. linkedHashMap.put("Amir",new Double(1000.00));
10. linkedHashMap.put("Yashota",new Double(1000.00));
11. linkedHashMap.put("Sankar",new Double(1000.00));
12. linkedHashMap.put("Balu",new Double(1000.00));
13.
14. Iterator it=linkedHashMap.keySet().iterator();
15. while (it.hasNext())
16. {
17. Object o=it.next();
18. System.out.println(o.toString()+" : "+linkedHashMap.get(o));
19. }
20.
21. }
22. }

Page 296 of 660


Java Book - Chidambaram.S

23.
24.
25. Output :
26.
27. Ragav : 1000.0
28. Rajesh : 1000.0
29. Amir : 1000.0
30. Yashota : 1000.0
31. Sankar : 1000.0
32. Balu : 1000.0

IdentityHashMap

IdentityHashMap extends AbstractMap implements Map

The HashMap equals method checks value comparision between two objects. In
contrary IdentityHashMap checks the reference equality between object not the
values.

IdentityHashMap constructors

IdentityHashMap()

Constructs a new, empty identity hash map with a default expected maximum size (21).

IdentityHashMap(int expectedMaxSize)

Constructs a new, empty map with the specified expected maximum size.

IdentityHashMap(Map m)

Constructs a new identity hash map with the initial values from m.

1. import java.util.IdentityHashMap;
2. class IdentityHashMapDemo
3. {

Page 297 of 660


Java Book - Chidambaram.S

4. public static void main(String args[])


5. {
6. IdentityHashMap identityHashMap1=new IdentityHashMap();
7. identityHashMap1.put("Ragav",new Double(1000.00));
8.
9. IdentityHashMap identityHashMap2=new IdentityHashMap();
10. identityHashMap2.put("Ragav",new Double(1000.00));
11.
12. // If the below statement is commented then the equals method returns fals
e.
13. identityHashMap2=identityHashMap1;
14. System.out.println("hm.equals(hm1)="+identityHashMap2.equals(identityHashM
ap1));
15.
16.
17. }
18. }
19.
20. Output
21.
22. true

SortedMap

SortedMap is the interface it comes with some interesting useful methods such
as below

SortedMap<K,V> headMap(K toKey)

SortedMapMethodsDemo

1. /*
2. SortedMap headMap(Object key)
3. Returns values lessthan (backwards) of key
4. SortedMap tailMap(Object key)
5. Returns values greater than or equal to (backwards) of key

Page 298 of 660


Java Book - Chidambaram.S

6. SortedMap subMap(Object start,Object end)


7. Returns values ranging from start to end -1
8. */
9. import java.util.*;
10. class SortedMapMethodsDemo
11. {
12. public static void main(String args[])
13. {
14. HashMap hm=new HashMap();
15. hm.put("Ragav",new Double(1000.00));
16. hm.put("Rajesh",new Double(2000.00));
17. hm.put("Amir",new Double(3000.00));
18. hm.put("Yashota",new Double(4000.00));
19. hm.put("Sankar",new Double(5000.00));
20. hm.put("Balu",new Double(6000.00));
21. TreeMap tm=new TreeMap(hm);
22. System.out.println("Tree Map");
23. System.out.println(tm);
24. System.out.println("\t tm.firstKey() = " + tm.firstKey());
25. SortedMap sm=tm.headMap("Sankar"); // provides the keys backwards from spe
cified key
26. Iterator it1=sm.keySet().iterator();
27. while (it1.hasNext())
28. {
29. Object key=it1.next();
30. System.out.println(key.toString() +":"+ hm.get(key));
31. }
32. SortedMap sm1=sm.headMap("Ragav");
33. it1=sm1.keySet().iterator();
34. while(it1.hasNext())
35. {
36. System.out.println(it1.next());
37. }
38. System.out.println();
39. SortedMap sm2=sm.tailMap("Ragav");
40. it1=sm2.keySet().iterator();
41. while(it1.hasNext())
42. {
43. System.out.println(it1.next());
44. }
45. System.out.println();
46. SortedMap sm4=sm.subMap("Balu","Rajesh");
47. it1=sm4.keySet().iterator();
48. while(it1.hasNext())
49. {
50. System.out.println(it1.next());
51. }
52. }//main
53. }//class
54.
55. Output
56.

Page 299 of 660


Java Book - Chidambaram.S

57. Tree Map


58. {Amir=3000.0, Balu=6000.0, Ragav=1000.0, Rajesh=2000.0, Sankar=5000.0, Yas
hota=4000.0}
59. tm.firstKey() = Amir
60. Amir:3000.0
61. Balu:6000.0
62. Ragav:1000.0
63. Rajesh:2000.0
64. Amir
65. Balu
66.
67. Ragav
68. Rajesh
69.
70. Balu
71. Ragav

Page 300 of 660


Java Book - Chidambaram.S

Chapter 29 - Legacy classes in collections

Now we will discuss about legacy classes in java.util. We also discussed like that
legacy classes were introduced in initial java release and modern java collection
frame work were introduced in java 1.2. So far we discussed modern java collection
framework.

Let's discuss about the legacy classes in collections.

Following classes are legacy clasess. Hope you remember the below points we discussed
early in below chapters.

Legacy classes are synchronized and thread safe also implements modern collections
framework.

Vector

Stack

Hashtable

Properties

Vector

Vector extends AbstractList implements List

The Vector class is a legacy class available since java 1.0. It is synchronized
class. It maintains internal data array to manage objects and it can grow or
shrink as per added / removed elements in vector. Since java 1.2 Vector
implements List. So we can use the List methods in Vector also.

Vector allows duplicates and null.

Vector() - Creates empty vector and capacity is zero and size is 10

Page 301 of 660


Java Book - Chidambaram.S

Vector(Collection c) - Constructs a vector containing the elements of the


specified collection

Vector(int initialCapacity) - Constructs an empty vector with the specified


initial capacity

Vector(int initialCapacity, int capacityIncrement)

Constructs an empty vector with the specified initial capacity and capacity
increment. Capcity increment defines how much size needs to be resized when its
size reached the capacity

1. import java.util.Vector;
2. public class VectorDemo1 {
3. public static void main(String ar[]) {
4. /*
5. * In below you can see Vector<Object> correct... in <> diamond operator
.
6. * It means we can add any object in Vector
7. */
8. Vector<Object> v = new Vector<>();
9. /*
10. * Vector's default capacity is zero.
11. * To define the capacity at the time of startup
12. */
13. v.ensureCapacity(20);
14. System.out.println(v.capacity());
15. System.out.println(v.isEmpty());
16. System.out.println(v.size());
17. v.addElement("india");
18. v.addElement("welcome");
19. // add(Object obj) - method of List
20. v.add(100);
21. // elementAt(int index) - retrieve the element at given index
22. System.out.println(v.elementAt(1));
23. // contains() - searches given element and returns true if found

Page 302 of 660


Java Book - Chidambaram.S

24. System.out.println(v.contains("welcome"));
25. Object ob[] = new Object[v.size()];
26. // copy the entire content into ob
27. v.copyInto(ob);
28. for (int i = 0; i < ob.length; i++) {
29. System.out.println(ob[i]);
30. }
31. // setSize() -
truncates only keeps given size of the elements and remove remaining items
32. // remaining items
33. v.setSize(2);
34. System.out.println("***************** vector after resizing ******
******** ");
35. System.out.println(v);
36. }
37. }
38.
39. Output
40.
41. 20
42. true
43. 0
44. welcome
45. true
46. india
47. welcome
48. 100
49. ***************** vector after resizing **************
50. [india, welcome]

Stack

The Stack class represents a last-in-first-out (LIFO) stack of objects. It


extends class Vector, so we can use the Vector class methods in Stack.

Page 303 of 660


Java Book - Chidambaram.S

Duplicate and null allowed in Stack

Stack Constructors

Stack() - Creates empty stack object

Stack defines below method in addition with Vector class methods.

boolean empty()

Tests if this stack is empty.

Object peek()

Looks at the object at the top of this stack without removing it from the
stack.

Object pop()

Removes the object at the top of this stack and returns that object as the
value of this function.

Object push(E item)

Pushes an item onto the top of this stack.

Object search(Object o)

Returns the 1-based position where an object is on this stack.

1. import java.util.Stack;
2.
3. class StackDemo
4. {
5. public static void main(String args[])
6. {
7. //Stack object created to add any type of elements
8. Stack<Object> st1=new Stack<>();
9. //push() - push the item on top of the stack

Page 304 of 660


Java Book - Chidambaram.S

10. st1.push("1");
11. st1.push("2");
12. st1.push("3");
13. st1.push("4");
14. st1.push("5");
15. //duplicate allowed in stack
16. st1.push("5");
17. st1.push("java");
18. //search() - returns 1 based position
19. System.out.println("st1.search(\"3\")="+st1.search("3"));
20. //Returns top of the stack without removing
21. System.out.println("Peek:"+(String)st1.peek());
22. //Returns top of the stack with removing
23. System.out.println("Pop:"+(String)st1.pop());
24. //null allowed in stack
25. st1.push(null);
26.
27. /* Vector class method can be used with Stack
28. * insertElementAt(Object,indexPos)
29. */
30. st1.insertElementAt("java 9",3);
31. System.out.println("***** stack after insertion *****");
32. System.out.println(st1);
33.
34. }//main
35. }//class
36.
37. Output
38.
39. st1.search("3")=5
40. Peek:java
41. Pop:java
42. ***** stack after insertion *****
43. [1, 2, 3, java 9, 4, 5, 5, null]
44.

Page 305 of 660


Java Book - Chidambaram.S

Hashtable

Hahtable extends Dictionary implements Map

Hashtable is a legacy class since Java 1.0 and it doesn't allow null key and
null value. Since Java 1.2 it implements Map interface to add the functionality
of new collection frame work.

Hashtable is synchronized. If thread safe is not needed then HashMap would be


good choice.

Constructors

Hashtable()

Constructs a new, empty hashtable with a default initial capacity (11) and load
factor (0.75).

Hashtable(int initialCapacity)

Constructs a new, empty hashtable with the specified initial capacity and
default load factor (0.75).

Hashtable(int initialCapacity, float loadFactor)

Constructs a new, empty hashtable with the specified initial capacity and the
specified load factor.

Hashtable(Map t)

Constructs a new hashtable with the intial elements of given Map.

Lets see the example program for Hashtable

1. import java.util.*;
2. import java.io.*;
3. class HashtableDemo

Page 306 of 660


Java Book - Chidambaram.S

4. {
5. String name;
6. Double salary;
7. String choice;
8. Hashtable ht=new Hashtable();
9. void getValue()
10. {
11. String key;
12. double value=0;
13. try
14. {
15. DataInputStream dis=new DataInputStream(System.in);
16. do
17. {
18. System.out.println("Enter the Name");
19. name=dis.readLine();
20. System.out.println("Enter the Salary");
21. salary=new Double(dis.readLine());
22. ht.put(name,salary);
23. System.out.println("Add More");
24. choice=dis.readLine();
25. }while(choice.equalsIgnoreCase("yes"));
26. Set set=ht.keySet();
27. Iterator it=set.iterator();
28. System.out.println("Key \t\t Value");
29. while (it.hasNext())
30. {
31. key=(String)it.next();
32. System.out.print(key);
33. System.out.println(((Double)ht.get(key)).doubleValue());
34. }
35. Enumeration e=ht.keys();
36. System.out.println("Key \t\t Value");
37. while (e.hasMoreElements())
38. {
39. key=(String)e.nextElement();
40. System.out.print(key);
41. System.out.println(((Double)ht.get(key)).doubleValue());
42. }
43. System.out.println("All values in hash table");
44. System.out.println(ht.toString());
45. double basic=((Double)ht.get("one")).doubleValue();
46. System.out.println("basic of one is="+basic);
47. }//try
48. catch(Exception e){}
49. }//method
50. void removeValue(String name)
51. {
52. System.out.println("Removed Object ="+ht.remove(name));
53. System.out.println("Size of Collection ="+ht.size());
54. }
55. public static void main(String args[])
56. {
57. try
58. {
59. String tname="";
60. String choice;
61. DataInputStream dis=new DataInputStream(System.in);
62. HashtableDemo htd=new HashtableDemo();
63. htd.getValue();
64. do
65. {
66. System.out.println("Enter The Name to Remove");
67. tname=dis.readLine();
68. htd.removeValue(tname);
69. System.out.println("Enter Choice to remove");
70. choice=dis.readLine();
71. }while(choice.equalsIgnoreCase("yes"));
72. }//try
73. catch(Exception e){}
74. }//main
75. }//class
76.
77. Output
78.
79. H:\Util\Hashtable>java HashtableDemo
80. Enter the Name
81. one
82. Enter the Salary
83. 10000
84. Add More
85. yes
86. Enter the Name
87. two
88. Enter the Salary
89. 20000
90. Add More
91. yes
92. Enter the Name

Page 307 of 660


Java Book - Chidambaram.S

93. three
94. Enter the Salary
95. 30000
96. Add More
97. no
98. Key Value
99. two20000.0
100. one10000.0
101. three30000.0
102. Key Value
103. two20000.0
104. one10000.0
105. three30000.0
106. All values in hash table
107. {two=20000.0, one=10000.0, three=30000.
108. basic of one is=10000.0
109. Enter The Name to Remove
110. two
111. Removed Object =20000.0
112. Size of Collection =2
113. Enter Choice to remove
114. yes
115. Enter The Name to Remove
116. one
117. Removed Object =10000.0
118. Size of Collection =1
119. Enter Choice to remove
120. no

Properties

Properties extends Hashtable implements Map

Properties class is legacy class and syncronized and it reperesents properties


as a key value pairs. We can use this class for properties manipulation such as
database properties such as username, password, datasource can be stored and
applied in required place.

Properties class extends Hashtable so we can use Hashtable's put(). But it is


not recommended. Generally Property class object will be used as property map.
So this class itself comes with setProperty(String key, String value) and
getProperty() to manage strings in property.

In addition it supports io stream to get the properties from file and store
properties in file.

Constructors

Properties()

Creates an empty property list with no default values.

Page 308 of 660


Java Book - Chidambaram.S

Properties(Properties defaults)

Creates an empty property list with the specified defaults.

1. import java.io.FileInputStream;
2. import java.io.FileOutputStream;
3. import java.util.*;
4. class PropertyDemo1
5. {
6. public static void main(String args[])
7. {
8. try
9. {
10. Properties p=new Properties();
11. //Add key value in property object
12. p.setProperty("username", "user1");
13. p.setProperty("password", "pass1PASS@9143");
14.
15.
16. System.out.println("p.getProperty(\"username\")="+p.getProperty("username"
));
17.
18. /* To store properties(from object p) in file and
19. * retrieve the same from file and store in property object (to p1 object)

20. */
21. FileOutputStream fos=new FileOutputStream("properties1.txt");
22. p.store(fos,"Company");
23. FileInputStream fis=new FileInputStream("properties1.txt");
24. Properties p1=new Properties();
25. p1.load(fis);
26. System.out.println("*** p1 *****");
27. System.out.println(p1);
28.
29. /*
30. * Store to xml file from properties object and

Page 309 of 660


Java Book - Chidambaram.S

31. * load the propertis from xml file


32. * In storeToXML() , the 1st argument is FileOutputStream object, 2nd argu
ment is title
33. */
34.
35. p.storeToXML(new FileOutputStream("xmlfile.xml"),"Database Properties");
36. Properties p2=new Properties();
37. //loadFromXML() loads properties from xml file to properties object - p2
38. p2.loadFromXML(new FileInputStream("xmlfile.xml"));
39. System.out.println("*** p2 *****");
40. System.out.println(p2);
41.
42. /*
43. * default properties object.
44. * We pass p2 in constructor
45. * It means p2 is the default object for p3.
46. *
47. */
48. Properties p3=new Properties(p2);
49. p3.setProperty("datasource", "oracle");
50. System.out.println("*** p3 *****");
51. //Prints p3 just prints the properties stored in p3
52. System.out.println(p3);
53. //getProperty of p3 also checks p3 and default property object of p2
54. System.out.println("p3.getProperty(\"username\")="+p3.getProperty("usernam
e"));
55. }
56. catch(Exception e)
57. {
58. e.printStackTrace();
59. }
60. }//main
61. }//class
62.
63. Output

Page 310 of 660


Java Book - Chidambaram.S

64.
65. p.getProperty("username")=user1
66. *** p1 *****
67. {password=pass1PASS@9143, username=user1}
68. *** p2 *****
69. {password=pass1PASS@9143, username=user1}
70. *** p3 *****
71. {datasource=oracle}
72. p3.getProperty("username")=user1
73.

Page 311 of 660


Java Book - Chidambaram.S

Chapter 30 - java.util Utility classes

java.util.Date class

java.util.Date object captures current date and current time.

Example

Date date =new Date();

System.out.println(date);

Output

Sat Dec 29 15:29:39 IST 2007

IST-International Standard Time

java.text.SimpleDateFormat class

It is used to format the Date.

How to format the Date?

String format(Date date)-It is a method available from SimpleDateFormat class to


format Date object into our needed format.

Example

SimpleDateFormat sdf=new SimpleDateFormat(“dd-MMM-yy”);

sdf.format(date);

Output

29-DEC-07

SimpleDateFormat example program to format the date

Page 312 of 660


Java Book - Chidambaram.S

1. import java.util.*;
2. import java.text.*;
3. class DateDemo
4. {
5. public static void main(String args[])
6. {
7. Date date=new Date();
8. System.out.println("Un Formatted Date="+date);
9. SimpleDateFormat sdf; // Reference
10. sdf=new SimpleDateFormat("dd/MMMM/yyyy");
11. System.out.println("dd/MMMM/yyyy==>"+sdf.format(date));
12. sdf=new SimpleDateFormat("dd/MMM/yyyy");
13. System.out.println("dd/MMM/yyyy==>"+sdf.format(date));
14. sdf=new SimpleDateFormat("dd/MM/yyyy");
15. System.out.println("dd/MM/yyyy==>"+sdf.format(date));
16. sdf=new SimpleDateFormat("dd/MM/yy");
17. System.out.println("dd/MM/yy==>"+sdf.format(date));
18. sdf=new SimpleDateFormat("d/MM/yy");
19. System.out.println("d/MM/yy==>"+sdf.format(date));
20. sdf=new SimpleDateFormat("d-MM-yy");
21. System.out.println("d-MM-yy==>"+sdf.format(date));
22. sdf=new SimpleDateFormat("hh:mm:ss");
23. System.out.println("hh:mm:ss==>"+sdf.format(date));
24. sdf=new SimpleDateFormat("dd");
25. System.out.println("dd==>"+sdf.format(date));
26. sdf=new SimpleDateFormat("MMMM");
27. System.out.println("MMMM==>"+sdf.format(date));
28. sdf=new SimpleDateFormat("yyyy");
29. System.out.println("yyyy==>"+sdf.format(date));
30. sdf=new SimpleDateFormat("hh");
31. System.out.println("hh==>"+sdf.format(date));
32. sdf=new SimpleDateFormat("mm");
33. System.out.println("mm==>"+sdf.format(date));

Page 313 of 660


Java Book - Chidambaram.S

34. sdf=new SimpleDateFormat("ss");


35. System.out.println("ss=>"+sdf.format(date));
36. }
37. }
38.
39. Output
40.
41. Un Formatted Date=Thu Oct 19 19:00:22 IST 2006
42. dd/MMMM/yyyy==>19/October/2006
43. dd/MMM/yyyy==>19/Oct/2006
44. dd/MM/yyyy==>19/10/2006
45. dd/MM/yy==>19/10/06
46. d/MM/yy==>19/10/06
47. d-MM-yy==>19-10-06
48. hh:mm:ss==>07:00:22
49. dd==>19
50. MMMM==>October
51. yyyy==>2006
52. hh==>07
53. mm==>00
54. ss==>22

Page 314 of 660


Java Book - Chidambaram.S

java.util.Arrays
This class comes with various methods to work with array such as sorting, searching.

1. import java.util.*;
2. class ArraysDemo
3. {
4. public static void main(String args[])
5. {
6. int a[]={1,2,3,4,5,6,7,8,9,10};
7. /*
8. binarySearch() is the static method. First argument is the array and second argu
ment is the element to be searched.
9. Returns index position of second argument.*/
10. System.out.println("Arrays.binarySearch(a,3)="+Arrays.binarySearch(a,3));

11. int b[]={1,2,3,4,5,6,7,8,9,10};


12. //equals() checks each values in a given arrays and return true if both va
lues are equal
13. System.out.println("Arrays.equals(a,b)="+Arrays.equals(a,b));
14. char ch[]={'a','b','c','d'};
15. System.out.println("Before Fill Ch="+new String(ch));
16. //fill() just fills all the element of first argument array with second ar
gument character
17. Arrays.fill(ch,'*');
18. System.out.println("After Fill Ch="+new String(ch));
19. // We can give the range to fill in second and third parameter
20. Arrays.fill(ch,1,2,'?');
21. System.out.println("After Fill Ch="+new String(ch));
22.
23. String str[]={"Java","C","C++","Vb","Servlet","Asp"};
24. System.out.println("=========== Before Sort ======================");
25.
26. for (int i=0;i<str.length;i++)
27. System.out.println(str[i]);

Page 315 of 660


Java Book - Chidambaram.S

28. Arrays.sort(str,1,4);
29. System.out.println("================ After Sort ======================");

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


31. System.out.println(str[i]);
32. }//main
33. }//class
34.
35. Arrays.binarySearch(a,3)=2
36. Arrays.equals(a,b)=true
37. Before Fill Ch=abcd
38. After Fill Ch=****
39. After Fill Ch=*?**
40. =========== Before Sort ======================
41. Java
42. C
43. C++
44. Vb
45. Servlet
46. Asp
47. ================ After Sort ======================
48. Java
49. C
50. C++
51. Vb
52. Servlet
53. Asp
54.

Page 316 of 660


Java Book - Chidambaram.S

Formatter
Formatter class provides format method to format the string as like C language printf.

Let's see with example program and inline comments to understand more better.

1. import java.util.*;
2. class FormatterDemo
3. {
4. public static void main(String args[])
5. {
6. //Formatter object creation
7. Formatter fmt=new Formatter();
8. /*
9. As per the number of format specified in the first argument, the remaining argum
ent should be given.
10. For example In below example
11. %s -> "The Number Integer is"
12. %d -> 10
13. %S -> " and Float is " -
%S is capital S, the output in below S.o.p prints AND FLOAT IS.. correct
14. %f->6.7
15. */
16. fmt.format("%s %d %S %f","The Number Integer is",10," and Float is ",6.7);

17. System.out.println(fmt);
18. //o.p -> The Number Integer is 10 AND FLOAT IS 6.700000
19.
20.
21. /* Dispaly Current Time */
22. Formatter fmt1=new Formatter();
23. fmt1.format("%tr",cal);
24. System.out.println("Time is ="+fmt1);
25. //o.p -> Time is =08:36:26 PM
26.
27.

Page 317 of 660


Java Book - Chidambaram.S

28. /* Display Date and Time */


29. Formatter fmt2=new Formatter();
30. fmt2.format("%tc",cal);
31. System.out.println("Date and Time is ="+fmt2);
32. //o.p -> Date and Time is =Tue Aug 22 20:36:26 IST 2006
33.
34. /* Display Month name and Month number */
35. Formatter fmt3=new Formatter();
36. fmt3.format("%s %tB %n %s %tb %n %s %tm","The Month Name is ",cal,"The Sho
rt Month name is ",cal,"The Month number is ",cal);
37. System.out.println(fmt3);
38. /*
39. o.p.
40.
41. The Month Name is August
42. The Short Month name is Aug
43. The Month number is 08
44. */
45.
46. Formatter fmt4=new Formatter();
47. fmt4.format("|%f|%n|%12f|%n|%012f|",10.12345,10.12345,10.12345);
48. System.out.println(fmt4);
49. /*
50. o.p
51.
52. |10.123450|
53. | 10.123450|
54. |00010.123450|
55. */
56.
57.
58. Formatter fmt5=new Formatter();
59. fmt5.format("%12.4f %n",123.234234234);
60. System.out.println(fmt5);
61. //o.p - > 123.2342

Page 318 of 660


Java Book - Chidambaram.S

62.
63. Formatter fmt6=new Formatter();
64. fmt6.format("%,.2f",1234255234.676575);
65. System.out.println(fmt6);
66. //o.p -> 1,234,255,234.68
67.
68. }
69. }

Formatter with Calendar object.

1. import java.util.*;
2. class FormatterDemo1
3. {
4. public static void main(String args[])
5. {
6. //Calendar object creation.
7. Calendar cal=Calendar.getInstance();
8. Formatter fmt;
9. fmt=new Formatter();
10. fmt.format("%s %ta","Abbreviated WeekDay Name ",cal);
11. System.out.println(fmt);
12. fmt=new Formatter();
13. fmt.format("%s %tA","Full Week Day Name ",cal);
14. System.out.println(fmt);
15. fmt=new Formatter();
16. fmt.format("%s %tb","Abbreviated Month Name ",cal);
17. System.out.println(fmt);
18. fmt=new Formatter();
19. fmt.format("%s %tB","Full Month Name ",cal);
20. System.out.println(fmt);
21. fmt=new Formatter();
22. fmt.format("%s %tc","Date and Time with time zone ",cal);
23. System.out.println(fmt);
24. fmt=new Formatter();

Page 319 of 660


Java Book - Chidambaram.S

25. fmt.format("%s %tC","First Two Digits of Year Name ",cal);


26. System.out.println(fmt);
27. fmt=new Formatter();
28.
29. fmt.format("%s %td","Day of Month ",cal);
30. System.out.println(fmt);
31. fmt=new Formatter();
32.
33. fmt.format("%s %tD","Month/day/Year ",cal);
34. System.out.println(fmt);
35. fmt=new Formatter();
36.
37. fmt.format("%s %te","Day of Month ",cal);
38. System.out.println(fmt);
39. fmt=new Formatter();
40.
41. fmt.format("%s %tF","Year-Month-day",cal);
42. System.out.println(fmt);
43. fmt=new Formatter();
44.
45. fmt.format("%s %th","Abbreviated Month Name",cal);
46. System.out.println(fmt);
47. fmt=new Formatter();
48.
49. fmt.format("%s %tH","Hour in Railway Time",cal);
50. System.out.println(fmt);
51. fmt=new Formatter();
52.
53. fmt.format("%s %tl","Hour in 12 hour format",cal);
54. System.out.println(fmt);
55. fmt=new Formatter();
56.
57. fmt.format("%s %tj","Day of Year",cal);
58. System.out.println(fmt);
59. fmt=new Formatter();

Page 320 of 660


Java Book - Chidambaram.S

60.
61. fmt.format("%s %tk","Hour in Railway Time",cal);
62. System.out.println(fmt);
63. fmt=new Formatter();
64.
65. fmt.format("%s %tL","Millisecond",cal);
66. System.out.println(fmt);
67. fmt=new Formatter();
68.
69. fmt.format("%s %tM","Minute",cal);
70. System.out.println(fmt);
71. fmt=new Formatter();
72.
73. fmt.format("%s %tN","NanoSecond",cal);
74. System.out.println(fmt);
75. fmt=new Formatter();
76.
77. fmt.format("%s %tP","AM or PM",cal);
78. System.out.println(fmt);
79. fmt=new Formatter();
80.
81. fmt.format("%s %tp","am or pm",cal);
82. System.out.println(fmt);
83. fmt=new Formatter();
84.
85. fmt.format("%s %tr","hour:minute 12 hour",cal);
86. System.out.println(fmt);
87. fmt=new Formatter();
88.
89. fmt.format("%s %tR","hour:minute 24 hour format",cal);
90. System.out.println(fmt);
91. fmt=new Formatter();
92.
93. fmt.format("%s %tS","Seconds",cal);
94. System.out.println(fmt);

Page 321 of 660


Java Book - Chidambaram.S

95. fmt=new Formatter();


96.
97. fmt.format("%s %ts","Seconds from 1.1.1970",cal);
98. System.out.println(fmt);
99. fmt=new Formatter();
100.
101. fmt.format("%s %tT","hh:mm:ss 24 hour format",cal);
102. System.out.println(fmt);
103. fmt=new Formatter();
104.
105. fmt.format("%s %ty","Last two digit of year",cal);
106. System.out.println(fmt);
107. fmt=new Formatter();
108.
109. fmt.format("%s %tY","Four digit of year",cal);
110. System.out.println(fmt);
111. fmt=new Formatter();
112.
113. fmt.format("%s %tZ","Time Zone Name",cal);
114. System.out.println(fmt);
115. }
116. }
117.
118. Output
119.
120. Abbreviated WeekDay Name Tue
121. Full Week Day Name Tuesday
122. Abbreviated Month Name Aug
123. Full Month Name August
124. Date and Time with time zone Tue Aug 22 20:41:13 IST 2006
125. First Two Digits of Year Name 20
126. Day of Month 22
127. Month/day/Year 08/22/06
128. Day of Month 22
129. Year-Month-day 2006-08-22

Page 322 of 660


Java Book - Chidambaram.S

130. Abbreviated Month Name Aug


131. Hour in Railway Time 20
132. Hour in 12 hour format 8
133. Day of Year 234
134. Hour in Railway Time 20
135. Millisecond 750
136. Minute 41
137. NanoSecond 750000000
138. AM or PM PM
139. am or pm pm
140. hour:minute 12 hour 08:41:13 PM
141. hour:minute 24 hour format 20:41
142. Seconds 13
143. Seconds from 1.1.1970 1156259473
144. hh:mm:ss 24 hour format 20:41:13
145. Last two digit of year 06
146. Four digit of year 2006
147. Time Zone Name IST

Page 323 of 660


Java Book - Chidambaram.S

Observer and Observable

Observer

Observable object can be notified by using Observer object.

Here Observable is the class, Observer is the interface.

Observer is the interface and it has update() method, void update(Observable o,


Object arg); the sub class of Observer must implement update method and this
update method will be called when ever Observable object is changed

Observable

Observable is the class, and to notify the state changes of observable object we can
use this concept.

In below example, A is the sub class of Observable

class A extends Observable

String readFile(String filename,int start,int end)

/*

if we want to notify Observer, when we call readFile() method, we must register


Observer using below two methods.

*/

setChanged();

notfiyObservers(Object ob);

Page 324 of 660


Java Book - Chidambaram.S

class B implements Observer

public void update(Observable ob,Object o)

// add the code. The code will be invoked by run time when you call readFile().

To do this you must register Observable and Observer.

Observable.addObserver(Observer);

One or more observers can be notified by one Observable.

Let's see the example.

Watcher is user defined class and it will act as Observer, because it implements
Observer interface and overrides update().

In main(), student.addObserver(watcher) means.. see the below note

Student is the sub class of Observable

We register Observer for Observable using the addObserver().. hope you got the point.

student.print() invokes print(). In print() we added below two lines to invoke the
observer

setChanged();

notifyObservers(new Integer(count));

and pass the count variable to update().. that's it.

1. import java.util.Observable;
2. import java.util.Observer;

Page 325 of 660


Java Book - Chidambaram.S

3.
4. class Watcher implements Observer
5. {
6. /*
7. * update() will be called whenever print() Student class is invoked
8. * parameter ob would be the Student object and we can cast
9. * ex: Student student = (Student)ob;
10. * paramter o would be the value we passed in notifyObservers()
11. */
12. public void update(Observable ob,Object o)
13. {
14. System.out.println("I am Update:"+(((Integer)o).intValue()));
15. }
16. }
17.
18. class ObserverDemo
19. {
20. public static void main(String args[])
21. {
22. //Observer
23. Watcher watcher=new Watcher();
24. //Observable
25. Student student=new Student();
26. //observer and observable registration using addObserver()
27. student.addObserver(watcher);
28. //print() invoked, which automatically triggers update() of observer.
29. student.print();
30. }
31. }
32.
33.
34. class Student extends Observable
35. {
36. int count=10;
37. void print()

Page 326 of 660


Java Book - Chidambaram.S

38. {
39. /*
40. * Below two method setChanged() and
41. * notifyObservers() must be called to trigger observer whenever obser
vable is invoked
42. * count will be parameter to update() of observer
43. */
44. setChanged();
45. notifyObservers(new Integer(count));
46. System.out.println("I am Student Class");
47. count++;
48. }
49. }
50.
51. Output :
52.
53. I am Update:10
54. I am Student Class

Random
Random is the java.util package class to generate the random numbers. The below
example program creates Random class object and prints random number using Random
class methods.

We can also use Math.random() to generate random number.

Let's see the below sample program, which prints random number within for loop to
understand Random object generates different output for each call.

1. import java.util.Random;
2.
3. class RandomDemo extends Random
4. {

Page 327 of 660


Java Book - Chidambaram.S

5.
6. public static void main(String args[])
7. {
8. Random r1=new Random();
9. //nextInt() returns any one integer number.
10. System.out.println("***** r1.nextInt() *****");
11. for (int i=0;i<3;i++)
12. System.out.println(r1.nextInt());
13.
14. //nextInt() returns any one integer number within 100
15. System.out.println(" ***** r1.nextInt(100) *****");
16. for (int i=0;i<3;i++)
17. System.out.println(r1.nextInt(100));
18.
19. //nextDouble() returns any one Double number within double range
20. System.out.println("**** r1.nextDouble() *****");
21. for (int i=0;i<3;i++)
22. System.out.println(r1.nextDouble());
23.
24. //nextBoolean() returns any one boolean value
25. System.out.println("***** r1.nextBoolean() *****");
26. for (int i=0;i<3;i++)
27. System.out.println(r1.nextBoolean());
28.
29. //nextBytes() fills byte[] with any of the byte range
30. System.out.println("***** r1.nextBytes(byte[]) *****");
31. byte b[]=new byte[20];
32. r1.nextBytes(b);
33. for (int i=0;i<3;i++)
34. System.out.println(b[i]);
35.
36. }
37. }
38.
39. Output

Page 328 of 660


Java Book - Chidambaram.S

40.
41.
42. ***** r1.nextInt() *****
43. 1500743010
44. 1048473621
45. 1863031333
46. ***** r1.nextInt(100) *****
47. 66
48. 59
49. 92
50. **** r1.nextDouble() *****
51. 0.30520999537245574
52. 0.2494990569479918
53. 0.9582452668807597
54. ***** r1.nextBoolean() *****
55. true
56. false
57. true
58. ***** r1.nextBytes(byte[]) *****
59. 1
60. -26
61. -17
62.

Scanner

Scanner parses from the given source using delimiters. It breaks its input into
tokens using a delimiters, default delimiter is whitespace.

Constructor

Scanner(java.io.File source)

By using this constructor we can create Scanner object with connecting one
file.

Page 329 of 660


Java Book - Chidambaram.S

It means reading from scanner really reads data from file.

It means we can read the file using scanner techniques.

Example:

File f=new File(“x.txt”);

Scanner s=new Scanner(f);

Scanner(java.io.InputStream source)

Here the source of scanner is InputStream object.

Example #1

FileInputStream fis=new FileInputStream(“file1.txt”);

Scanner s=new Scanner(fis);

Example #2

ByteArrayInputStream bais=new ByteArrayInputStream(b);

Scanner s1=new Scanner(bais);

Example #3

In below example, System.in refers console input

Scanner s2=new Scanner(System.in);

Scanner(java.lang.Readable source)

Readable is the interface, so we can give the sub class of Readbale for exampole
FileReader

CharArrayReader

Scanner(java.lang.String source)

Here string is the source of Scanner. It means reading from scanner really reads from
any String source.

Page 330 of 660


Java Book - Chidambaram.S

Methods

boolean hasNext()

This method reads next token from source(tokens are identified by using space or
enter) and returns true if next token is available.

boolean hasNextXxx()

To check the data type of token. Here Xxx is the data type like int, float, etc..

xxx nextXxx()

To get token from scanner

String next()

To get token already read by scanner as string.

1. import java.io.FileReader;
2. import java.util.Scanner;
3.
4. /* Parse one file into token with its data type */
5.
6. class FileReaderDemo
7. {
8. public static void main(String args[])
9. {
10. try
11. {
12. FileReader fr=new FileReader("file.txt");
13. Scanner in=new Scanner(fr);
14. in.useDelimiter("-"); // default delimiter is space
15. while (in.hasNext()) // If token found returns true
16. {
17. if (in.hasNextInt())
18. {
19. System.out.println("Integer :"+in.nextInt());
20. }

Page 331 of 660


Java Book - Chidambaram.S

21. else if (in.hasNextDouble())


22. {
23. System.out.println("Double :"+in.nextDouble());
24. }
25. else if (in.hasNextBoolean())
26. {
27. System.out.println("Boolean :"+in.nextBoolean());
28. }
29. else
30. {
31. String str=in.next();
32. System.out.println("String str="+str);
33. }
34. }
35. }
36. catch(Exception e)
37. {
38. e.printStackTrace();
39. }
40. }
41. }
42.
43. Output
44.
45. Integer :12
46. Boolean :true
47. Integer :23
48. Double :35.5
49. Boolean :false
50. Double :56.78
51. String str=done
52. String str=afterdone
53. Integer :12
54. String str=a
55.

Page 332 of 660


Java Book - Chidambaram.S

56. file.txt
57.
58. 12-true-23-35.5-false-56.78-done-afterdone-12-a

StringTokenizer

public class StringTokenizer extends Object implements Enumeration

The string tokenizer class is used to break a string into tokens using
delimiters.

StringTokenizer constructors

Constructor and Description

StringTokenizer(String str)

Constructs a string tokenizer for the specified string.

StringTokenizer(String str, String delim)

Constructs a string tokenizer for the specified string and delimiter

StringTokenizer(String str, String delim, boolean returnDelims)

Constructs a string tokenizer for the specified string and delimiter. If


returnDelims is true then delim also will be returned as token else delim will
not be treated as token

A StringTokenizer object internally maintains a current position within the


string to be tokenized. Some operations advance this current position past the
characters processed.

A token is returned by taking a substring of the string that was used to create
the StringTokenizer object.

Page 333 of 660


Java Book - Chidambaram.S

The following is one example of the use of the tokenizer. The code:

StringTokenizer st = new StringTokenizer("this is a test");

while (st.hasMoreTokens()) {

System.out.println(st.nextToken());

prints the following output:

this

is

test

StringTokenizer is a legacy class that is retained for compatibility reasons


although its use is discouraged in new code. It is recommended that anyone
seeking this functionality use the split method of String or the
java.util.regex package instead.

The following example illustrates how the String.split method can be used to
break up a string into its basic tokens:

String[] result = "this is a test".split("\\s");

for (int x=0; x<result.length; x++)

System.out.println(result[x]);

prints the following output:

this

Page 334 of 660


Java Book - Chidambaram.S

is

test

Example using colon : delimiter

1. import java.util.StringTokenizer;
2.
3. class StringTokenizerDemo
4. {
5. public static void main(String args[])
6. {
7. String str="Name:Rama:Age:60:Salary:7500";
8. StringTokenizer st=new StringTokenizer(str,":");
9. System.out.println("No of Tokens in str="+st.countTokens());
10. while (st.hasMoreElements())
11. {
12. System.out.println(st.nextElement());
13. }
14. }
15. }
16.
17.
18. Output
19.
20. No of Tokens in str=6
21. Name
22. Rama
23. Age
24. 60
25. Salary
26. 7500

Page 335 of 660


Java Book - Chidambaram.S

Example using colon : and semicolon delimiters ;

1. import java.util.StringTokenizer;
2.
3. class StringTokenizerDemo1
4. {
5. public static void main(String args[])
6. {
7. String str="Name:Rama:seetha;Age:60:70;Salary:7500:354656";
8. StringTokenizer st=new StringTokenizer(str,";");
9. System.out.println(st.toString());
10. System.out.println("No of Tokens in str="+st.countTokens());
11. while (st.hasMoreTokens())
12. {
13. String inner=st.nextToken();
14. StringTokenizer st1=new StringTokenizer(inner,":");
15. System.out.print(st1.nextToken()+" ");
16. System.out.println(st1.nextToken());
17. System.out.println(st1.nextToken());
18. }
19. }
20. }

Example - to return delim as the token

1. import java.util.StringTokenizer;
2. class StringTokenizerDemo2
3. {
4. public static void main(String args[])

Page 336 of 660


Java Book - Chidambaram.S

5. {
6. String str="Hello Java Guys - Welcome";
7. /*
8. The below constructor has thre arguments
9. str -> source string
10. - -> delimiter
11. true -> true delim returns as the token. default is false.
12. StringTokenizer st=new StringTokenizer(str,"-",true);
13. while(st.hasMoreTokens())
14. System.out.println(st.nextToken());
15. }//method
16. }//class
17.
18. Output
19.
20. Hello Java Guys
21. -
22. Welcome

Page 337 of 660


Java Book - Chidambaram.S

Chapter 31- java.lang Package

The package is used to accomplish the fundamental needs of the Java programming
language.

java.lang.Object is the implicit super class for all the java classes

The wrapper classes Boolean, Character, Integer, Long, Float, and Double serve
the functionality for data of our application.

java.lang Math provides commonly used mathematical functions such as sine,


cosine, and square root.

String, StringBuffer, and StringBuilder provide commonly used operations on


strings.

ClassLoader, Process, ProcessBuilder, Runtime, SecurityManager,


and System provide "system operations" that manage the dynamic loading of
classes, creation of external processes.

Throwable is the super class of Exception and Error and these are useful to
manipulate exception handling mechanisms.

java.lang is the default package. It means we need not to import this package in our
program to use the classes of this package.

java.lang.Number

Number is the super class of Integer, Float,Double,Byte,Short wrapper classes.

Below program illustrates Number class methods, which just returns the requried
data type primitive value.

1. class MethodsOfNumberClass
2. {
3. public static void main(String args[])

Page 338 of 660


Java Book - Chidambaram.S

4. {
5. System.out.println("Integer");
6. Integer i=new Integer(200);
7. System.out.println("int "+i.intValue());
8. System.out.println("float "+i.floatValue());
9. System.out.println("byte "+i.byteValue());
10. System.out.println("long "+i.longValue());
11. System.out.println("double "+i.doubleValue());
12. System.out.println("short "+i.shortValue());
13. System.out.println("-------------------------------");
14. System.out.println("Long");
15. Long l=new Long(4566);
16. System.out.println("int "+l.intValue());
17. System.out.println("float "+l.floatValue());
18. System.out.println("byte "+l.byteValue());
19. System.out.println("long "+l.longValue());
20. System.out.println("double "+l.doubleValue());
21. System.out.println("short "+l.shortValue());
22. System.out.println("-------------------------------");
23. System.out.println("Byte");
24. Byte b=new Byte((byte)67);
25. System.out.println("int "+b.intValue());
26. System.out.println("float "+b.floatValue());
27. System.out.println("byte "+b.byteValue());
28. System.out.println("long "+b.longValue());
29. System.out.println("double "+b.doubleValue());
30. System.out.println("short "+b.shortValue());
31. System.out.println("-------------------------------");
32. System.out.println("Short");
33. Short s=new Short((short)457);
34. System.out.println("int "+s.intValue());
35. System.out.println("float "+s.floatValue());
36. System.out.println("byte "+s.byteValue());
37. System.out.println("long "+s.longValue());
38. System.out.println("double "+s.doubleValue());

Page 339 of 660


Java Book - Chidambaram.S

39. System.out.println("short “+s.shortValue());


40. System.out.println("-------------------------------");
41. System.out.println("Float");
42. Float f=new Float(23.65);
43. System.out.println("int "+f.intValue());
44. System.out.println("float "+f.floatValue());
45. System.out.println("byte "+f.byteValue());
46. System.out.println("long "+f.longValue());
47. System.out.println("double "+f.doubleValue());
48. System.out.println("short “+f.shortValue());
49. System.out.println("-------------------------------");
50. System.out.println("Double");
51. Double d=new Double(565.787);
52. System.out.println("int "+d.intValue());
53. System.out.println("float "+d.floatValue());
54. System.out.println("byte "+d.byteValue());
55. System.out.println("long "+d.longValue());
56. System.out.println("double "+d.doubleValue());
57. System.out.println("short "+d.shortValue());
58. System.out.println("-------------------------------");
59. }
60. }
61.
62. Output
63.
64. Integer
65. int 200
66. float 200.0
67. byte -56
68. long 200
69. double 200.0
70. short 200
71. -----------------
72. Long
73. int 4566

Page 340 of 660


Java Book - Chidambaram.S

74. float 4566.0


75. byte -42
76. long 4566
77. double 4566.0
78. short 4566
79. -----------------
80. Byte
81. int 67
82. float 67.0
83. byte 67
84. long 67
85. double 67.0
86. short 67
87. -----------------
88. Short
89. int 457
90. float 457.0
91. byte -55
92. long 457
93. double 457.0
94. short 457
95. -----------------
96. Float
97. int 23
98. float 23.65
99. byte 23
100. long 23
101. double 23.649999618530273
102. short 23
103. -------------------
104. Double
105. int 565
106. float 565.787
107. byte 53
108. long 565

Page 341 of 660


Java Book - Chidambaram.S

109. double 565.787


110. short 565

Double class

Double Constructors

Double(double)

Double(String str) throws NumberFormatException

1. class DoubleConstructorsDemo
2. {
3. public static void main(String args[])
4. {
5. Double d1=new Double(6);
6. Double d2=new Double("6.4");
7. System.out.println("d1="+d1);
8. System.out.println("d2="+d2);
9. }
10. }
11.
12. Output
13.
14. d1=6.0
15. d2=6.4

Illustrates Double class Fields

1. class DoubleFieldsDemo
2. {
3. public static void main(String args[])
4. {

Page 342 of 660


Java Book - Chidambaram.S

5. System.out.println("Double.MAX_VALUE="+Double.MAX_VALUE);
6. System.out.println("Double.MIN_VALUE="+Double.MIN_VALUE);
7. System.out.println("Double.SIZE="+Double.SIZE);
8. System.out.println("Double.TYPE="+Double.TYPE);
9. System.out.println("Double.POSITIVE_INFINITY="+Double.POSITIVE_INFINITY);
10. System.out.println("Double.NEGATIVE_INFINITY="+Double.NEGATIVE_INFINITY);

11. System.out.println("Double.NaN="+Double.NaN);
12. Double f=new Double(5.0f/0.0f);
13. System.out.println(f);
14. Double f1=new Double(-5.0f/0.0f);
15. System.out.println(f1);
16. }
17. }
18.
19. Output
20.
21. Double.MAX_VALUE=1.7976931348623157E308
22. Double.MIN_VALUE=4.9E-324
23. Double.SIZE=64
24. Double.TYPE=double
25. Double.POSITIVE_INFINITY=Infinity
26. Double.NEGATIVE_INFINITY=-Infinity
27. Infinity
28. -Infinity

isInfinite() and isNaN() methods

public boolean isInfinite()-Returns true if this Float value is infinitely large in


magnitude, false otherwise.

public boolean isNaN() - Returns true if this Float value is a Not-a-Number


(NaN), false otherwise.

1. class FloatIsInfiniteDemo
2. {

Page 343 of 660


Java Book - Chidambaram.S

3. public static void main(String args[])


4. {
5. Float f1=new Float(5.2f/0); // true
6. Float f2=new Float(5.2f/2f); //false
7. Float f3=new Float(0.0/0.0);//false isNaN()=true
8. Float f4=new Float(-0.0); // isNaN()=false
9. System.out.println(f1.isInfinite());
10. System.out.println(f2.isInfinite());
11. System.out.println(f3.isInfinite());
12. System.out.println(f3.isNaN());
13. System.out.println(f4.isNaN());
14. }
15. }
16.
17. Output
18.
19. true
20. false
21. false
22. true
23. false

toBinaryString(), toHexString() and toOctalString()

static String toBinaryString(int i) -> Returns Binary String

static String toHexString(int i)-> Returns Hexa decimal value

static String toOctalString(int i) -> Returns Octal value.

1. class IntegerHexBinOct
2. {
3. public static void main(String args[])
4. {
5. System.out.println("Binary of 25 is ="+Integer.toBinaryString(25));

Page 344 of 660


Java Book - Chidambaram.S

6. System.out.println("Hexa Deciaml of 25 is ="+Integer.toHexString(25));


7. System.out.println("Octal value of 25 is ="+Integer.toOctalString(25));
8. }
9. }
10.
11. Output
12.
13. Binary of 25 is =11001
14. Hexa Deciaml of 25 is =19
15. Octal value of 25 is =31

static String toBinaryString(long num)

static String toOctalString(long num)

static String toHexString(long num)

1. import java.io.*;
2. class LongMethodsDemo
3. {
4. public static void main(String args[])
5. {
6. System.out.println(Long.toBinaryString(100));
7. System.out.println(Long.toOctalString(100));
8. System.out.println(Long.toHexString(100));
9. }
10. }
11.
12. Output
13.
14. 1100100
15. 144
16. 64

Page 345 of 660


Java Book - Chidambaram.S

Below program illustrates the constructors of Byte class.

Byte(byte b)

Byte(String s)

1. class ByteConstructors
2. {
3. public static void main(String args[])
4. {
5. Byte b1=new Byte((byte)100);
6. Byte b2=new Byte("100");
7. System.out.println("b1="+b1);
8. System.out.println("b2="+b2);
9. }
10. }
11.
12. Output
13.
14. b1=100
15. b2=100

Below program illustrates the MAX_VALUE,MIN_VALUE,TYPE and SIZE


fields of Byte class.

1. class ByteFields
2. {
3. public static void main(String args[])
4. {
5. System.out.println("Max="+Byte.MAX_VALUE);
6. System.out.println("Min="+Byte.MIN_VALUE);
7. System.out.println("Type="+Byte.TYPE);
8. System.out.println("Size="+Byte.SIZE); // returns size in bits
9. }

Page 346 of 660


Java Book - Chidambaram.S

10. }
11.
12. Output
13.
14. Max=127
15. Min=-128
16. Type=byte
17. Size=8

Below program illustrates about wrapper type to primitive type

This program aims to get the user input and convert to primitive using AutoBox
and Autounbox. This is the mechanism introduced in java 5. The wrapper object
type values can be stored to primitive wrapper type and vice versa. Prior in
java 5, it will throw exception

1. import java.io.DataInputStream;
2. public class ObjectToPrimitiveWithAutoBox
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. DataInputStream dis=new DataInputStream(System.in);
9. System.out.println("Enter Integer");
10. int num1=new Integer(dis.readLine());
11. System.out.println("Enter float");
12. float num2=new Float(dis.readLine());
13. System.out.println("Enter Double");
14. double num3=new Double(dis.readLine());
15. System.out.println("Enter byte value");
16. byte num4=new Byte(dis.readLine());
17. System.out.println("Enter long value");
18. long num5=new Long(dis.readLine());
19. System.out.println("Enter Short value");

Page 347 of 660


Java Book - Chidambaram.S

20. short num6=new Short(dis.readLine());


21. System.out.println("Enter boolean value");
22. boolean num7=new Boolean(dis.readLine());
23. System.out.println("integer ="+num1);
24. System.out.println("float ="+num2);
25. System.out.println("double ="+num3);
26. System.out.println("byte ="+num4);
27. System.out.println("long ="+num5);
28. System.out.println("short ="+num6);
29. //System.out.println("boolean ="+num7);
30. }
31. catch(Exception e){
32. e.printStackTrace();
33. }
34. }
35. }
36.
37. Output
38.
39. Enter Integer
40. 50
41. Enter float
42. 45.34
43. Enter Double
44. 34.67
45. Enter byte value
46. 45
47. Enter long value
48. 12344563
49. Enter Short value
50. 23435
51. Enter boolean value
52. false
53. integer =50
54. float =45.34

Page 348 of 660


Java Book - Chidambaram.S

55. double =34.67


56. byte =45
57. long =12344563
58. short =23435
59. boolean =false

ConvertObjectToPrimitiveDifferentType

1. import java.io.*;
2. class ConvertObjectToPrimitiveDifferentType
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. DataInputStream dis=new DataInputStream(System.in);
9. System.out.println("Enter Double to Integer");
10. int num1=new Double(dis.readLine()).intValue();
11. System.out.println("Enter Float to double");
12. double num2=new Float(dis.readLine()).doubleValue();
13. System.out.println("integer num1 ="+num1);
14. System.out.println("double num2 ="+num2);
15. }
16. catch(Exception e){}
17. }
18. }
19.
20. Output
21.
22. Enter Double to Integer
23. 23.43
24. Enter Float to double
25. 54.67
26. integer num1 =23
27. double num2 =54.66999816894531

Page 349 of 660


Java Book - Chidambaram.S

Max and min values of number types

1. class MaxAndMinValues
2. {
3. public static void main(String args[])
4. {
5. System.out.println("Integer.MAX_VALUE="+Integer.MAX_VALUE);
6. System.out.println("Integer.MIN_VALUE="+Integer.MIN_VALUE);
7.
8. System.out.println("Long.MAX_VALUE="+Long.MAX_VALUE);
9. System.out.println("Long.MIN_VALUE="+Long.MIN_VALUE);
10.
11. System.out.println("Double.MAX_VALUE="+Double.MAX_VALUE);
12. System.out.println("Double.MIN_VALUE="+Double.MIN_VALUE);
13.
14. System.out.println("Float.MAX_VALUE="+Float.MAX_VALUE);
15. System.out.println("Float.MIN_VALUE="+Float.MIN_VALUE);
16.
17. System.out.println("Byte.MAX_VALUE="+Byte.MAX_VALUE);
18. System.out.println("Byte.MIN_VALUE="+Byte.MIN_VALUE);
19. System.out.println("Short.MAX_VALUE="+Short.MAX_VALUE);
20. System.out.println("Short.MIN_VALUE="+Short.MIN_VALUE);
21. }
22. }
23.
24. Output
25.
26. Integer.MAX_VALUE=2147483647
27. Integer.MIN_VALUE=-2147483648
28. Long.MAX_VALUE=9223372036854775807
29. Long.MIN_VALUE=-9223372036854775808
30. Double.MAX_VALUE=1.7976931348623157E308
31. Double.MIN_VALUE=4.9E-324
32. Float.MAX_VALUE=3.4028235E38
33. Float.MIN_VALUE=1.4E-45

Page 350 of 660


Java Book - Chidambaram.S

34. Byte.MAX_VALUE=127
35. Byte.MIN_VALUE=-128
36. Short.MAX_VALUE=32767
37. Short.MIN_VALUE=-32768

Boolean class

Below program illustrates the method public int compareTo(Boolean b) using


Boolean class.

Boolean is the wrapper class.

1. class BooleanCompareToDemo
2. {
3. public static void main(String args[])
4. {
5. Boolean b1=new Boolean("true");
6. Boolean b2=new Boolean(false);
7. Boolean b3=new Boolean(true);
8. System.out.println("b1.compareTo(b2)="+b1.compareTo(b2));
9. System.out.println("b1.compareTo(b3)="+b1.compareTo(b3));
10. System.out.println("b2.compareTo(b3)="+b2.compareTo(b3));
11. }
12. }
13.
14. Output
15.
16. b1.compareTo(b2)=1
17. b1.compareTo(b2)=1 // true and false comparision returns positive integer

18. b1.compareTo(b3)=0 // both are equal so returns zero


19. b2.compareTo(b3)=-1 // false and true comparision returns negative value

Page 351 of 660


Java Book - Chidambaram.S

Below program illustrates the Boolean class constructors.

Boolean(String)

Boolean(boolean)

1. class BooleanConstructor
2. {
3. public static void main(String args[])
4. {
5. Boolean b1=new Boolean("true");
6. Boolean b2=new Boolean(false);
7. Boolean b3=new Boolean(true);
8. System.out.println("b1="+b1);
9. System.out.println("b2="+b2);
10. System.out.println("b3="+b3);
11. }
12. }
13.
14. Output
15.
16. b1=true
17. b2=false
18. b3=true

Below program illustrates the method public boolean equals(Object


obj)

1. class BooleanEqualsDemo
2. {
3. public static void main(String args[])
4. {
5. Boolean b1=new Boolean("true");
6. Boolean b2=new Boolean(false);

Page 352 of 660


Java Book - Chidambaram.S

7. Boolean b3=new Boolean(true);


8. System.out.println("b1.equlas(b2)="+b1.equals(b2));
9. System.out.println("b3.equlas(b2)="+b3.equals(b2));
10. }
11. }
12.
13. Output
14.
15. b1.equlas(b2)=false
16. b3.equlas(b2)=false

Below program illustrates public static boolean parseBoolean(String


name) This method parses string value to boolean

1. class BooleanParseBooleanDemo
2. {
3. public static void main(String args[])
4. {
5. Boolean b1=new Boolean("true");
6. Boolean b2=new Boolean(false);
7. Boolean b3=new Boolean(true);
8. String b4="false";
9. boolean bool1=Boolean.parseBoolean(b4);
10. System.out.println("bool1="+bool1);
11. }
12. }
13.
14. Output
15.
16. bool1=false

Character class

Page 353 of 660


Java Book - Chidambaram.S

Below program illustrates public char charValue() - convert


object to char value

1. class CharacterCharValueDemo
2. {
3. public static void main(String args[])
4. {
5. Character c1=new Character('A');
6. Character c2=new Character('Z');
7. char char1=c1.charValue();
8. System.out.println("c1.charValue()="+char1);
9. }
10. }
11.
12. Output
13.
14. c1.charValue()=A

Below program illustrates the public int compareTo(Character


anotherCharacter)- returns ascii difference.

1. class CharacterCompareToDemo
2. {
3. public static void main(String args[])
4. {
5. Character c1=new Character('A');
6. Character c2=new Character('Z');
7. System.out.println("c1.compareTo('D')="+c1.compareTo('D'));
8. System.out.println("c1.compareTo('a')="+c1.compareTo('a'));
9. System.out.println("c1.compareTo('I')="+c1.compareTo('I'));
10. }
11. }
12.

Page 354 of 660


Java Book - Chidambaram.S

13. Output
14.
15. c1.compareTo('D')=-3
16. c1.compareTo('a')=-32
17. c1.compareTo('I')=-8

Below program illustrates Character constructor

Character(char value)

1. class CharacterConstructorDemo
2. {
3. public static void main(String args[])
4. {
5. Character c1=new Character('A');
6. Character c2=new Character('Z');
7. System.out.println(c1);
8. System.out.println(c2);
9. }
10. }
11.
12. Output
13.
14. A
15. Z

public boolean equals(Object obj)- returns true if both are same.

1. class CharacterEqualsDemo
2.
3. {
4. public static void main(String args[])

Page 355 of 660


Java Book - Chidambaram.S

5. {
6. Character c1=new Character('A');
7. Character c2=new Character('Z');
8. System.out.println("c1.equals(c2)="+c1.equals(c2));
9. }
10. }
11.
12. Output
13.
14. c1.equals(c2)=false

Below program illustrates Character class methods

1. public static boolean isLowerCase(char ch)


2. public static boolean isUpperCase(char ch)
3. public static boolean isSpaceChar(char ch)
4. public static boolean isWhitespace(char ch)
5. public static boolean isLetter(char ch)
6. public static boolean isLetterOrDigit(char ch)
7. class CharacterIsLowerCaseDemo
8. {
9. public static void main(String args[])
10. {
11. Character c1=new Character('A');
12. Character c2=new Character('Z');
13. System.out.println("Character.isLowerCase('A')=
14. "Character.isLowerCase('A'));
15. System.out.println("Character.isUpperCase('A')="+Character.isUpperCase('A'
));
16. System.out.println("Character.isSpaceChar(' ')="+Character.isSpaceChar(' '
));
17. System.out.println("Character.isSpaceChar('y')="+Character.isSpaceChar('y'
));
18. System.out.println("Character.isWhitespace(\\n)="+Character.isWhitespace('
\n'));

Page 356 of 660


Java Book - Chidambaram.S

19. System.out.println("Character.isWhitespace(' ')="+Character.isWhitespace('


'));
20. System.out.println("Character.isWhitespace(\\t)="+Character.isWhitespace('
\t'));
21. System.out.println("Character.isWhitespace(\\t)="+Character.isWhitespace('
\t'));
22. System.out.println("Character.isWhitespace(B)="+Character.isWhitespace('B'
));
23. System.out.println("Character.isLetter(B)="+Character.isLetter('B'));
24. System.out.println("Character.isLetterOrDigit(B)="+Character.isLetterOrDig
it('B'));
25. System.out.println("Character.isLetterOrDigit(1)="+Character.isLetterOrDig
it('1'));
26. }
27. }
28.
29. Output
30.
31. Character.isLowerCase('A')=false
32. Character.isUpperCase('A')=true
33. Character.isSpaceChar(' ')=true
34. Character.isSpaceChar('y')=false
35. Character.isWhitespace(\n)=true
36. Character.isWhitespace(' ')=true
37. Character.isWhitespace(\t)=true
38. Character.isWhitespace(\t)=true
39. Character.isWhitespace(B)=false
40. Character.isLetter(B)=true
41. Character.isLetterOrDigit(B)=true
42. Character.isLetterOrDigit(1)=true

To print the ascii character value

1. class PrintAscii

Page 357 of 660


Java Book - Chidambaram.S

2. {
3. public static void main(String args[])
4. {
5. for(int i=0;i<=255;i++)
6. System.out.println(i+"="+(char)i);
7. }
8. }
9.
10. Output
11.
12. Here we can see all ascii characters and its values.

java.lang.System class

System.getProperties()

Properties is a class, it is in java.util package to retrieve all


about system details

1. import java.util.*;
2. class SystemProperties
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. Properties p=System.getProperties();
9. // Enumeration is an interface to retrieve the key stored in Collection(class) *
/
10. Enumeration e=p.propertyNames();
11. while (e.hasMoreElements())
12. {
13. String key=e.nextElement().toString();
14. String value=System.getProperty(key);

Page 358 of 660


Java Book - Chidambaram.S

15. System.out.println(key+":\"answers:\""+value);
16. }//while
17. }//try
18. catch(Exception e)
19. {
20. System.out.println(e);
21. }
22. }//main
23. }//class
24.
25. Output
26.
27. java.runtime.name:"answers:"Java(TM) 2 Runtime Environment, Standard Editi
on
28. sun.boot.library.path:"answers:"D:\Program Files\Java\jdk1.5.0\jre\bin
29. java.vm.version:"answers:"1.5.0-beta2-b51
30. java.vm.vendor:"answers:"Sun Microsystems Inc.
31. java.vendor.url:"answers:"http://java.sun.com/
32. path.separator:"answers:";
33. java.vm.name:"answers:"Java HotSpot(TM) Client VM
34. file.encoding.pkg:"answers:"sun.io
35. user.country:"answers:"US
36. sun.os.patch.level:"answers:"
37. java.vm.specification.name:"answers:"Java Virtual Machine Specification
38. user.dir:"answers:"G:\KalaiPrintingWork\lang\System\properties
39. java.runtime.version:"answers:"1.5.0-beta2-b51
40. java.awt.graphicsenv:"answers:"sun.awt.Win32GraphicsEnvironment
41. java.endorsed.dirs:"answers:"D:\Program Files\Java\jdk1.5.0\jre\lib\endors
ed
42. os.arch:"answers:"x86
43. java.io.tmpdir:"answers:"D:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\
44. line.separator:"answers:"
45. java.vm.specification.vendor:"answers:"Sun Microsystems Inc.
46. user.variant:"answers:"
47. os.name:"answers:"Windows XP

Page 359 of 660


Java Book - Chidambaram.S

48. sun.jnu.encoding:"answers:"Cp1252
49. java.library.path:"answers:"D:\Program Files\Java\jdk1.5.0\bin;.;D:\WINDOW
S\System32;D:\WINDOWS;D:\WINDOWS\system32;D:\WINDOWS;D:\WINDOWS\System32\Wbem;C:
\jdk1.5.0\bin;g:\ORAWIN95\BIN;F:\Program Files\Java\jdk1.5.0\bin
50. java.specification.name:"answers:"Java Platform API Specification
51. java.class.version:"answers:"49.0
52. sun.management.compiler:"answers:"HotSpot Client Compiler
53. java.util.prefs.PreferencesFactory:"answers:"java.util.prefs.WindowsPrefer
encesFactory
54. os.version:"answers:"5.1
55. user.home:"answers:"D:\Documents and Settings\Administrator
56. user.timezone:"answers:"
57. java.awt.printerjob:"answers:"sun.awt.windows.WPrinterJob
58. file.encoding:"answers:"Cp1252
59. java.specification.version:"answers:"1.5
60. user.name:"answers:"Administrator
61. java.class.path:"answers:".;D:\Program Files\Java\jdk1.5.0\lib\classes.zip
;F:\Program Files\Apache Group\Tomcat 4.1\common\lib\servlet.jar;F:\Program File
s\Apache Software Foundation\Tomcat 5.5\common\lib\jsp-
api.jar;F:\Program Files\Apache Software Foundation\Tomcat 5.5\common\lib\servle
t-api.jar;
62. java.vm.specification.version:"answers:"1.0
63. sun.arch.data.model:"answers:"32
64. java.home:"answers:"D:\Program Files\Java\jdk1.5.0\jre
65. java.specification.vendor:"answers:"Sun Microsystems Inc.
66. user.language:"answers:"en
67. awt.toolkit:"answers:"sun.awt.windows.WToolkit
68. java.vm.info:"answers:"mixed mode, sharing
69. java.version:"answers:"1.5.0-beta2
70. java.ext.dirs:"answers:"D:\Program Files\Java\jdk1.5.0\jre\lib\ext
71. sun.boot.class.path:"answers:"D:\Program Files\Java\jdk1.5.0\jre\lib\rt.ja
r;D:\Program Files\Java\jdk1.5.0\jre\lib\i18n.jar;D:\Program Files\Java\jdk1.5.0
\jre\lib\sunrsasign.jar;D:\Program Files\Java\jdk1.5.0\jre\lib\jsse.jar;D:\Progr
am Files\Java\jdk1.5.0\jre\lib\jce.jar;D:\Program Files\Java\jdk1.5.0\jre\lib\ch
arsets.jar;D:\Program Files\Java\jdk1.5.0\jre\classes

Page 360 of 660


Java Book - Chidambaram.S

72. java.vendor:"answers:"Sun Microsystems Inc.


73. file.separator:"answers:"\
74. java.vendor.url.bug:"answers:"http://java.sun.com/cgi-bin/bugreport.cgi
75. sun.cpu.endian:"answers:"little
76. sun.io.unicode.encoding:"answers:"UnicodeLittle
77. sun.desktop:"answers:"windows
78. sun.cpu.isalist:"answers:"

Exit the program using exit()

To terminate the program using exit() of System class. The int arguments serves as the
status code.

The call System.exit(n) is effectively equivalent to the call and exit() calls below
method.

Runtime.getRuntime().exit(n)

1. class ExitDemo
2. {
3. public static void main(String args[])
4. {
5. System.out.println("I am before Exit");
6. System.exit(100);
7. System.out.println("I am after exit");
8. }
9. }
10.
11. Output
12.
13. I am before Exit

Below program calculates the program execution time.

CurrentTimeMillisDemo.java
Page 361 of 660
Java Book - Chidambaram.S

1. /* static long currentTimeMillis() */


2. import java.text.*;
3. import java.util.*;
4. import java.io.*;
5. class CurrentTimeMillisDemo
6. {
7. public static void main(String args[])
8. {
9. try
10. {
11. DataInputStream dis=new DataInputStream(System.in);
12. long starttime=System.currentTimeMillis();
13. Date date=new Date(starttime);
14. SimpleDateFormat sdf=new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss");
15. String start=sdf.format(date);
16. System.out.println("Program Started at ="+start);
17. System.out.println("Enter Are You ready");
18. String choice=dis.readLine();
19. long endtime=System.currentTimeMillis();
20. System.out.println("Program ended at :"+new SimpleDateFormat("dd/MMM/yyyy
hh:mm:ss").format(new Date(endtime)));
21. double elapsedtime=(double)(endtime-starttime)/1000;
22. System.out.println("Program elapsed :"+elapsedtime+" seconds");
23. }
24. catch(Exception e){}
25. }
26. }
27.
28. Output
29.
30. Program Started at =09-Nov-2006 04:06:41
31. Enter Are You ready
32. java
33. Program ended at :09/Nov/2006 04:06:46
34. Program elapsed :5.36 seconds

Page 362 of 660


Java Book - Chidambaram.S

Methods of java.lang.Class

Provider is the sub class and ProviderSuper is the base class.

In ClassCall class using java.lang.Class functionality, we get the class name


and prints them.

1. class ProviderSuper
2. {
3. ProviderSuper()
4. {
5. System.out.println("I am ProviderSuper");
6. }
7. }
8. class Provider extends ProviderSuper
9. {
10. Provider()
11. {
12. System.out.println("I am Provider");
13. }
14. }
15. class ClassCall
16. {
17. public static void main(String args[])
18. {
19. try
20. {
21. Class c1=Class.forName("Provider");
22. System.out.println(c1.getName());
23. Class c2=c1.getSuperclass();
24. System.out.println(c1.getSuperclass().getName());
25. System.out.println(c2.getSuperclass());
26. System.out.println(c2);

Page 363 of 660


Java Book - Chidambaram.S

27. }
28. catch(Exception e)
29. {
30. System.out.println(e);
31. }
32. }
33. }
34.
35. Output
36.
37. Provider
38. ProviderSuper
39. class java.lang.Object
40. class ProviderSuper

Reflection

Using java.lang.Class below programs retrieve and invoke the members of the
Provider.class. This mechanism is known as reflection.

See the inline comments illustrate more detail of the program.

1. Provider.java -
It is the source class and in output you can see the list of members of this cl
ass
2. public class Provider
3. {
4. public final int x=100;
5. public String y="Ragav";
6. public int m1=10;
7. public int m2=100;
8. public Provider(){}
9. public Provider(String name){}

Page 364 of 660


Java Book - Chidambaram.S

10. public Provider(double i,double j){}


11. Provider(float k){}
12. public void private_sum(double x,double y){}
13. public void public_mul(String name){}
14. public void protected_subtract(){}
15. public void default_div(){}
16. public static void main(String args[]){
17. new Provider();
18. }
19. }
20.
21. NetworkClassLoader.java
22. This is the sub class of java.lang.ClassLoader abstract class.
23. It overrides findClass method of the given class name in name parameter an
d loads the class, returns java.lang.Class object.
24. class NetworkClassLoader extends ClassLoader
25. {
26. public Class findClass(String name)
27. {
28. try
29. {
30. FileInputStream fis=new FileInputStream(new File(name));
31. byte b[]=new byte[fis.available()];
32. fis.read(b);
33. return defineClass(b,0,b.length);
34. }
35. catch(Exception e)
36. {
37. e.printStackTrace();
38. return null;
39. }
40. }
41. }
42.
43. ClassDemo.java

Page 365 of 660


Java Book - Chidambaram.S

44. To see the output, run this class.


45. The class is using java.lang.reflect mechanism to retrieve all the members
of the Provider class and invokes the public_mul(String name) of Provider class
.
46. public class ClassDemo
47. {
48. public ClassDemo()
49. {
50. Class c=null;
51. Object ob=null;
52. try
53. {
54. String classname="Provider.class";
55. ClassLoader ncl=new NetworkClassLoader();
56. c=ncl.loadClass(classname);
57. ob=c.newInstance();
58. System.out.println("The name of class is ="+c.getName());
59. Method method[]=c.getDeclaredMethods();
60. for (int i=0;i<method.length;i++)
61. {
62. /* To Display all methods defined in Given Class */
63. System.out.print((method[i].getReturnType()).getName()+ " ");
64. System.out.print(method[i].getName()+"(");
65. Class pmtype[]=method[i].getParameterTypes();
66. for (int j=0;j<pmtype.length;j++)
67. {
68. String args1=pmtype[j].getName();
69. System.out.print(args1);
70. if ((j+1)!=pmtype.length)
71. System.out.print(",");
72. }//inner for
73. System.out.println(")");
74. }//outer for
75. method[3].invoke(ob,"Java");
76. }

Page 366 of 660


Java Book - Chidambaram.S

77. catch(Exception e)
78. {
79. e.printStackTrace();
80. }
81. /* To Display all Construcors defined in Given Class */
82. System.out.println("List of Constructors");
83. try
84. {
85. Constructor co[]=c.getDeclaredConstructors();
86. for (int i=0;i<co.length;i++)
87. {
88. int modifier=co[i].getModifiers();
89. switch (modifier)
90. {
91. case 1:
92. System.out.print("public ");
93. case 0:
94. System.out.print("default ");
95. }
96. System.out.print(co[i].getName()+"(");
97. Class pmtype[]=co[i].getParameterTypes();
98. for (int j=0;j<pmtype.length;j++)
99. {
100. System.out.print(pmtype[j].getName());
101. if ((j+1)!=pmtype.length)
102. System.out.print(",");
103. }
104. System.out.println(")");
105. }
106. }
107. catch(Exception e)
108. {
109. e.printStackTrace();
110. }
111. /* To Display all Variables defined in Given Class */

Page 367 of 660


Java Book - Chidambaram.S

112. System.out.println("List of Variables");


113. try
114. {
115. Field f[]=c.getDeclaredFields();
116. for (int i=0;i<f.length;i++)
117. {
118. int modifier=f[i].getModifiers();
119. switch (modifier)
120. {
121. case 1:
122. System.out.print("public ");
123. break;
124. case 0:
125. System.out.print("default ");
126. break;
127. case 17:
128. System.out.print("public final ");
129. break;
130. case 8:
131. System.out.print("default static ");
132. break;
133. case 9:
134. System.out.print("public static ");
135. break;
136. case 16:
137. System.out.print("final ");
138. break;
139. }//switch
140. System.out.print(f[i].getType().getName()+" ");
141. System.out.print(f[i].getName());
142. Object val= f[i].get(ob);
143. if (val!=null)
144. System.out.print("="+val.toString());
145. System.out.println();
146. }//for

Page 368 of 660


Java Book - Chidambaram.S

147. }//try
148. catch(Exception e)
149. {
150. e.printStackTrace();
151. }
152. }
153. public static void main(String args[])
154. {
155. new ClassDemo();
156. }
157. }
158.
159. command to run the program - java ClassDemo
160.
161. Output
162.
163. The name of class is =Provider
164. void main([Ljava.lang.String;)
165. void protected_subtract()
166. void private_sum(double,double)
167. void public_mul(java.lang.String)
168. void default_div()
169. List of Constructors
170. default Provider(float)
171. public default Provider(double,double)
172. public default Provider(java.lang.String)
173. public default Provider()
174. List of Variables
175. public final int x=100
176. public java.lang.String y=Ragav
177. public int m1=10
178. public int m2=100

1. import java.lang.reflect.*;
2. class MethodsViewDemo

Page 369 of 660


Java Book - Chidambaram.S

3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. Class c=Class.forName("A");
9. //A ob1=new A();
10. //Class c=ob1.getClass();
11. Object ob1=c.newInstance();
12. Method m[]=c.getDeclaredMethods();
13. for (int i=0;i<m.length;i++)
14. {
15. int x=m[i].getModifiers();
16. System.out.println("x="+x);
17. if (x==1)
18. System.out.print("public ");
19. else if(x==0)
20. System.out.print("default ");
21. else if(x==9)
22. System.out.print("public static ");
23. else if(x==8)
24. System.out.print("default static ");
25.
26. System.out.print(m[i].getReturnType().getName()+" ");
27. System.out.print(m[i].getName()+"(");
28. Class ptypes[]=m[i].getParameterTypes();
29. for (int j=0;j<ptypes.length;j++)
30. {
31. System.out.print(ptypes[j].getName());
32. if (j!=ptypes.length-1)
33. System.out.print(",");
34. }//for
35. System.out.println(")");
36. }//outerfor
37. Object ob=m[0].invoke(ob1,5,5,"Rama");

Page 370 of 660


Java Book - Chidambaram.S

38. System.out.println(ob.toString());
39. Constructor con[]=c.getDeclaredConstructors();
40. for(int j=0;j<con.length;j++)
41. {
42. int mod=con[j].getModifiers();
43. if(mod==0)
44. System.out.print("default ");
45. else if(mod==1)
46. System.out.print("public ");
47. else if(mod==2)
48. System.out.print("private ");
49. System.out.print(con[j].getName()+"(");
50. Class pratypes[]=con[j].getParameterTypes();
51. for(int k=0;k<pratypes.length;k++)
52. {
53. System.out.print(pratypes[k].getName());
54. if(k!=pratypes.length-1)
55. System.out.print(",");
56. }
57. System.out.print(")");
58. System.out.println();
59. }
60. Object obj= con[1].newInstance(5,"java");
61. //Object obj1= con[0].newInstance(5.0f);
62. Field f[]=c.getDeclaredFields();
63. for(int l=0;l<f.length;l++)
64. {
65. int md=f[l].getModifiers();
66. if (md==1)
67. System.out.print("public ");
68. else if(md==0)
69. System.out.print("default ");
70. else if(md==9)
71. System.out.print("public static ");
72. else if(md==8)

Page 371 of 660


Java Book - Chidambaram.S

73. System.out.print("default static ");


74. else if(md==2)
75. System.out.print("private ");
76. System.out.print(f[l].getType().getName()+" ");
77. System.out.print(f[l].getName());
78. System.out.print("= ");
79. Object o=f[l].get(ob1);
80. System.out.print(o.toString()+";");
81. System.out.println();
82. }
83. }//try
84. catch(Exception e)
85. {
86. System.out.println(e);
87. }
88. }
89. }
90. Output
91. I am A
92. x=9
93. public static java.lang.String pubmethod(int,int,java.lang.String)
94. x=8
95. default static void defmethod(double,double)
96. I am pubmethod
97. Hello
98. private A(float)
99. default A(int,java.lang.String)
100. public A()
101. I am A with i and s
102. public int age= 23;
103. public static java.lang.String s= java;
104. default float f= 0.0;
105. Class1\A.java
106. A.java
107. public class A

Page 372 of 660


Java Book - Chidambaram.S

108. {
109. public int age=23;
110. public static String s="java";
111. float f;
112. public A()
113. {
114. System.out.println("I am A");
115. }
116. A(int i,String s)
117. {
118. System.out.println("I am A with i and s");
119. }
120. private A(float f)
121. {
122. }
123. public static String pubmethod(int x,int y,String s)
124. {
125. System.out.println("I am pubmethod ");
126. return ("Hello");
127. }
128. static void defmethod(double d1,double d2)
129. {
130. System.out.println("I am defmethod ");
131. }
132. }

Cloning
Cloning is the way to get the copy of the object.

java.lang.Object class has below method to do the clone.

protected Object clone() throws CloneNotSupportedException

Normally assignment operator creates copy of reference only.

Page 373 of 660


Java Book - Chidambaram.S

For example ob1 and ob2 are objects.

ob1=ob2; using this, now ob1 refers the memory of ob2. All the changes in ob2 or ob1
affects both the objects.

By creating the object using clone method creates new copy with the new memory.

To do the clone for an object the class must implement Cloneable interface. Otherwise
we will get CloneNotSupportedException.

Clone Example 1

1. class A implements Cloneable


2. {
3. int x;
4. protected Object clone()
5. {
6. try
7. {
8. //A ob2=(A)super.clone(); // way no 1
9. A ob2=this;
10. return ob2;
11. }
12. catch(Exception e){
13. return null;
14. }
15. }
16. }
17. class CloneDemo1
18. {
19. public static void main(String args[])
20. {
21. A ob1=new A();
22. ob1.x=100;
23. A ob2=(A)ob1.clone();
24. System.out.println("ob1.x="+ob1.x);
25. System.out.println("ob2.x="+ob2.x);

Page 374 of 660


Java Book - Chidambaram.S

26. ob2.x=500;
27. System.out.println("ob1.x="+ob1.x);
28. System.out.println("ob2.x="+ob2.x);
29. }
30. }
31.
32. Output
33.
34. ob1.x=100
35. ob2.x=100
36. ob1.x=500
37. ob2.x=500

Clone Example 2

1. class A implements Cloneable


2. {
3. int x;
4. A objectFactory(A ob1)
5. {
6. try
7. {
8. /*Object o=ob1.clone();//way no 2
9. A o1=(A)o;
10. return o1;*/
11. return (A)ob1.clone();
12. }
13. catch(Exception e)
14. {
15. System.out.println(e);
16. return null;
17. }
18. }
19. }
20. class CloneDemo

Page 375 of 660


Java Book - Chidambaram.S

21. {
22. public static void main(String args[])
23. {
24. A ob1=new A();
25. ob1.x=100;
26.
27. A ob2=ob1.objectFactory(ob1);
28. System.out.println("ob1.x="+ob1.x);
29. System.out.println("ob2.x="+ob2.x);
30. ob1.x=300;
31. System.out.println("ob1.x="+ob1.x);
32. System.out.println("ob2.x="+ob2.x);
33. }
34. }
35.
36. Output
37.
38. ob1.x=100
39. ob2.x=100
40. ob1.x=300
41. ob2.x=100

Math class static methods

Illustrates Math class static methods

1. class MathMethodsDemo1
2. {
3. public static void main(String args[])
4. {
5. System.out.println("Math.ceil(5.1) = " + Math.ceil(5.1));
6. System.out.println("Math.ceil(5.9) = " + Math.ceil(5.9));
7. System.out.println("Math.floor(5.1) = " + Math.floor(5.1));
8. System.out.println("Math.floor(5.9) = " + Math.floor(5.9));

Page 376 of 660


Java Book - Chidambaram.S

9. System.out.println("Math.cos(90.0) = " + Math.cos(90.0));


10. System.out.println("Math.cosh(5.1) = " + Math.cosh(5.1));
11. System.out.println("Math.exp(1) = " + Math.exp(1));
12. System.out.println("Math.expml(1) = " + Math.expm1(1)); // e to the power
x -1
13. System.out.println("Math.IEEEremainder(5,2)="+Math.IEEEremainder(5,2));
14. }
15. }
16.
17. Output
18.
19. Math.ceil(5.1) = 6.0
20. Math.ceil(5.9) = 6.0
21. Math.floor(5.1) = 5.0
22. Math.floor(5.9) = 5.0
23. Math.cos(90.0) = -0.4480736161291702
24. Math.cosh(5.1) = 82.01400202323359
25. Math.exp(1) = 2.7182818284590455
26. Math.expml(1) = 1.718281828459045
27. Math.IEEEremainder(5,2)=1.0
28. class MathMethodsDemo2
29. {
30. public static void main(String args[])
31. {
32. double s=Math.asin(0.123);
33. double c=Math.acos(0.2345);
34. System.out.println("\t acos(12.2345) = " + Math.acos(1.2345));
35. System.out.println("\t asin(0.2345) = " + Math.asin(0.9345));
36. System.out.println("\t atan(12.2345) = " + Math.atan(s/c));
37. System.out.println("\t atan2(12.2345,11.22) = " + Math.atan2(s,c));
38. System.out.println("\t cbrt(27) = " + Math.cbrt(27));
39. }
40. }
41.
42. Output

Page 377 of 660


Java Book - Chidambaram.S

43.
44. acos(12.2345) = NaN
45. asin(0.2345) = 1.206851824742245
46. atan(12.2345) = 0.09216971189683117
47. atan2(12.2345,11.22) = 0.09216971189683117
48. cbrt(27) = 3.0
49. 5,2)=1.0

1. class MathMethodsDemo4
2. {
3. public static void main(String args[])
4. {
5. System.out.println("\t Math.log(2) = " + Math.log(2));
6. System.out.println("\t Math.log10(2) = " + Math.log10(2));
7. System.out.println("\t Math.log1p(2) = " + Math.log1p(2));
8. }
9. }
10.
11. Output
12.
13. Math.log(2) = 0.6931471805599453
14. Math.log10(2) = 0.3010299956639812
15. Math.log1p(2) = 1.0986122886681096

1. class MathMethodsDemo5
2. {
3. public static void main(String args[])
4. {
5. System.out.println("\t Math.max(12,34) = " + Math.max(12,34));
6. System.out.println("\t Math.min(12,34) = " + Math.min(12,34));
7. System.out.println("\t Math.round(2.2)="+Math.round(2.2));
8. System.out.println("\t Math.round(2.5)="+Math.round(2.5f));
9. System.out.println("\t Math.round(2.9)="+Math.round(2.9));
10. System.out.println("\t Math.rint(2.5)="+Math.rint(2.5));

Page 378 of 660


Java Book - Chidambaram.S

11. System.out.println("\t Math.rint(2.6)="+Math.rint(2.6));


12. System.out.println("\t Math.rint(2.9)="+Math.rint(2.9));
13. System.out.println("\t Math.rint(2.1)="+Math.rint(2.1));
14. System.out.println("\t Math.pow(12,2) = " + Math.pow(12,2));
15. System.out.println("\t Math.sqrt(16) = " + Math.sqrt(16));
16. for (int i=0;i<5;i++)
17. {
18. System.out.println(Math.random());
19. }
20. }
21. }
22.
23. Output
24.
25. Math.max(12,34) = 34
26. Math.min(12,34) = 12
27. Math.round(2.2)=2
28. Math.round(2.5)=3
29. Math.round(2.9)=3
30. Math.rint(2.5)=2.0
31. Math.rint(2.6)=3.0
32. Math.rint(2.9)=3.0
33. Math.rint(2.1)=2.0
34. Math.pow(12,2) = 144.0
35. Math.sqrt(16) = 4.0
36. 0.06478348478660945
37. 0.9361368374563154
38. 0.02165977727822388
39. 0.7506637895922688
40. 0.7854865454984901
41. t f= 0.0;

Page 379 of 660


Java Book - Chidambaram.S

Garbage Collection

It is working as like destructor. It means JRE manages Garbage collection to


delete the memory for unused (scopeless) objects.

We need not to start garbage collection. It will be automatically started by run


time. During the time of garbage collection, if you override following method of
java.lang.Object class, it will be called by run time. But it is not guarantee.

protected void finalize()

Garbage collection is the process run by Runtime automatically and


periodically. We can start garbage collection using gc().

Below program illustrates the how garbage collection can be started


and memory consumed using Runtime class

1. class GarbageDemo
2. {
3. Runtime rt=rt=Runtime.getRuntime(); // Runtime class object creation
4. void m1()
5. {
6. int a[]=new int[3000];
7. System.out.println("Total Memory ="+rt.totalMemory());
8. System.out.println("Free Memory 1 ="+rt.freeMemory());
9. System.out.println("Max Memory="+rt.maxMemory());
10. // call the finalize(); but it is not guarantee to call the finalize meth
od even we override the method here
11. rt.runFinalization();
12. rt.gc();//To start the garbage collection explicitly

Page 380 of 660


Java Book - Chidambaram.S

13. System.out.println("After Garbage Collection free memory="+rt.freeMemory()


);
14. }
15. protected void finalize()
16. {
17. System.out.println("I am finalize");
18. }
19. public static void main(String args[])
20. {
21. GarbageDemo gd=new GarbageDemo();
22. gd.m1();
23. }
24. }
25.
26. Output
27.
28. Total Memory =2031616
29. Free Memory 1 =1853376
30. Max Memory=66650112
31. After Garbage Collection free memory=1907328

Runtime class exec()

Using Runtime class we can invoke the applications stored in our machine using
exec() which returns Process object to control the executed application.

1. import java.io.*;
2. class StartFile
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. int x;

Page 381 of 660


Java Book - Chidambaram.S

9. Runtime rt=Runtime.getRuntime();
10. // str[0] - path of the application; str[1] -
the file which opens with the application
11. String str[]={"F:\\Program Files\\Microsoft Office\\Office10\\winword.exe"
,"H:\\java5.30\\lang\\RunTime\\Methods.doc"};
12. Process p=rt.exec(str);
13. p.waitFor(); // This enables JRE to wait until the opened application is c
losed.
14. }catch(Exception e){e.printStackTrace();}
15. }
16. }
17.
18. Output
19.
20. currentTimeMillis() returns current date as long number -
the difference, measured in milliseconds, between the current time and midnight
, January 1, 1970

java.lang.Object class

It is the super class of all predefined and user defined classes. So we can use
the members of Object class in our classes without creating object.

Methods of java.lang.Object

protected Object clone() throws CloneNotSupportedException

To create shallow copy of an object we can use this method. It means object
assignment will not create object with new memory. The LHS object refers the
memory of RHS. By using this method we can create new object based on existing
object with new memory. In java.lang we will discuss about it.

public boolean equals(Object ob)

To check memory equality of objects, we can use this method. If two objects are
having same memory reference, it returns true.

Page 382 of 660


Java Book - Chidambaram.S

protected void finalize() throws Throwable

refer Garbage collection.

public final class getClass()

Creates java.lang.Class object for any one class. In java.lang we will discuss
about it.

public int hashCode()

For each one object run time provides the hash code. The hash codes are same for
same memory references objects. equals() does the same job. If you override
equals() in your class, you can use this method to check the memory equality for
the objects.

public final void notify()

public final void notifyAll()

public final void wait() throws InterruptedException

In thread concepts we will discuss about above three methods.

public String toString()

Refer String class Methods.

Page 383 of 660


Java Book - Chidambaram.S

Chapter 32 - java.net Package

java.net package comes with the classes to implement networking applications.

ServerSockets and Sockets are the two classes to create the client server
application. Lets see the program example below to understand clearly.

ServerSocket - This class performs server side actions.

ServerSocket(int port)

Creates a server socket, bound to the specified port. A port number of 0 means that
the port number is automatically allocated, typically from an ephemeral port range.
This port number can then be retrieved by calling getLocalPort()

Socket
This class implements client sockets

Simple Chat

Send Msg from client to Server

Server.java

1. import java.net.*;
2. import java.io.*;
3.
4. class Server {
5. public static void main(String args[]) {
6. try {
7. /*
8. * ServerSocket is created @ localhost @ 2000 port number. It means
9. * the ServerSocket waits in 2000 port number and listens to accept
10. * Socket

Page 384 of 660


Java Book - Chidambaram.S

11. */
12. ServerSocket ss = new ServerSocket(2000);
13. System.out.println("1");
14. // If socket is connected this server then server accepts and
return
15. // the Socket to our application
16. Socket socket = ss.accept();
17. System.out.println("2");
18. // To get the data from Socket as InputStream
19. InputStream is = socket.getInputStream();
20. System.out.println("3");
21. //
22. byte b[] = new byte[20];
23. System.out.println("4");
24. // Reads data from socket and store in b
25. is.read(b);
26. System.out.println("5");
27. // b[] is converted to String
28. String str = new String(b);
29.
30. System.out.println(str);
31. } catch (Exception e) {
32. e.printStackTrace();
33. }
34. }
35. }

Client.java

1. import java.io.*;
2. import java.net.*;
3.
4. class Client {
5. public static void main(String args[]) {

Page 385 of 660


Java Book - Chidambaram.S

6. try {
7. // Socket object is created. The first argument is the computer name

8. // and the second argument is the port number


9. Socket socket = new Socket("com5", 2000);
10. System.out.println("Enter the Msg to send server");
11. DataInputStream dis = new DataInputStream(System.in);
12. String str = dis.readLine();
13. byte b[] = str.getBytes();
14. // Sockets outputstream is created to write the message to sen
d to
15. // server
16. OutputStream os = socket.getOutputStream();
17. os.write(b);
18. socket.close();
19. } catch (Exception e) {
20. e.printStackTrace();
21. }
22. }
23. }

Note : you can use single machine with two command prompts to demonstrate the
program.

Output

Page 386 of 660


Java Book - Chidambaram.S

InetAddress

This class represents an Internet Protocol (IP) address.

An Internet Protocol address (IP address) is a numerical unsigned number


assigned to each device connected to a computer network.

Internet Protocol version 4 (IPv4) defines an IP address as a 32-bit number

A new version of IP (IPv6), using 128 bits for the IP address.

IPv4 IP Address Example : 172.16.254.1

Lets see the program example below for InetAddress. Below program uses
InetAddress object to retrieve the request details.

1. import java.net.*;
2.
3. class InetAddressDemo {
4. public static void main(String args[])
5. {
6. try
7. {
8. /*
9. InetAddress has below static methods to create InetAddress object
10. We created the object inet1,inet2,inet3 and inet4 */
11. InetAddress inet1=InetAddress.getLocalHost();
12. InetAddress inet2=InetAddress.getByName("Chidambaram-
PC");
13. System.out.println("inet1="+inet1);
14. System.out.println("Details of inet1");
15. System.out.println("GetCanonicalHostName="+inet1.getCanonicalH
ostName());
16. System.out.println("GetHostName="+inet1.getHostName());

Page 387 of 660


Java Book - Chidambaram.S

17. System.out.println("GetHostAddress="+inet1.getHostAddress());
18. System.out.println("inet2="+inet2);
19. System.out.println("Details of inet2");
20. System.out.println("GetCanonicalHostName="+inet2.getCanonicalH
ostName());
21. System.out.println("GetHostName="+inet2.getHostName());
22. System.out.println("GetHostAddress="+inet2.getHostAddress());
23.
24. }//try
25. catch(Exception e){
26. e.printStackTrace();
27. }
28. }// main
29. }// class
30.
31. Output
32.
33. inet1=Chidambaram-PC/192.168.43.33
34. Details of inet1
35. GetCanonicalHostName=Chidambaram-PC
36. GetHostName=Chidambaram-PC
37. GetHostAddress=192.168.43.33
38. inet2=Chidambaram-PC/192.168.43.33
39. Details of inet2
40. GetCanonicalHostName=Chidambaram-PC
41. GetHostName=Chidambaram-PC
42. GetHostAddress=192.168.43.33

Page 388 of 660


Java Book - Chidambaram.S

Two Way Chat


Develop the program to achieve two way chatting

Server Program
It is similar to first program. Except here we accept the socket in while(true) loop.
So it works indefinitely until we quit the command prompt

1. import java.net.*;
2. import java.io.*;
3. import java.util.Date;
4. import java.text.SimpleDateFormat;
5.
6. class Server {
7. public static void main(String args[]) {
8. try {
9. // server socket creation @ localhost @ 2000 port
10. ServerSocket ss = new ServerSocket(2000);
11. while (true) {
12. /*
13. * server waits here; the below line will be executed when
the
14. * socket is arrived to the server and server accepts the
socket
15. * and returns to the application
16. */
17. Socket socket = ss.accept();
18. // InetAddress object created to resolve the client machin
e to
19. // know who is connected the server
20. InetAddress inet = socket.getInetAddress();
21. String clientcomputername = inet.getHostName();
22. // date object created to print when is the client reached
the
23. // server

Page 389 of 660


Java Book - Chidambaram.S

24. String date = new SimpleDateFormat("dd/MMM/yyyy hh:mm:ss")


.format(new Date());
25. // Read the socket data means read the data sent by client

26. InputStream is = socket.getInputStream();


27. byte b[] = new byte[20];
28. is.read(b);
29. String str = new String(b);
30. System.out.println("Client:" + clientcomputername + "Date:
" + date + "Msg:" + str);
31. System.out.print("Client Message:");
32. System.out.println(str);
33. // OutputStream is created for socket to write the message
to
34. // perform the reply
35. OutputStream os = socket.getOutputStream();
36. DataInputStream dis = new DataInputStream(System.in);
37. // Get the reply and send back to client
38. System.out.println("Enter Answer to send the client");
39. str = dis.readLine();
40. os.write(str.getBytes());
41. socket.close();
42. }
43. } catch (Exception e) {
44. e.printStackTrace();
45. }
46.
47. }
48. }

Client Program
It is similar to first program in this book. but in below client program we get the
input and send to server in while(true) loop. So it works indefinitely until we quit
the command prompt or we can close the socket using some condition. I just commented
out the socket.close() in below program.

Page 390 of 660


Java Book - Chidambaram.S

1. import java.io.*;
2. import java.net.*;
3. class Client
4. {
5. public static void main(String args[])
6. {
7. try
8. {
9. while (true)
10. {
11. /*
12. scoket is created to connect SeverSocket in com5 computer @ 2000 port
13. In your machine, you can change to localhost if you run server and client
in two console.
14. ex: Socket socket=new Socket(“localhost”,2000); */
15.
16. Socket socket=new Socket(“com5”,2000);
17. DataInputStream dis=new DataInputStream(System.in);
18. System.out.println(“Enter Msg to send server”);
19. String str=dis.readLine();
20. OutputStream os=socket.getOutputStream();
21. byte b[]=str.getBytes();
22. os.write(b);
23. InputStream is=socket.getInputStream();
24. byte b1[]=new byte[20];
25. is.read(b1);
26. System.out.println(“Server:”+new String(b1));
27. //socket.close();
28. }
29. }
30. catch(Exception e)
31. {
32. e.printStackTrace();
33. }
34. }

Page 391 of 660


Java Book - Chidambaram.S

35. }

Socket Methods

Below program demonstrate Socket Methods


Socket class provides the methods to know the system details. The below program prints
the results of the socket class methods.

The same socket class methods are printed in client side and server side.

Server.java

1. import java.net.*;
2. import java.io.*;
3. import java.util.Date;

Page 392 of 660


Java Book - Chidambaram.S

4. import java.text.SimpleDateFormat;
5. class Server
6. {
7. public static void main(String args[])
8. {
9. String str=””;
10. try
11. {
12. ServerSocket ss=new ServerSocket(2000);
13. while(true)
14. {
15. Socket socket=ss.accept();
16. // To know the client computer name of the machine which socket is
created
17. System.out.println(“Client Name=”+socket.getInetAddress().
getHostName());
18. // To know the server name to the machine socket is connected
19. System.out.println(“Server Name=”+socket.getLocalAddress()
.getHostName());
20. //The port number socket is created at client machine.
21. System.out.println(“Client Port=”+socket.getPort());
22. //The port number socket is connected in server machine
23. System.out.println(“Server Port=”+socket.getLocalPort());

24. /*
25. Returns the binding state of the socket. Even closing a socket doesn't cle
ar its binding state. It means this method will return true until it is bound @
server machine */
26. System.out.println(“Is socket Available=”+socket.isBound()
);
27.
28. String date=new SimpleDateFormat(“dd/MMM/yyyy hh:mm:ss”).f
ormat(new Date());
29. InputStream is=socket.getInputStream();
30. byte b[]=new byte[20] ;

Page 393 of 660


Java Book - Chidambaram.S

31. System.out.println(“Client:”+clientname+”Date:”+date+”Msg:
”+str);
32. socket.close();
33. System.out.println(“After Closing Socket”);
34. System.out.println(“Is socket Available=”+socket.isBound()
);
35. System.out.println(“Is socket Closed=”+socket.isClosed());

36. /*
37. Returns the connection state of the socket. Closing a socket doesn't clea
r its connection state, which means this method will return true until it connec
ts the server */
38. System.out.println(“Is socket Connected=”+socket.isConnect
ed());
39. System.out.println(“Is string information of socket=”+sock
et.toString());
40. }
41. }
42.
43. catch(Exception e)
44. {
45. System.out.println(e);
46. }
47. }
48. }

Client.java

1. import java.io.*;
2. import java.net.*;
3. class Client
4. {
5. public static void main(String args[])
6. {

Page 394 of 660


Java Book - Chidambaram.S

7. Socket socket=null;
8. try
9. {
10. socket=new Socket("com5",2000);
11. socket.getOutputStream().write("Hello ".getBytes());
12. Thread.sleep(5000);
13. }
14. catch(Exception e)
15. {
16. System.out.println(e);
17. }
18. try
19. {
20. InetAddress serverinet=InetAddress.getByName("com5");
21. InetAddress clientinet=InetAddress.getByName("com5");
22. System.out.println("Server Name="+socket.getInetAddress().getH
ostName());
23. System.out.println("Client Name="+socket.getLocalAddress().get
HostName());
24. System.out.println("Socket getPort()="+socket.getPort());
25. System.out.println("Socket getLocalPort()="+socket.getLocalPor
t());
26. System.out.println("Socket isConnected()="+socket.isConnected(
));
27. System.out.println("Is socket Available="+socket.isBound());
28. System.out.println("Socket isClosed()="+socket.isClosed());
29. System.out.println("Socket toString()="+socket.toString());
30. }
31. catch(Exception e)
32. {
33. System.out.println(e);
34. }
35. }
36. }

Page 395 of 660


Java Book - Chidambaram.S

Output

Need

Develop Chat Application. The below program accepts many sockets and enable the

Mulitway Chat Application


Chat between multiple clients as and when required continuously .

Client

ClientPrg

init() - create socket and write client message to send to server

readMessage() - reads the message arrived from other client

sendMessage() - sends the message to other client

ReadThread

It is the thread. For each one client the new thread is started.

This thread invokes readMessage method of ClientPrg

readMessage() waits for client message and once received it will


print.

SendThread

It is one more thread. For each one client the new thread is started

It invokes sendMessage of ClientPrg.

sendMessage() gets the input from client and sends to other client

readMessage() and sendMessage() methods are invoked withing while(true) block.

So one reading / sending is completed again the methods are reading / sending
message indefinitely.

Page 396 of 660


Java Book - Chidambaram.S

Server

ServerPrg

The main method, in while(true) we receive the socket and put


ServerPrg object into one array and invokes createClientThread().

Whenever its createClientThread method is called, it starts new


thread.

In run() it waits to read the message from the client

once the message is received, it separates msg and targetname(target


client computername) using hyphen (-). This is the way we need to send the message for
example if we want to send the message to com2(it is the computername) from com1, the
com2 user should type as like "hello this is com1-com2". Then this method searches
com2 socket and write this message

1. import java.net.*;
2. import java.io.*;
3. class ClientPrg
4. {
5. DataInputStream dis=new DataInputStream(System.in);
6. Socket s;
7. String str;
8. OutputStream os;
9. String systemname;
10. InputStream is;
11. void init()
12. {
13. try
14. {
15. s=new Socket("com8",2000);
16. systemname=InetAddress.getLocalHost().getHostName();
17. os=s.getOutputStream();
18. os.write(systemname.getBytes());
19. }
20. catch(Exception e)
21. {
22. System.out.println("init ="+e);

Page 397 of 660


Java Book - Chidambaram.S

23. }
24.
25. }
26. void readMessage()
27. {
28. try
29. {
30. System.out.println("read 1");
31. byte b[]=new byte[100];
32. System.out.println("read 2");
33. is=s.getInputStream();
34. System.out.println("read 3");
35. is.read(b);
36. System.out.println("read 4");
37. System.out.println(new String(b));
38. }
39. catch(Exception e)
40. {
41. System.out.println("From read="+e);
42. }
43. }//method
44.
45. void sendMessage()
46. {
47. try
48. {
49. System.out.println("Enter the String -
Friend name to send the server");
50. str=dis.readLine();
51. os=s.getOutputStream();
52. os.write(str.getBytes());
53. }
54. catch(Exception e){}
55. }
56. }

Page 398 of 660


Java Book - Chidambaram.S

1. class ReadThread implements Runnable


2. {
3. ClientPrg cp;
4. Thread t1;
5. ReadThread(ClientPrg cp)
6. {
7. this.cp=cp;
8. t1=new Thread(this);
9. t1.start();
10. }
11. public void run()
12. {
13. while(true)
14. cp.readMessage();
15. }//run
16. }//class
17. class SendThread implements Runnable
18. {
19. ClientPrg cp;
20. Thread t2;
21. SendThread(ClientPrg cp)
22. {
23. this.cp=cp;
24. t2=new Thread(this);
25. t2.start();
26. }
27. public void run()
28. {
29. while(true)
30. cp.sendMessage();
31. }//run
32. }//class

Page 399 of 660


Java Book - Chidambaram.S

1. class Client
2. {
3. public static void main(String args[])throws Exception
4. {
5. ClientPrg cp=new ClientPrg();
6. cp.init();
7. ReadThread rt=new ReadThread(cp);
8. SendThread st=new SendThread(cp);
9. }
10. }

1. import java.net.*;
2. import java.io.*;
3. class ServerPrg implements Runnable
4. {
5. static int clientcount;
6. Socket s;
7. Thread t;
8. InputStream is;
9. OutputStream os;
10. String clientname;
11. String message,msg,targetname;
12. static ServerPrg sp[]=new ServerPrg[10];
13. void createClientThread(Socket s)
14. {
15. clientcount=clientcount+1;
16. this.s=s;
17. t=new Thread(this);
18. t.start();
19. }
20. public void run()
21. {

Page 400 of 660


Java Book - Chidambaram.S

22. try
23. {
24. while(true)
25. {
26. System.out.println("1");
27. byte b[]=new byte[100];
28. System.out.println("2");
29. is=s.getInputStream();
30. System.out.println("3");
31. is.read(b);
32. System.out.println("4");
33. message=new String(b);
34. System.out.println("5");
35. msg=message.substring(0,message.indexOf('-'));
36. System.out.println("6");
37. targetname=message.substring(message.indexOf('-
')+1,message.length());
38. System.out.println("7");
39. System.out.println("client Name : "+clientname +": Message
" +msg+"Target Name : "+targetname);
40. // source - clientname
41. // target - targetname
42. //message - msg
43. msg=clientname + ":" +msg;
44. for (int i=0;i<clientcount;i++)
45. {
46. System.out.println("client List");
47. System.out.println("-------------------------");
48. System.out.println(i+"]"+sp[i].clientname);
49.
50. }
51. System.out.println("-------------------------");
52. for (int i=0;i<clientcount;i++)
53. {
54. System.out.println("server for 1");

Page 401 of 660


Java Book - Chidambaram.S

55. System.out.println("sp[i].clientname:"+sp[i].clientnam
e);
56. System.out.println("this.targetname:"+this.targetname)
;
57. if (((sp[i].clientname).trim()).equalsIgnoreCase((this
.targetname).trim()))
58. {
59. System.out.println("server for 2");
60. os=sp[i].s.getOutputStream();
61. System.out.println("server for 3");
62. os.write(msg.getBytes());
63. System.out.println("server for 4");
64. break;
65. }
66. }
67. }//while
68. }
69. catch(Exception e)
70. {
71. e.printStackTrace(); }
72. }//run
73.
74. public static void main(String args[])
75. {
76. int i=-1;
77. InputStream is;
78. byte b[]=new byte[5];
79. String clientname;
80. String clientname1;
81. try
82. {
83. ServerSocket ss=new ServerSocket(2000);
84. while(true)
85. {
86. Socket s=ss.accept();

Page 402 of 660


Java Book - Chidambaram.S

87. i=i+1;
88. sp[i]=new ServerPrg();
89. s.getInputStream().read(b);
90. sp[i].clientname=new String(b);
91. System.out.println(sp[i].clientname+" Connected");
92. sp[i].createClientThread(s);
93.
94. }//while
95. }//try
96. catch(Exception e)
97. {
98. System.out.println("From main ="+e);
99. }//catch
100. }//main
101. }//class

Output

Page 403 of 660


Java Book - Chidambaram.S

How to run this program

1) Open dos console (click start button in windows and type cmd and click
cmd.exe)

2) go to your program stored path using below commands

command : cd..

to come out from one directory

command : cd\

to come to drive

command : drivename:

to go to your program stored drive for example c: or d:

once the drive is changed in prompt go to your folder using below command

cd <your folder path> press enter

now the prompt would show the folder where you store the program.

open three dos prompts

one is for server folder another twoare for client folder

in server dos prompt run server using below command

java ServerPrg

in client dos prompts run clinet using below command

java ClientPrg

now you have three prompts one for server and another two for client. correct.

in one client dos prompt type client1 and another client window type client2

Page 404 of 660


Java Book - Chidambaram.S

these names should be unique and server identifies you using this name only

in client1, type message as like "hi client2-client2". in this message first


part is the actual message and second part would be the client name where this
message should be sent.

in client2, type message as like "hi client1-client1". in this message first


part is the actual message and second part would be the client name where this
message should be sent.

msg part you can any message and second part must be the target client name.

now you can see the message in client console screens.

you can run these programs in LAN (Local Area Network) also.

Datagram

This is the another way to communicate network using Datagram. In previous


article we have seen the ServerSocket and Socket, correct. ServerSocket is for
establish the server side connection and Socket creates the client side
connection. Remember, in chat application or previous program we create only
one server and two sockets correct. It means two sockets are communicated via
serversocket only.

In Datagram, there is no serversocket and socket. Only DatagramSocket. We need


to start different DatagramSockets in different console in one machine or in
different machines. To communicate between DatagramSockets we will be using
DatagramPockets. Hope you understand the first one difference between Socket
and Datagram.

The Socket uses TCP(Transmission Control Protocol), whereas Datagram uses UDP
(User Datagram Protocol).

Page 405 of 660


Java Book - Chidambaram.S

TCP is reliable and message transmission guranteed.

UDP is not reliable but it is desirable when speed is required of example


broadcasting and gaming.

Hope you got the differences between sockets and datagrams

Ok.. now lets look at the program and it is similar flow of above one program
but here we start client and server datagram sockets only.

Two Way Chat - using DatagramSocket and


DatagramPacket
MyDatagram is a java class.

Place this files in two different locations and change port no to different one if you
run in single machine. I here mention 20000 for one file correct. you can change it to
10000 in another file.

Start two MyDatagrams in two different console that's it. Now you are ready to start
the chat. OK Fine. Now let's see how this program is working.

We will start from main method. In main().

1) MyDatagram object md is created correct. md.serverStart() will invoke


serverStart().
2) SendMsg, RecMsg objects are created by passing md as argument.

Let's see the serverStart()

In this method DatagramSocket is created in portno 20000, and another one is 10000.
correct. It means the DatagramSocket is started @ 20000 port number of localhost and @
10000 port number of localhost in different console.

SendMsg, RecMsg constructors start the threads and invoke sendMsg() and recMsg().

sendMsg() accepts the string with the format of computername-message and parses it.

DatagramPacket is created with the argument of byte array, lenght of byte array,
InetAddress object, portnumber

ds.send(dp) sends the msg to the target dp.

Page 406 of 660


Java Book - Chidambaram.S

What we need to understand here that DatagramPacket holds the target computer name,
target computer portnumber along with message.

DatagramSocket sends the DatagramPacket.

In recMsg() we create DatagramPacket with the byte array and its size 25.

ds.receive(dp)- receives Datagrampacket

In next line String object is created to print the datagram packet.

1. import java.net.*;
2. import java.io.*;
3. class MyDatagram
4. {
5. DatagramSocket ds;
6. DataInputStream dis=new DataInputStream(System.in);
7. void serverStart()
8. {
9. try
10. {
11. ds=new DatagramSocket(20000);
12. }
13. catch(Exception e)
14. {
15. e.printStackTrace();
16. }
17. }
18. void sendMsg()
19. {
20. try
21. {
22. String message="";
23. while (true)
24. {

Page 407 of 660


Java Book - Chidambaram.S

25. System.out.println("Enter The String to send, Format : computername-


message");
26. message=dis.readLine();
27. int hyind=message.lastIndexOf("-");
28. String computername=message.substring(0,hyind);
29. String msg=message.substring(hyind+1,message.length());
30. InetAddress inet=InetAddress.getByName(computername);
31. byte b[]=msg.getBytes();
32.
33. DatagramPacket dp=new DatagramPacket(b,b.length,inet,10000);
34. ds.send(dp);
35. }
36. }
37. catch(Exception e)
38. {
39. e.printStackTrace();
40. }
41. }//meth send
42.
43. void recMsg()
44. {
45. byte b1[]=new byte[25];
46. try
47. {
48. while (true)
49. {
50. DatagramPacket dp=new DatagramPacket(b1,25);
51. ds.receive(dp);
52. //dp.getData() - returns byte[], 0-
starting pos of byte array,dp.getLenght()-len of byte array
53. System.out.println("From ur friend: "+new String(dp.getData(),0,dp.getLeng
th()));
54. }
55. }
56. catch(Exception e)

Page 408 of 660


Java Book - Chidambaram.S

57. {
58. e.printStackTrace();
59. }
60. }//meth rec
61. }//class

Page 409 of 660


Java Book - Chidambaram.S

1. class SendMsg implements Runnable


2. {
3. Thread t;
4. MyDatagram md;
5. SendMsg(MyDatagram md)
6. {
7. this.md=md;
8. t=new Thread(this);
9. t.start();
10. }
11. public void run()
12. {
13. try
14. {
15. md.sendMsg();
16. }
17. catch(Exception e)
18. {
19. e.printStackTrace();
20. }
21. }//meth
22. }//class

1. class RecMsg implements Runnable


2. {
3. Thread t;
4. MyDatagram md;
5. RecMsg(MyDatagram md)
6. {
7. this.md=md;
8. t=new Thread(this);
9. t.start();
10. }
11. public void run()

Page 410 of 660


Java Book - Chidambaram.S

12. {
13. try
14. {
15. md.recMsg();
16. }
17. catch(Exception e)
18. {
19. e.printStackTrace();
20. }
21. }//meth
22. }//class

1. class DatagramDemo
2. {
3. static MyDatagram md=new MyDatagram();
4. public static void main(String args[])throws Exception
5. {
6. MyDatagram md=new MyDatagram();
7. md.serverStart();
8. SendMsg sm=new SendMsg(md);
9. RecMsg rm=new RecMsg(md);
10. }
11. }

Page 411 of 660


Java Book - Chidambaram.S

URL and URLConnetion

URLConnection class can be used to open the network location specified by URL
and here I give the local computer file URL using file protocol path format.
You can use any valid http /https URL also to open.

The getInputStream() URLConnection opens the stream in the network location to


read the data.

Need
Receive the Content from Server by Using URL Class

1. import java.net.URL;
2. import java.net.URLConnection;
3. import java.io.*;
4.
5. public class URLConnectionDemo {
6. public static void main(String ar[]) {
7.
8. try {
9. URL url = new URL("file:/e:/demo.txt");
10. URLConnection urlcon = url.openConnection();
11. InputStream stream = urlcon.getInputStream();
12. int i;
13. while ((i = stream.read()) != -1) {
14. System.out.print((char) i);
15. }
16. } catch (Exception e) {
17. System.out.println(e);
18. }
19.
20. }// main
21. }// class

Page 412 of 660


Java Book - Chidambaram.S

ServerSocket with IE as a client


Run the below program in one console as shown in output and start IE and call
the server by entering the URL as shown in output.

Now you can see the result in IE sent by our server.

If client is console just it prints the data. Here the client is brower. So
browser executes HTML code and shows the result.

The message from IE (client) will be printed in server console.

1. import java.net.*;
2. import java.io.*;
3. class Server
4. {
5. public static void main(String args[])
6. {
7. try
8. {
9. ServerSocket ss=new ServerSocket(2000);
10. Socket socket=ss.accept();
11. InputStream is=socket.getInputStream();
12. byte b[]=new byte[300];
13. is.read(b);
14. System.out.println("Request String From IE");
15. System.out.println("------------------------");
16. System.out.println(new String(b));
17. System.out.println("------------------------");
18. OutputStream os=socket.getOutputStream();
19. String str="<h1> MY Server Response <table border=5> <th> Name
</th><th> Age </th> <tr><td> Ram </td><td>21</td></tr></table>";
20. os.write(str.getBytes());
21. socket.close();
22. }
23. catch(Exception e)
24. {

Page 413 of 660


Java Book - Chidambaram.S

25. e.printStackTrace();
26. }
27. }

Output

Page 414 of 660


Java Book - Chidambaram.S

Chapter 33 - java.rmi – Remote Method


invocation

RMI

To develop distributed applications and to call a remote method like calling a


method in same machine. RMI uses registry service for registering and locating
object.

To access the method in living object in remote we can use RMI.

JVM Communication

In java there are three ways to pass message between two JVM(Two Process). Lets
see the three ways below.

Sockets

Datagram

RMI

Socket (Http Based)

Reliable

Fastless

DatagramSocket and DatagramPacket (UDP Protocol)

Fast

Unreliable

RMI
Page 415 of 660
Java Book - Chidambaram.S

Http based

Object can be passed between JVMs but socket allows only primitive type data.

Registry based networking.

RMI Layers

Application Layer

Actual implementation of the client and server applications.

Proxy Layer

Stub and skeleton are the proxies.

Remote Reference Layer

Establishes the communication between stub and skeleton.

Transport Layer

Setting and managing connections to remote machines.

It sends to and receives data from other machines.

Transport layer is responsible for shutting down the connection.

Stub and Skeleton

Responsibilities of Stub

Connects to the Remote JVM

Serializes any arguments to a remote method.

Reads a value returned by remote method

Page 416 of 660


Java Book - Chidambaram.S

Returns the value to the client.

Responsibilities of Skeleton

Reads the parameters for the remote object

Locates the object to be called

Invokes the desired method on remote object

Transmits the result to the stub

Registry

Registry is the memory created and developed by runtime to hold remote objects.

Client can connect registry to get the reference of server.

Registry allows only java.rmi.Remote objects.

Server Application

In java.rmi any one server object should be the sub class of


java.rmi.server.UnicastRemoteObject. Because client can connect only the
object of UnicastRemoteObject and also it should be the sub class of
java.rmi.Remote. Because registry allows only Remote objects.

Example Programs

Need

Client program calls public Student processResult(Student s) and this method


performs following action retrieve the values tamil,English.maths from Student

Page 417 of 660


Java Book - Chidambaram.S

s and find s.total. Then returns s to client.This program demonstrate how we


send and receive object.

Files - Client

Client.java,Student.java,ServerInterface.class,Server_Stub.class.

Files - Server

Server.java,ServerInterface.java,Student.class,Server_Stub.class.

Client/Client.java

1. import java.rmi.*;
2. import java.io.*;
3.
4. class Client {
5. public static void main(String args[]) {
6. try {
7. Student s = new Student();
8. /*
9. * this is the way to access server from client. lookup methods
10. * looks the server object in specified computer as args[0] ar
gs[0]
11. * is the argument can be passed when run the program in conso
le.
12. */
13. ServerInterface si = (ServerInterface) Naming.lookup("rmi://"
+ args[0] + "/Server");
14. Student result = si.processResult(s);
15. System.out.println(" Tamil Mark is =" + result.tamil);
16. System.out.println(" English Mark is =" + result.english);
17. System.out.println(" Maths Mark is =" + result.maths);
18. System.out.println(" Total Mark is =" + result.total);
19. System.out.println(" Average is =" + result.avg);
20. } catch (Exception e) {

Page 418 of 660


Java Book - Chidambaram.S

21. e.printStackTrace();
22. }
23. }
24. }

Client/Student.java

1. import java.io.*;
2. /*
3. Student object will be passed to server from client and
4. server returns the same. The object passed in wire should be the sub class of
5. Serializable to do encryption and decrytpion by runtime. Otherwise we will have
MarshallException at runtime */
6. class Student implements Serializable
7. {
8. int tamil,english,maths,total;
9. double avg;
10. Student()
11. {
12. try
13. {
14. DataInputStream dis=new DataInputStream(System.in);
15. System.out.println("Enter The Tamil ");
16. tamil=Integer.parseInt(dis.readLine());
17. System.out.println("Enter The English ");
18. english=Integer.parseInt(dis.readLine());
19. System.out.println("Enter The Maths ");
20. maths=Integer.parseInt(dis.readLine());
21. }
22. catch(Exception e)
23. {
24. e.printStackTrace();
25. }
26. }

Page 419 of 660


Java Book - Chidambaram.S

27. }

Server/Server.java

1. import java.rmi.*;
2. import java.rmi.server.*;
3. /*
4. Server must be the sub class of java.rmi.server.UnicastRemoteObject and java.rmi
.Remote interface
5. Server is our own class and it extends UnicastRemoteObject and implements Server
Interface (sub interface of Remote)
6. /*
7. class Server extends UnicastRemoteObject implements ServerInterface
8. {
9. // we must add emptry constructor
10. public Server() throws Exception
11. {
12. System.out.println("Server Started");
13. }
14.
15. /*
16. business function that done by server
17. it accesspts Student object and returns same object after
18. applying total in that object
19. */
20. public Student processResult(Student s)
21. {
22. s.total=s.tamil+s.english+s.maths;
23. s.avg=s.total/3;
24. return s;
25. }
26.

Page 420 of 660


Java Book - Chidambaram.S

27. public static void main(String args[])


28. {
29. try
30. {
31. /*
32. server object creation and registration
33. rebind() registers server object in the name of
34. "Server" . So that it can be available to client
35. */
36. Server server=new Server();
37. Naming.rebind("Server",server);
38. }
39. catch(Exception e)
40. { e.printStackTrace();
41. }
42. }//main
43. }//class

Server/ServerInterface.java

1. import java.rmi.*;
2. /*
3. sub interface of Remote must have all business functions
4. needed for client
5. ServerInterface.class must be placed in client folder.
6. */
7. public interface ServerInterface extends Remote
8. {
9. public Student processResult(Student s) throws Exception;
10. }

Output – Client Side

java Client

Enter The Tamil

Page 421 of 660


Java Book - Chidambaram.S

89

Enter The English

98

Enter The Maths

99

Tamil Mark is =89

English Mark is =98

Maths Mark is =99

Total Mark is =286

Average is =95.0

Output – Server Side

java Server

Server Started

Need

By default client can invoke the server’s method, how can we invoke client’s
method from server like Queue Applications. This program is the answer.

Files

Client

Client.class,Client.java,Client_Stub.class,ClientInterface.class,ClientInterface.java,

Server

Page 422 of 660


Java Book - Chidambaram.S

Server.class,Server.java,ServerInterface.class,ServerInterface.java,
ClientInterface.class

Server.java

1. import java.rmi.*;
2. import java.rmi.server.*;
3. import java.util.*;
4. import java.text.*;
5. import java.rmi.registry.*;
6. public class Server extends UnicastRemoteObject implements ServerInterface
7. {
8. int count=0;
9. ClientInterface ci;
10. Vector vector=new Vector();
11. public Server() throws Exception
12. {
13. System.out.println("Server Started");
14. }
15. /* The String sent by client received here */
16. public void receiveMessage(String str)
17. {
18. try
19. {
20. /*
21. Each str sent by client is stored in vector object
22. if more than 5 str means server invokes client method to
23. share the error message
24. */
25. vector.addElement(str);
26. if (vector.size()>=5)
27. /* Now Server Calls Client method getErrorMessage */
28. ci.getErrorMessage("Limit Over, Request Prohibited",vector);

Page 423 of 660


Java Book - Chidambaram.S

29. }
30. catch(Exception e)
31. {
32. e.printStackTrace();
33. }
34. }

Client.java

1. import java.awt.*;
2. import javax.swing.*;
3. import java.awt.event.*;
4. import java.rmi.*;
5. import java.rmi.registry.*;
6. import java.rmi.server.*;
7. import java.util.*;
8. import javax.swing.border.*;
9. /*
10. In previous program Server only sub class of Remote.
11. This program Client also sub class of Remote
12. So client can call client and server can call client.
13. */
14. /*
15. Client qualifies Remote(to invoke by server), JFrame ( to act as frame (sc
reen)) and
16. ActionListener (to listen events such button click and invoke listener met
hods)
17. */
18. class Client extends JFrame implements ActionListener,ClientInterface
19. {
20. //Swing GUI components to create the screen
21. JPanel centerpanel=new JPanel();
22. JPanel centerpanel1=new JPanel();

Page 424 of 660


Java Book - Chidambaram.S

23. JPanel centerpanel2=new JPanel();


24. JPanel southpanel=new JPanel();
25. JPanel northpanel=new JPanel();
26. JList list=new JList();
27. JTextArea textareafile=new JTextArea();
28. JTextField textfield=new JTextField(10);
29. JScrollPane jsp,jsp1;
30. int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
31. int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
32. Container con;
33. JButton sendcmd=new JButton("Send");
34. //si can be used invoke server methods
35. ServerInterface si;
36. void objectCreator()
37. {
38. jsp1=new JScrollPane(list,v,h);
39. con=getContentPane();
40. con.setLayout(new BorderLayout());
41. jsp=new JScrollPane(textareafile,v,h);
42. centerpanel1.setLayout(new BorderLayout());
43. centerpanel2.setLayout(new BorderLayout());
44. centerpanel.setLayout(new BorderLayout());
45. centerpanel1.add(jsp,BorderLayout.CENTER);
46. centerpanel2.add(jsp1,BorderLayout.CENTER);
47. centerpanel.add(centerpanel1,BorderLayout.CENTER);
48. centerpanel.add(centerpanel2,BorderLayout.WEST);
49. northpanel.add(textfield);
50. textfield.setEnabled(false);
51. southpanel.add(sendcmd);
52. add(centerpanel,BorderLayout.CENTER);
53. add(southpanel,BorderLayout.SOUTH);
54. add(northpanel,BorderLayout.NORTH);
55. setExtendedState(Frame.MAXIMIZED_BOTH);
56. setVisible(true);
57. sendcmd.addActionListener(this);

Page 425 of 660


Java Book - Chidambaram.S

58. northpanel.setBorder(new TitledBorder("North Panel"));


59. southpanel.setBorder(new TitledBorder("South Panel"));
60. centerpanel.setBorder(new TitledBorder("Center Panel"));
61. }
62. public void actionPerformed(ActionEvent ae)
63. {
64. try
65. {
66. si.receiveMessage(textareafile.getText());
67. textareafile.setText("");
68. textareafile.requestFocus();
69. }
70. catch(Exception e)
71. {
72. e.printStackTrace();
73. }
74. }
75. /* This method can be invoked by server */
76. public void getErrorMessage(String msg,Vector vector) throws Exception
77. {
78. textfield.setText(msg);
79. list.setListData(vector);
80. sendcmd.setEnabled(false);
81. }
82. void registerClient() throws Exception
83. {
84. //This is the way to get Registry of server
85. Registry reg=LocateRegistry.getRegistry("com7",2000);
86. //get the server object
87. si=(ServerInterface)reg.lookup("Server");
88. /*
89. this refers client object. This call is very important to make client obje
ct
90. is available to server to invoke client methods
91. */

Page 426 of 660


Java Book - Chidambaram.S

92. UnicastRemoteObject.exportObject(this);
93. //This methods passes client object to server.
94. si.registerServer(this);
95. }
96. public static void main(String args[])
97. {
98. try
99. {
100. Client client=new Client();
101. //To start GUI screen in client
102. client.objectCreator();
103. //invokes registerClient()
104. client.registerClient();
105. }
106. catch(Exception e)
107. {
108. e.printStackTrace();
109. }
110. }
111. }

Output – Client

Output – Server

Page 427 of 660


Java Book - Chidambaram.S

java Server

Server Started

Client :192.168.0.208 Registered

Page 428 of 660


Java Book - Chidambaram.S

Chapter 34 - Swing Package

Swing is used to build the GUI (Graphical User Interface) application,


javax.swing package has set of classes to build the UI page and interact with the java
classes to perform the events.

In prior java.awt (Abstract window Toolkit) was introduced in java 1.0 to build
the GUI pages. Swing comes with lot more components more than awt and swing extends
awt to incorporate awt functionalitis in swing.

Differences between AWT and Swing

Awt Swing

Platform Dependent Platform Independent. It was


fully written in java.

Don’t It has Look and Feel


environment with WYSIWYG (What
You See Is What You Get)

Don’t It has more features not


available in awt like border,
picture in button, tool tip
etc.

Page 429 of 660


Java Book - Chidambaram.S

Before deep dive, Lets discuss about component hierarchy to understand how
classes are arranged in awt and swing.

java.awt.Component

java.awt.Container

java.awt.Window

java.awt.Frame java.awt.Dialog

javax.swing.JFrame javax.swing.JDialog

Using above image, lets understand the flow of awt and swing hierarchy as
below and how swing extends awt.

java.awt.Component is the super class, java.awt.Container extends Component,


java.awt.Window extends Container extends java.awt.Frame and java.awt.Dialog
extends Window, javax.swing.JFrame extends java.awt.Frame and
javax.swing.JDialog extends java.awt.Dialog.

Page 430 of 660


Java Book - Chidambaram.S

To create window (screen to place component), we can use JFrame.

To create screen, we need to understand the below screen model. The below
imageillustrates Frame contains window, windows contains container and
container contains the component. Just It is better to remember this one as of
now. In below sections we will understand more better.

Frame
Window
Container
Component

Create and display the JFrame

Below statement is the way to create the JFrame object and displaying JFrame.

JFrame frame=new JFrame("My Window");

frame.show();

Add the controls in JFrame

okcmd=new JButton("Ok");

frame.add(okcmd);

Now the following program, interestingly displays frame in top left corner with
minimized state; when you maximize the frame we can see the command button displays
full in frame.

The following line just displays the command button in center.

Page 431 of 660


Java Book - Chidambaram.S

frame.setLayout(JFrame.BORDER_LAYOUT);

The following line displays JFrame in full window with maximized manner.

frame.setSize(JFRAME.MAXIMIZED_BOTH);

Why? here we need to understand about layout concepts and frame's display methods.

so the complete code would be as follows. Just add this code in one main method and
run it, that's it.

JFrame frame=new JFrame("My Window");

frame.setLayout(JFrame.BORDER_LAYOUT);

frame.setSize(JFRAME.MAXIMIZED_BOTH);

okcmd=new JButton("Ok");

frame.add(okcmd);

frame.show();

Layouts

What is layout

Layout is the technique to apply the design to the screen that instructs how
the components should be arranged.

Layout interfaces

java.awt.LayoutManager and java.awt.LayoutManager2 are the two interfaces below


classes are the sub classes of the above interfaces.

LayoutManager2 extends LayoutManager

Layout Classes

BorderLayout

Page 432 of 660


Java Book - Chidambaram.S

BoxLayout

CardLayout

FlowLayout

GridBagLayout

GridLayout

GroupLayout

SpringLayout

Page 433 of 660


Java Book - Chidambaram.S

BorderLayout

A BorderLayoutplaces components in up to five areas: top, bottom, left, right,


and center.

All extra space is placed in the center area.

Tool bars that are created using JToolBar must be created within
a BorderLayout container.

Sample code to set borderlayout.

frame.setLayout(JFrame.BORDER_LAYOUT);

Event handling

Event handling is the process to handle the events such as mouse click, key press.

In event handling we need to understand two different process.

1) Listeners

2) Event handlers

Listeneres

Below table illustrates, listeners, events and adapters.

Listeners are the sub classes of any one of Listener interface and it overrides
listener methods, which will be invoked by runtime based on the events raised by user
against components.

At the time of listener invocation, the event class will be passed by runtime
automatically. The methods of event class will be useful to handle the events. We will
see the example programs with these concepts.

Adapter classes

The below table lists the Adapter classes for each one listener except those listener
has only one method.

Page 434 of 660


Java Book - Chidambaram.S

In below class, we must override all the methods in MouseListener. Even we don't need
all the methods, we must override with atleast empty implementation.

For example, we want to do something when mouse clicked against button. In this case,
we can add the code in mouseClicked() but we should add empty implementation as like
below.

class MyMouseListener implements MouseListener

public void mouseClicked(MouseEvent e) {

// code to do something

public void mouseEntered(MouseEvent e) {}

public void mouseExited(MouseEvent e) {}

public void mousePressed(MouseEvent e) {}

public void mouseReleased(MouseEvent e) {}

Instead of implementing MouseListener we can extend MouseAdapter to override what


methods we need exactly. No need to override all the methods.

class MyMouseListener extends MouseAdapter

public void mouseClicked(MouseEvent e) {

//code to do something

Page 435 of 660


Java Book - Chidambaram.S

Listener Action Event Methods Adapter

MouseListener Mouse MouseEvent void mouseClicked(MouseEvent e) MouseAdapte


events r
void mouseEntered(MouseEvent e)

void mouseExited(MouseEvent e)

void mousePressed(MouseEvent e)

void mouseReleased(MouseEvent
e)

ActionListener button ActionEvent void No


click actionPerformed(ActionEven
t e)

AdjustmentListe
Scrollb AdjustmentEv Void No
ner
ar ent adjustmentValueChanged(Adjustmen
movemen tEvent e)
ts

FoucsListener
Keyboar FocusEvent void focusGained(FocusEvent e) FocusAdapte
d focus r
void focusLost(FocusEvent e)
events

ItemListener
Checkbo ItemEvent void itemStateChanged(ItemEvent No
x, e)
Radio
button
events

KeyListener
Textbox KeyEvent void keyPressed(KeyEvent e) KeyAdapter

Invoked when a key has been

Page 436 of 660


Java Book - Chidambaram.S

pressed.

void keyReleased(KeyEvent e)

Invoked when a key has been


released.

void keyTyped(KeyEvent e)

Invoked when a key has been


typed.

MouseWheelListe
MouseWheelEv void
ner
ent mouseWheelMoved(MouseWheel
Event e)

FocusListener
FocusEvent void focusGained(FocusEvent e) FocusAdapte
r
void focusLost(FocusEvent e)

WindowListener
Window WindowEvent void WindowAdapt
windowActivated(WindowEven er
t e)

void windowClosed(WindowEvent
e)

void windowClosing(WindowEvent
e)

void
windowDeactivated(WindowEv
ent e)

void
windowDeiconified(WindowEv
ent e)

void

Page 437 of 660


Java Book - Chidambaram.S

windowIconified(WindowEven
t e)

void windowOpened(WindowEvent
e)

java.awt.EventListener is the super interface for all listeners

Lets see the examples in swing package and somne example applets.

Below program demonstrates ActionListener, KeyListener.

1. import javax.swing.*;
2. import java.awt.event.*;
3. import java.awt.*;
4. import javax.swing.border.*;
5. class ActionEventDemo implements ActionListener,KeyListener
6. {
7. JButton okcmd,cancelcmd;
8. JTextField displaytxt;
9. JFrame jf;
10. ActionEventDemo()
11. {
12. objectCreator();
13. layoutProvider();
14. register();
15. effectsProvider();
16. addControlsToJFrame();
17. jframeShow();
18. }
19. void addControlsToJFrame()
20. {
21. jf.getContentPane().add(displaytxt);
22. jf.getContentPane().add(okcmd);

Page 438 of 660


Java Book - Chidambaram.S

23. jf.getContentPane().add(cancelcmd);
24. }
25. void objectCreator()
26. {
27. jf=new JFrame("Events Prg");
28. okcmd=new JButton("Ok");
29. cancelcmd=new JButton("Cancel");
30. displaytxt=new JTextField(15);
31. }
32.
33. void layoutProvider()
34. {
35. jf.getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
36. }
37.
38. void effectsProvider()
39. {
40. jf.setSize(250,250);
41. }
42. void register()
43. {
44. //okcmd.addListSelectionListener(this);
45. cancelcmd.addActionListener(this);
46. displaytxt.addKeyListener(this);
47. displaytxt.requestFocus();
48. }
49. void jframeShow()
50. {
51. jf.show();
52. }
53. public void actionPerformed(ActionEvent ae)
54. {
55. String str=ae.getActionCommand();
56. displaytxt.setText(str);
57. }

Page 439 of 660


Java Book - Chidambaram.S

58. public void keyPressed(KeyEvent ke)


59. {
60. }
61. public void keyReleased(KeyEvent ke)
62. {
63. System.out.println(ke.getKeyChar() + " -"+ke.getKeyCode());
64. if (ke.getKeyCode()==ke.VK_ENTER)
65. {
66. displaytxt.setForeground(Color.red);
67. }
68. }
69. public void keyTyped(KeyEvent ke)
70. {
71. }
72. public static void main(String args[])
73. {
74. new ActionEventDemo();
75. }
76. }

Output

/* if ok is pressed*/

j -74

a -65

Page 440 of 660


Java Book - Chidambaram.S

v -86

a -65

Page 441 of 660


Java Book - Chidambaram.S

Below program demonstrates WindowListener, FocusListener,


TextListener

1. import java.util.*;
2. import javax.swing.*;
3. import java.awt.event.*;
4. import javax.swing.border.*;
5. import java.awt.*;
6. import java.text.*;
7. public class JEventDemo implements Runnable,ActionListener,TextListener,FocusLis
tener,WindowListener
8. {
9. Date timedate;
10. JPanel panel1,panel2,panel3,panel21,panel22;
11. JFrame jf;
12. JLabel dateLbl,timeLbl,titleLbl;
13. Thread t1;
14. JTextField jtf;
15. JEventDemo()
16. {
17. objectCreator();
18. effectsProvider();
19. layoutProvider();
20. addControlsToPanels();
21. addPanelsToJFrame();
22. jf.setSize(700,500);
23. jf.show();
24. t1.start();
25. }
26. public void run()
27. {
28. while(true)
29. {
30. try

Page 442 of 660


Java Book - Chidambaram.S

31. {
32. Thread.sleep(1000);
33. timedate=new Date();
34. }//try
35. catch(Exception e){}
36. setTime();
37. }//while
38. }//run
39. void setTime()
40. {
41. timeLbl.setText(new SimpleDateFormat("hh:mm:ss").format(timedate));
42. }
43. void layoutProvider()
44. {
45. panel1.setLayout(new BorderLayout());
46. jf.getContentPane().setLayout(new BorderLayout());
47. panel2.setLayout(new BorderLayout());
48. jtf.addActionListener(this);
49.
50. jf.addWindowListener(this);
51. }
52. void objectCreator()
53. {
54. jf=new JFrame("Book Store");
55. panel1=new JPanel();
56. panel2=new JPanel();
57. panel3=new JPanel();
58. panel21=new JPanel();
59. panel22=new JPanel();
60. dateLbl=new JLabel();
61. timeLbl=new JLabel();
62. titleLbl=new JLabel("Mark List for 2005 - 2006",SwingConstants.CENTER);
63. t1=new Thread(this);
64. jtf=new JTextField("Hello JAVa",5);
65. }

Page 443 of 660


Java Book - Chidambaram.S

66. void effectsProvider()


67. {
68. /* Date date=new Date
69. SimpleDateFormat sdf=new SimpleDateFormat("dd/MMM/yyyy");
70. */
71. titleLbl.setFont(new Font("Arial",Font.BOLD | Font.ITALIC,20));
72. titleLbl.setForeground(Color.red);
73. dateLbl.setText(new SimpleDateFormat("dd/MMM/yyyy").format(new Date()));
74. panel1.setBorder(new LineBorder(Color.red));
75. panel2.setBorder(new LineBorder(Color.yellow));
76. panel3.setBorder(new LineBorder(Color.blue));
77. panel21.setBorder(new LineBorder(Color.black));
78. panel22.setBorder(new LineBorder(Color.green));
79. jf.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
80. }
81. void addControlsToPanels()
82. {
83. panel1.add(dateLbl,BorderLayout.WEST);
84. panel1.add(timeLbl,BorderLayout.EAST);
85. panel1.add(jtf,BorderLayout.CENTER);
86. //panel1.add(titleLbl,BorderLayout.CENTER);
87. panel2.add(panel21,BorderLayout.CENTER);
88. panel2.add(panel22,BorderLayout.SOUTH);
89.
90. }
91. void addPanelsToJFrame()
92. {
93. jf.getContentPane().add(panel1,BorderLayout.NORTH);
94. jf.getContentPane().add(panel2,BorderLayout.CENTER);
95. jf.getContentPane().add(panel3,BorderLayout.SOUTH);
96. }
97. public void textValueChanged(TextEvent te)
98. {
99. JTextField jtf=(JTextField)(te.getSource());
100. System.out.println(jtf.getText());

Page 444 of 660


Java Book - Chidambaram.S

101. }
102. public void focusGained(FocusEvent fe)
103. {
104.
105. }
106. public void focusLost(FocusEvent fe)
107. {
108. }
109. public void actionPerformed(ActionEvent ae)
110. {
111. System.out.println("ae.getActionCommand()="+ae.getActionCommand());
112. }
113. public void windowClosing(WindowEvent we)
114. {
115. System.out.println("Window Closing");
116. }
117. public void windowClosed(WindowEvent we)
118. {
119. System.out.println("Window Closed");
120. }
121. public void windowIconified(WindowEvent we)
122. {
123. System.out.println("Window Iconified");
124. }
125. public void windowDeiconified(WindowEvent we)
126. {
127. System.out.println("Window DeIconified");
128. }
129. public void windowActivated(WindowEvent we)
130. {
131. System.out.println("Window Activated");
132. }
133. public void windowDeactivated(WindowEvent we)
134. {
135. System.out.println("Window DeActivated");

Page 445 of 660


Java Book - Chidambaram.S

136. }
137. public void windowOpened(WindowEvent we)
138. {
139. }
140.
141. public static void main(String args[])
142. {
143. new JEventDemo();
144. }
145. }

/* WindowConstants

DO_NOTHING_ON_CLOSE

HIDE_ON_CLOSE

DISPOSE_ON_CLOSE

EXIT_ON_CLOSE

*/

Output

Window DeIconified

Window Activated

Window Closing

Window DeActivated

Window Closed

Page 446 of 660


Java Book - Chidambaram.S

Page 447 of 660


Java Book - Chidambaram.S

MouseAdapter example using two classes

1. import java.awt.*;
2. import java.awt.event.*;
3. import javax.swing.*;
4. public class Listener extends MouseAdapter
5. {
6. Source s;
7. public Listener(Source s)
8. {
9. this.s=s;
10. }
11. public void mouseClicked(MouseEvent me)
12. {
13. JOptionPane.showConfirmDialog(s.frame,"My Frame","My Frame Message",JOptio
nPane.DEFAULT_OPTION);
14. }
15. }

1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. class Source
5. {
6. JFrame frame;
7. JButton cmd1;
8. Source()
9. {
10. frame=new JFrame("My Frame");
11. cmd1=new JButton("Click");
12. frame.setLayout(new FlowLayout());
13. frame.add(cmd1);

Page 448 of 660


Java Book - Chidambaram.S

14. frame.setSize(300,300);
15. frame.show();
16. cmd1.addMouseListener(new Listener(this));
17. }
18. public static void main(String args[])
19. {
20. Source s=new Source();
21. }
22. }

Output

/*If ok is clicked*/

Page 449 of 660


Java Book - Chidambaram.S

MouseAdapter example using same class

1. import java.awt.*;
2. import javax.swing.*;
3. import java.awt.event.*;
4. class AdapterDemo extends MouseAdapter
5. {
6. JFrame frame;
7. JButton addcmd,exitcmd,savecmd;
8. AdapterDemo()
9. {
10. frame=new JFrame("Frame");
11. addcmd=new JButton("Add");
12. exitcmd=new JButton("Exit");
13. savecmd=new JButton("Save");
14. frame.setExtendedState(Frame.MAXIMIZED_BOTH);
15. addcmd.addMouseListener(this);
16. frame.setLayout(new FlowLayout(FlowLayout.LEFT,50,50));
17. frame.addMouseListener(this);
18. frame.add(addcmd);
19. frame.add(savecmd);
20. frame.add(exitcmd);
21. frame.show();
22. }
23. public static void main(String s[])
24. {
25. new AdapterDemo();
26. }
27. public void mouseClicked(MouseEvent me)
28. {
29. System.out.println("x="+me.getX());
30. System.out.println("y="+me.getY());
31. }
32. }
33.

Page 450 of 660


Java Book - Chidambaram.S

34. Output
35. /* if add is clicked*/
36. x=29
37. y=10

Page 451 of 660


Java Book - Chidambaram.S

BoxLayout demonstration

1.
2. import javax.swing.*;
3. import java.awt.event.*;
4. import javax.swing.border.*;
5. import java.awt.*;
6. public class BoxLayoutDemo
7. {
8. JPanel panel1,panel2,panel3;
9. JFrame jf;
10. BoxLayoutDemo()
11. {
12. objectCreator();
13. effectsProvider();
14. layoutProvider();
15. addControlsToPanels();
16. addPanelsToJFrame();
17. jf.setSize(700,500);
18. jf.show();
19. }
20. void layoutProvider()
21. {
22. jf.getContentPane().setLayout(new BoxLayout(jf.getContentPane(),BoxLayout.
Y_AXIS));
23. }
24. void objectCreator()
25. {
26. jf=new JFrame("Book Store");
27. panel1=new JPanel();
28. panel2=new JPanel();
29. panel3=new JPanel();
30. }
31. void effectsProvider()
32. {

Page 452 of 660


Java Book - Chidambaram.S

33. panel1.setBorder(new LineBorder(Color.red,10));


34. panel2.setBorder(new LineBorder(Color.yellow,10));
35. panel3.setBorder(new LineBorder(Color.blue,10));
36. }
37. void addControlsToPanels()
38. {
39. //panel2.add(panel21,BorderLayout.CENTER);
40. //panel2.add(panel22,BorderLayout.SOUTH);
41. }
42. void addPanelsToJFrame()
43. {
44. jf.getContentPane().add(panel1);
45. jf.getContentPane().add(panel2);
46. jf.getContentPane().add(panel3);
47. }
48.
49. public static void main(String args[])
50. {
51. new BoxLayoutDemo();
52. }
53. }

Page 453 of 660


Java Book - Chidambaram.S

Output

Page 454 of 660


Java Book - Chidambaram.S

To use object arrays to handle more objects and below methods

setIcon(Icon)

setPressedIcon(Icon)

setRolloverIcon(Icon)

setFont(Font)

setForeground(Color)

setBorder(Border)

setTooltipText(String str)

setMnemonic(int num)

1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. import javax.swing.border.*;
5. class HundredButton implements ActionListener
6. {
7. int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
8. int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
9. JButton button[]=new JButton[100];
10. JPanel panel1;
11. JFrame frame;
12. JScrollPane scrollpane;
13.
14. HundredButton()
15. {
16. objectCreator();
17. layoutProvider();
18. addControlsToPanels();
19. effectsProvider();

Page 455 of 660


Java Book - Chidambaram.S

20. register();
21. frame.show();
22. }
23. void objectCreator()
24. {
25. panel1=new JPanel();
26. frame=new JFrame("My Frame");
27. for (int i=0;i<100;i++)
28. {
29. button[i]=new JButton(String.valueOf(i+1));
30. button[i].setMnemonic(i+49);
31. button[i].setBorder(new LineBorder(Color.blue));
32. }//for
33. }//method
34. void layoutProvider()
35. {
36. frame.setLayout(new BorderLayout());
37. panel1.setLayout(new GridLayout(10,10,20,20));
38. }
39. void addControlsToPanels()
40. {
41. for (int i=0;i<100;i++)
42. panel1.add(button[i]);
43. scrollpane=new JScrollPane(panel1,v,h);
44. frame.add(scrollpane,BorderLayout.CENTER);
45. }
46. void effectsProvider()
47. {
48. for (int i=0;i<100;i++)
49. {
50. button[i].setIcon(new ImageIcon("pressed.jpg"));
51. button[i].setPressedIcon(new ImageIcon("press.jpg"));
52. //button[i].setReleasedIcon(new ImageIcon("release.jpg"));
53. button[i].setRolloverIcon(new ImageIcon("rollover.jpg"));
54. panel1.setBorder(new LineBorder(Color.red,10));

Page 456 of 660


Java Book - Chidambaram.S

55. button[i].setToolTipText("Click to View File "+i);


56. button[i].setForeground(Color.red);
57. button[i].setFont(new Font("Arial",Font.BOLD|Font.ITALIC,20));
58. frame.setExtendedState(Frame.MAXIMIZED_BOTH);
59. }
60. }
61. void register()
62. {
63. for (int i=0;i<100;i++)
64. button[i].addActionListener(this);
65. }
66. public void actionPerformed(ActionEvent ae)
67. {
68. String str=ae.getActionCommand();
69. System.out.println(str);
70. int i=Integer.parseInt(str);
71. //button[i-1].setEnabled(false);
72. button[i-1].setVisible(false);
73. }
74. public static void main(String args[])
75. {
76. new HundredButton();
77. }
78. }//class
79.
80. Output
81. /* if button 99 is clicked*/

Page 457 of 660


Java Book - Chidambaram.S

Page 458 of 660


Java Book - Chidambaram.S

Button methods demonstration

1. import java.awt.*;
2. import javax.swing.*;
3. import javax.swing.border.*;
4. class ButtonMethods
5. {
6. JButton cmd1,cmd2,cmd3;
7. JFrame frame;
8. ButtonMethods()
9. {
10. objectCreator();
11. effectsProvider();
12. layoutProvider();
13. addControlsToFrame();
14. jframeShow();
15. }
16. void objectCreator()
17. {
18. cmd1=new JButton("First");
19. cmd2=new JButton("Second");
20. cmd3=new JButton("Third");
21. frame=new JFrame("JButton Methods");
22. }
23. void effectsProvider()
24. {
25. cmd1.setToolTipText("Click To view File1");// JComponent
26. cmd2.setToolTipText("Click To view File2");
27. cmd3.setToolTipText("Click To view File3");
28. cmd1.setMnemonic('F');
29. cmd2.setMnemonic('S');
30. cmd3.setMnemonic('T');
31.
32. cmd1.setCursor(new Cursor(Cursor.HAND_CURSOR));
33. cmd2.setCursor(new Cursor(Cursor.HAND_CURSOR));

Page 459 of 660


Java Book - Chidambaram.S

34. cmd3.setCursor(new Cursor(Cursor.HAND_CURSOR));


35. cmd1.setFont(new Font("Arial",Font.BOLD,30));
36. cmd1.setBackground(Color.red);
37. cmd2.setBackground(Color.red);
38. cmd3.setBackground(Color.red);
39. cmd1.setForeground(Color.green);
40. cmd2.setForeground(Color.green);
41. cmd3.setForeground(Color.green);
42. cmd1.setIcon(new ImageIcon("cmd1.gif"));
43. cmd1.setRolloverIcon(new ImageIcon("rollover.gif"));
44. cmd1.setPressedIcon(new ImageIcon("pressed.gif"));
45.
46. cmd1.setBorder(new LineBorder(Color.blue,15));
47. }
48. void layoutProvider()
49. {
50. frame.setLayout(new FlowLayout());
51. }
52. void addControlsToFrame()
53. {
54. frame.add(cmd1);
55. frame.add(cmd2);
56. frame.add(cmd3);
57. }
58. void jframeShow()
59. {
60. frame.setExtendedState(Frame.MAXIMIZED_BOTH);
61. frame.show();
62. cmd2.requestFocus();
63. }
64. public static void main(String args[])
65. {
66. new ButtonMethods();
67. }
68. }

Page 460 of 660


Java Book - Chidambaram.S

Output

Card Layout Demonstration

Page 461 of 660


Java Book - Chidambaram.S

1. import javax.swing.*;
2. import java.awt.event.*;
3. import javax.swing.border.*;
4. import java.awt.*;
5. public class CardLayoutDemo implements MouseListener,ActionListener
6. {
7. JPanel panel1,panel2,panel3;
8. JFrame jf;
9. JPanel main1;
10. JButton cb1,cb2;
11. CardLayout clo;
12. CardLayoutDemo()
13. {
14. objectCreator();
15. layoutProvider();
16. effectsProvider();
17. addListeners();
18. addControlsToPanels();
19. addPanelsToJFrame();
20. jf.setSize(300,300);
21. jf.show();
22. }
23. void layoutProvider()
24. {
25. jf.getContentPane().setLayout(new BoxLayout(jf.getContentPane(),BoxLayout.
Y_AXIS));
26. main1.setLayout(new CardLayout());
27. }
28. void objectCreator()
29. {
30. jf=new JFrame("Book Store");
31. panel1=new JPanel();
32. panel2=new JPanel();
33. panel3=new JPanel();
34. main1=new JPanel();

Page 462 of 660


Java Book - Chidambaram.S

35. cb1=new JButton("Next");


36. cb2=new JButton("Previous");
37. clo=new CardLayout();
38. }
39. void effectsProvider()
40. {
41. panel1.setBorder(new LineBorder(Color.red,10));
42. panel2.setBorder(new LineBorder(Color.yellow,10));
43. panel3.setBorder(new LineBorder(Color.blue,10));
44. }
45. void addControlsToPanels()
46. {
47. main1.add(panel1,"a");
48. main1.add(panel2,"b");
49. panel3.add(cb1);
50. panel3.add(cb2);
51. }
52. void addListeners()
53. {
54. jf.addMouseListener(this);
55. cb1.addActionListener(this);
56. cb2.addActionListener(this);
57. }
58. void addPanelsToJFrame()
59. {
60. /*jf.getContentPane().add(panel1);
61. jf.getContentPane().add(panel2);*/
62. jf.getContentPane().add(panel3);
63. jf.getContentPane().add(main1);
64. }
65. public void mousePressed(MouseEvent me)
66. {
67. clo.next(main1);
68. }
69.

Page 463 of 660


Java Book - Chidambaram.S

70. public void mouseClicked(MouseEvent me)


71. {
72.
73. }
74. public void mouseReleased(MouseEvent me)
75. {
76.
77. }
78. public void mouseExited(MouseEvent me)
79. {
80.
81. }
82. public void mouseEntered(MouseEvent me)
83. {
84.
85. }
86. public void actionPerformed(ActionEvent ae)
87. {
88. if (ae.getSource()==cb1)
89. clo.show(main1,"a");
90. else
91. clo.show(main1,"b");
92. }
93. public static void main(String args[])
94. {
95. new CardLayoutDemo();
96. }
97. }

Output

Page 464 of 660


Java Book - Chidambaram.S

Page 465 of 660


Java Book - Chidambaram.S

Checkbox Demonstration

1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. import javax.swing.border.*;
5. class CheckBox1 implements ItemListener
6. {
7. String selectedtext="";
8. JFrame jf;
9. JPanel p1,p2,p3,p4;
10. JCheckBox win98,win2000,winxp,IP,AMD,celeron;
11. ButtonGroup bg1,bg2;
12. JLabel displaylbl,titlelbl;
13. CheckBox1()
14. {
15. objectCreator();
16. effectsProvider();
17. layoutProvider();
18. register();
19. addControlsToPanels();
20. addPanelsToJFrame();
21. jframeShow();
22. }
23. void objectCreator()
24. {
25. bg1=new ButtonGroup();
26. bg2=new ButtonGroup();
27. win98=new JCheckBox("win98");
28. win2000=new JCheckBox("win2000");
29. winxp=new JCheckBox("winxp");
30. IP=new JCheckBox("IP");

Page 466 of 660


Java Book - Chidambaram.S

31. AMD=new JCheckBox("AMD");


32. celeron=new JCheckBox("celeron");
33. titlelbl=new JLabel(" CheckBoxDemo ");
34. displaylbl=new JLabel();
35. p1=new JPanel();
36. p2=new JPanel();
37. p3=new JPanel();
38. p4=new JPanel();
39. jf=new JFrame("CheckBox ");
40. }
41.
42. void effectsProvider()
43. {
44. titlelbl.setBackground(Color.red);
45. titlelbl.setForeground(Color.green);
46. titlelbl.setFont(new Font("Arial",Font.BOLD,18));
47.
48. p1.setBorder(new LineBorder(Color.yellow));
49. p2.setBorder(new LineBorder(Color.yellow));
50. p3.setBorder(new LineBorder(Color.yellow));
51. p4.setBorder(new LineBorder(Color.yellow));
52.
53. p2.setBorder(new TitledBorder("which OS"));
54. p3.setBorder(new TitledBorder("which CPU"));
55.
56. p1.setBackground(new Color(50,50,150));
57. p2.setBackground(new Color(50,50,150));
58. p3.setBackground(new Color(50,50,150));
59. p4.setBackground(new Color(50,50,150));
60.
61. win98.setBackground(Color.red);
62. win2000.setBackground(Color.red);
63. winxp.setBackground(Color.red);
64. IP.setBackground(Color.red);
65. AMD.setBackground(Color.red);

Page 467 of 660


Java Book - Chidambaram.S

66. celeron.setBackground(Color.red);
67.
68. displaylbl.setBackground(Color.red);
69. displaylbl.setForeground(Color.green);
70. displaylbl.setFont(new Font("Arial",Font.BOLD,18));
71. }
72. void addControlsToPanels()
73. {
74. p1.add(titlelbl);
75. p2.add(win98);
76. p2.add(win2000);
77. p2.add(winxp);
78. p3.add(IP);
79. p3.add(AMD);
80. p3.add(celeron);
81. p4.add(displaylbl);
82.
83. bg1.add(win98);
84. bg1.add(win2000);
85. bg1.add(winxp);
86.
87. bg2.add(IP);
88. bg2.add(AMD);
89. bg2.add(celeron);
90.
91. }
92. void addPanelsToJFrame()
93. {
94. jf.getContentPane().add(p1);
95. jf.getContentPane().add(p2);
96. jf.getContentPane().add(p3);
97. jf.getContentPane().add(p4);
98. }
99. void register()
100. {

Page 468 of 660


Java Book - Chidambaram.S

101. win98.addItemListener(this);
102. win2000.addItemListener(this);
103. winxp.addItemListener(this);
104. IP.addItemListener(this);
105. AMD.addItemListener(this);
106. celeron.addItemListener(this);
107.
108. }
109. void jframeShow()
110. {
111. jf.setExtendedState(Frame.MAXIMIZED_BOTH);
112. jf.show();
113. }
114. void layoutProvider()
115. {
116. p1.setLayout(new FlowLayout(FlowLayout.CENTER,20,50));
117. p2.setLayout(new FlowLayout(FlowLayout.CENTER,50,50));
118. p3.setLayout(new FlowLayout(FlowLayout.CENTER,50,50));
119. p4.setLayout(new FlowLayout(FlowLayout.CENTER,50,50));
120. jf.getContentPane().setLayout(new BoxLayout(jf.getContentPane(),BoxLayout.
Y_AXIS));
121. }
122. public void itemStateChanged(ItemEvent ie)
123. {
124. if (win98.isSelected())
125. displaylbl.setText("win98");
126. if (win2000.isSelected())
127. displaylbl.setText("win2000");
128. else if(winxp.isSelected())
129. displaylbl.setText("winxp");
130. if (IP.isSelected())
131. displaylbl.setText("IP");
132. if (AMD.isSelected())
133. displaylbl.setText("AMD");
134. else if(celeron.isSelected())

Page 469 of 660


Java Book - Chidambaram.S

135. displaylbl.setText("celeron");
136. }//method
137.
138. public static void main(String args[])
139. {
140. CheckBox1 cb=new CheckBox1();
141. }
142. }

Output

/* if win98 is clicked*/

Page 470 of 660


Java Book - Chidambaram.S

Online Exam Demonstration

1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. import javax.swing.border.*;
5. class Checkbox implements ActionListener,ItemListener
6. {
7. ImageIcon normal;
8. ImageIcon rollover;
9. ImageIcon selected;
10. String selectedtext="";

Page 471 of 660


Java Book - Chidambaram.S

11. JFrame jf;


12. JPanel p1,p2,p3,p4;
13. JCheckBox choicerdo1,choicerdo2,choicerdo3,choicerdo4,choice1rdo1,choice1r
do2,choice1rdo3,choice1rdo4;
14. ButtonGroup bg1,bg2;
15. JButton result1cmd,result2cmd;
16. JLabel correct1lbl,correct2lbl,titlelbl;
17. Checkbox()
18. {
19. objectCreator();
20. effectsProvider();
21. layoutProvider();
22. register();
23. addControlsToPanels();
24. addPanelsToJFrame();
25. jframeShow();
26. }
27. void objectCreator()
28. {
29. normal=new ImageIcon("normal.gif");
30. rollover=new ImageIcon("rollover.gif");
31. selected=new ImageIcon("selected.gif");
32. bg1=new ButtonGroup();
33. bg2=new ButtonGroup();
34. choicerdo1=new JCheckBox("JDK");
35. choicerdo2=new JCheckBox("JVM");
36. choicerdo3=new JCheckBox("J2EE");
37. choicerdo4=new JCheckBox("J2MV");
38. choice1rdo1=new JCheckBox("RMI");
39. choice1rdo2=new JCheckBox("Advanced Java");
40. choice1rdo3=new JCheckBox("Core Java");
41. choice1rdo4=new JCheckBox("Swing");
42. titlelbl=new JLabel(" On Line Exam ");
43. result1cmd=new JButton(" View Result ");
44. result2cmd=new JButton(" View Result ");

Page 472 of 660


Java Book - Chidambaram.S

45. correct1lbl=new JLabel();


46. correct2lbl=new JLabel();
47. p1=new JPanel();
48. p2=new JPanel();
49. p3=new JPanel();
50. p4=new JPanel();
51. jf=new JFrame(" On Line Exam");
52. }
53.
54. void effectsProvider()
55. {
56. choicerdo1.setRolloverIcon(rollover);
57. choicerdo1.setSelectedIcon(selected);
58. choicerdo2.setRolloverIcon(rollover);
59. choicerdo2.setSelectedIcon(selected);
60. choicerdo3.setRolloverIcon(rollover);
61. choicerdo3.setSelectedIcon(selected);
62. choice1rdo1.setRolloverIcon(rollover);
63. choice1rdo1.setSelectedIcon(selected);
64. choice1rdo2.setRolloverIcon(rollover);
65. choice1rdo2.setSelectedIcon(selected);
66. choice1rdo3.setRolloverIcon(rollover);
67. choice1rdo3.setSelectedIcon(selected);
68. p2.setBorder(new TitledBorder("appletviewer is the part of ________"));
69. p3.setBorder(new TitledBorder("J2SE refers __________"));
70. titlelbl.setForeground(new Color(97,125,222));
71. titlelbl.setFont(new Font("Arial",Font.BOLD,35));
72. p1.setBackground(new Color(26,87,123));
73. p2.setBackground(new Color(26,87,123));
74. p3.setBackground(new Color(26,87,123));
75. p4.setBackground(new Color(26,87,123));
76. choicerdo1.setBackground(new Color(26,87,123));
77. choicerdo2.setBackground(new Color(26,87,123));
78. choicerdo3.setBackground(new Color(26,87,123));
79. choicerdo4.setBackground(new Color(26,87,123));

Page 473 of 660


Java Book - Chidambaram.S

80. choice1rdo1.setBackground(new Color(26,87,123));


81. choice1rdo2.setBackground(new Color(26,87,123));
82. choice1rdo3.setBackground(new Color(26,87,123));
83. choice1rdo4.setBackground(new Color(26,87,123));
84. correct1lbl.setBackground(new Color(26,87,123));
85. correct2lbl.setBackground(new Color(26,87,123));
86. titlelbl.setForeground(new Color(97,125,222));
87. }
88. void addControlsToPanels()
89. {
90. p1.add(titlelbl);
91. p2.add(choicerdo1);
92. p2.add(choicerdo2);
93. p2.add(choicerdo3);
94. p2.add(choicerdo4);
95. p2.add(result1cmd);
96. p3.add(choice1rdo1);
97. p3.add(choice1rdo2);
98. p3.add(choice1rdo3);
99. p3.add(choice1rdo4);
100. p3.add(result2cmd);
101. p4.add(correct1lbl);
102. p4.add(correct2lbl);
103. bg1.add(choicerdo1);
104. bg1.add(choicerdo2);
105. bg1.add(choicerdo3);
106. bg1.add(choicerdo4);
107. bg2.add(choice1rdo1);
108. bg2.add(choice1rdo2);
109. bg2.add(choice1rdo3);
110. bg2.add(choice1rdo4);
111. }
112. void addPanelsToJFrame()
113. {
114. jf.getContentPane().add(p1);

Page 474 of 660


Java Book - Chidambaram.S

115. jf.getContentPane().add(p2);
116. jf.getContentPane().add(p3);
117. jf.getContentPane().add(p4);
118. }
119. void register()
120. {
121. result1cmd.addActionListener(this);
122. result2cmd.addActionListener(this);
123. choicerdo1.addItemListener(this);
124. choicerdo2.addItemListener(this);
125. choicerdo3.addItemListener(this);
126. choicerdo4.addItemListener(this);
127. choice1rdo1.addItemListener(this);
128. choice1rdo2.addItemListener(this);
129. choice1rdo3.addItemListener(this);
130. choice1rdo4.addItemListener(this);
131. result1cmd.addActionListener(this);
132. result2cmd.addActionListener(this);
133. }
134. void jframeShow()
135. {
136. jf.setExtendedState(Frame.MAXIMIZED_BOTH);
137. jf.show();
138. }
139. void layoutProvider()
140. {
141. p1.setLayout(new FlowLayout(FlowLayout.CENTER,20,50));
142. p2.setLayout(new FlowLayout(FlowLayout.CENTER,50,50));
143. p3.setLayout(new FlowLayout(FlowLayout.CENTER,50,50));
144. p4.setLayout(new FlowLayout(FlowLayout.CENTER,50,50));
145. jf.getContentPane().setLayout(new BoxLayout(jf.getContentPane(),BoxLayout.
Y_AXIS));
146. }
147. public void itemStateChanged(ItemEvent ie)
148. {

Page 475 of 660


Java Book - Chidambaram.S

149. if (choicerdo1.isSelected())
150. correct1lbl.setText("Good, You had 10 Marks");
151. else
152. correct1lbl.setText("Badd, You had 0 Marks");
153. if (choice1rdo3.isSelected())
154. correct2lbl.setText("Good, You had 10 Marks");
155. else
156. correct2lbl.setText("Badd, You had 0 Marks");
157. }//method
158.
159. public void actionPerformed(ActionEvent ae)
160. {
161. if (ae.getSource()==result1cmd)
162. {
163. if (selectedtext.equalsIgnoreCase("JDK"))
164. correct1lbl.setText("Good, You had 10 Marks");
165. else
166. correct1lbl.setText("bad, You had 0 Marks");
167. }
168. if (ae.getSource()==result2cmd)
169. {
170. if (selectedtext.equalsIgnoreCase("Core Java"))
171. correct2lbl.setText("Good, You had 10 Marks");
172. else
173. correct2lbl.setText("bad, You had 0 Marks");
174. }
175. }//method
176. public static void main(String args[])
177. {
178. new Checkbox();
179. }
180. }

Page 476 of 660


Java Book - Chidambaram.S

Output

Colorchooser Demonstration

1. import javax.swing.*;
2. import javax.swing.event.*;
3. import java.awt.*;
4. import java.awt.event.*;
5. import javax.swing.border.*;
6. class ColorChooser1
7. {
8. JFrame frame;
9. JColorChooser jcc;
10. JPanel panel;
11. ColorChooser1()
12. {

Page 477 of 660


Java Book - Chidambaram.S

13. panel=new JPanel();


14. frame=new JFrame("Color Chooser");
15. frame.setLayout(new BorderLayout());
16. jcc=new JColorChooser();
17. frame.setVisible(true);
18. frame.setExtendedState(Frame.MAXIMIZED_BOTH);
19. Color c=jcc.showDialog(frame,"Color",Color.blue);
20. frame.add(panel,BorderLayout.CENTER);
21. panel.setBackground(c);
22. panel.setBorder(new LineBorder(Color.blue,10));
23. frame.show();
24. }
25.
26. public static void main(String args[])
27. {
28. new ColorChooser1();
29. }
30. }

Output

Page 478 of 660


Java Book - Chidambaram.S

Dialog Demonstration

1. import java.io.*;
2. import javax.swing.*;
3. import java.awt.*;
4. import java.awt.event.*;
5. public class Dialog implements ActionListener
6. {
7. JDialog jd;
8. JLabel jl;
9. JButton jb;
10. JFrame jf;
11. public void showDialog()
12. {
13. jf=new JFrame("Dialog Box");
14. jd=new JDialog(jf,true);
15. jd.setTitle("Password Success");
16. jd.getContentPane().setLayout(null);
17. jl=new JLabel("Click Ok to go to Server");
18. jb=new JButton("OK");
19. jb.addActionListener(this);
20. jl.setBounds(10,40,300,25);
21. jb.setBounds(70,80,100,25);
22. jd.getContentPane().add(jl);
23. jd.getContentPane().add(jb);
24. jd.setBounds(160,70,400,150);
25. jf.setExtendedState(Frame.MAXIMIZED_BOTH);
26. jf.show();
27. jd.show();
28. }
29. public void actionPerformed(ActionEvent ae)
30. {
31. if ((ae.getActionCommand()).equals("OK"))

Page 479 of 660


Java Book - Chidambaram.S

32. {
33. jd.setVisible(false);
34. jd=null;
35. }//if
36. }//method
37.
38. public static void main(String args[])
39. {
40. Dialog d=new Dialog();
41. d.showDialog();
42. }
43. }//class

Output

Page 480 of 660


Java Book - Chidambaram.S

GraphicsEnvironment Usage

import java.awt.*;

class LocalScreenDemo

public static void main(String args[])

GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();

Rectangle r=ge.getMaximumWindowBounds();

System.out.println(r.width);

System.out.println(r.height);

Point p=ge.getCenterPoint();

System.out.println(p.x);

System.out.println(p.y);

Output

800

566

400

283

Page 481 of 660


Java Book - Chidambaram.S

FileChooser Demonstration

1. import javax.swing.*;
2. import javax.swing.event.*;
3. import java.awt.event.*;
4. import java.awt.*;
5. import java.io.*;
6. import javax.swing.filechooser.*;
7. class ExampleFileFilter extends javax.swing.filechooser.FileFilter
8. {
9. String filename;
10. String extension;
11. public boolean accept(File f)
12. {
13. if (f.isDirectory())
14. {
15. return true;
16. }
17. else
18. {
19. filename=f.getName();
20. extension=filename.substring(filename.lastIndexOf("."),filename.length());

21. if (extension.equalsIgnoreCase(".jpg"))
22. return true;
23. else
24. return false;
25. }
26. }
27. public String getDescription() {
28. return null;
29. }
30. }
31.
32. public class FileChooser implements ActionListener

Page 482 of 660


Java Book - Chidambaram.S

33. {
34. //JLabel lbl=new JLabel();
35. JFileChooser jfc=new JFileChooser();
36. JFrame frame=new JFrame("My Frame");
37. JButton opencmd=new JButton("Open");
38. JButton savecmd=new JButton("Save");
39. JButton clearcmd=new JButton("Clear");
40. JTextField text =new JTextField(20);
41. JPanel panel=new JPanel();
42. JPanel panel1=new JPanel();
43. FileChooser()
44. {
45. try
46. {
47. panel.add(opencmd);
48. panel.add(savecmd);
49. panel.add(clearcmd);
50. panel1.add(text);
51. //panel1.add(lbl);
52. frame.setLayout(new BorderLayout());
53. frame.add(panel,BorderLayout.SOUTH);
54. frame.add(panel1,BorderLayout.CENTER);
55. jfc.setFileFilter(new ExampleFileFilter());
56. jfc.setCurrentDirectory(new File("h:/javapsna/swing"));
57. //setExtendedState(Frame.MAXIMIZED_BOTH);
58. frame.setSize(500,500);
59. //setVisible(true);
60. opencmd.addActionListener(this);
61. savecmd.addActionListener(this);
62. clearcmd.addActionListener(this);
63. frame.show();
64. }
65. catch(Exception e)
66. {}
67. }

Page 483 of 660


Java Book - Chidambaram.S

68. public void actionPerformed(ActionEvent ae)


69. {
70. try
71. {
72. if(((JButton)ae.getSource()==opencmd))
73. {
74. int returnVal = jfc.showOpenDialog(frame);
75. if(returnVal == JFileChooser.APPROVE_OPTION)
76. {
77. String open=jfc.getSelectedFile().getCanonicalPath();
78. FileInputStream fis=new FileInputStream(open);
79. byte b[]=new byte[fis.available()];
80. fis.read(b);
81. text.setText(new String(b));
82. //lbl.setIcon(new ImageIcon(open));
83. }
84. }
85. else if(((JButton)ae.getSource()==savecmd))
86. {
87. int returnVal = jfc.showSaveDialog(frame);
88. if(returnVal == JFileChooser.APPROVE_OPTION)
89. {
90. String save=jfc.getSelectedFile().getCanonicalPath();
91. String txt=text.getText();
92. //String txt=lbl.getText();
93. byte b1[]=txt.getBytes();
94. FileOutputStream fos=new FileOutputStream(save);
95. fos.write(b1);
96. }//if
97. }//elseif
98. else if(((JButton)ae.getSource()==clearcmd))
99. {
100. text.setText("");
101. //lbl.setIcon(null);
102. }

Page 484 of 660


Java Book - Chidambaram.S

103. }//try
104. catch(Exception e)
105. { }
106. }
107. public static void main(String args[])
108. {
109. FileChooser fc=new FileChooser();
110. }
111. }

Output

Page 485 of 660


Java Book - Chidambaram.S

FoucsEvent Demonstration

1. import java.util.*;
2. import javax.swing.*;
3. import java.awt.event.*;
4. import javax.swing.border.*;
5. import java.awt.*;
6. import java.text.*;
7. public class JFocusEventDemo implements TextListener,FocusListener
8. {
9. Date timedate;
10. JFrame jf;
11. JTextField text1,text2,text3;
12. JLabel label1,label2;
13. JPanel panel1;
14. JFocusEventDemo()
15. {
16. objectCreator();
17. effectsProvider();
18. addControlsToPanels();
19. addPanelsToJFrame();
20. register();

Page 486 of 660


Java Book - Chidambaram.S

21. jf.setSize(300,300);
22. jf.show();
23. }
24. void objectCreator()
25. {
26. f=new JFrame("Book Store");
27. text1=new JTextField(20);
28. text2=new JTextField(20);
29. text3=new JTextField(20);
30. panel1=new JPanel();
31. label1=new JLabel("Focus Gained=");
32. label2=new JLabel("Focus Lost =");
33. }
34. void effectsProvider()
35. {
36. text1.setName("Text1");
37. text2.setName("Text2");
38. text3.setName("Text3");
39. jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
40. }
41. void addControlsToPanels()
42. {
43. panel1.add(text1);
44. panel1.add(text2);
45. panel1.add(text3);
46. panel1.add(label1);
47. panel1.add(label2);
48. }
49.
50. void addPanelsToJFrame()
51. {
52. jf.getContentPane().add(panel1,BorderLayout.CENTER);
53. }
54. void register()
55. {

Page 487 of 660


Java Book - Chidambaram.S

56. text1.addFocusListener(this);
57. text2.addFocusListener(this);
58. text3.addFocusListener(this);
59. //text1.addTextListener(this);
60. }
61. public void textValueChanged(TextEvent te)
62. {
63. JTextField jtf=(JTextField)(te.getSource());
64. System.out.println(jtf.getText());
65. }
66. public void focusGained(FocusEvent fe)
67. {
68. label2.setText("Focus Lost=");
69. System.out.println("Oppoiste="+fe.getOppositeComponent());
70. if (fe.getOppositeComponent()!=null)
71. {
72. label2.setText(label2.getText()+fe.getOppositeComponent().getName());
73. }
74. }
75. public void focusLost(FocusEvent fe)
76. {
77. label1.setText("Focus Gained=");
78. if (fe.getOppositeComponent()!=null)
79. {
80. label1.setText(label1.getText()+fe.getOppositeComponent().getName());
81. System.out.println(label1.getText()+fe.getOppositeComponent().getName());

82. }
83. }
84.
85. public static void main(String args[])
86. {
87. new JFocusEventDemo();
88. }
89. }

Page 488 of 660


Java Book - Chidambaram.S

/* WindowConstants

DO_NOTHING_ON_CLOSE

HIDE_ON_CLOSE

DISPOSE_ON_CLOSE

EXIT_ON_CLOSE

*/

Output

Focus Gained=Text3Text3

Oppoiste=javax.swing.JTextField[Text2,34,30,224x20,layout=javax.swing.plaf.basic.Basic
TextUI$UpdateHandler,alignmentX=0.0,alignmentY=0.0,border=javax.swing.plaf.BorderUIRes
ource$CompoundBorderUIResource@14a9972,flags=296,maximumSize=,minimumSize=,preferredSi
ze=,caretColor=javax.swing.plaf.ColorUIResource[r=51,g=51,b=51],disabledTextColor=java
x.swing.plaf.ColorUIResource[r=184,g=207,b=229],editable=true,margin=javax.swing.plaf.

Page 489 of 660


Java Book - Chidambaram.S

InsetsUIResource[top=0,left=0,bottom=0,right=0],selectedTextColor=javax.swing.plaf.Col
orUIResource[r=51,g=51,b=51],selectionColor=javax.swing.plaf.ColorUIResource[r=184,g=2
07,b=229],columns=20,columnWidth=11,command=,horizontalAlignment=LEADING]

Process terminated

Label Demonstration

1. import java.awt.*;
2. import java.awt.event.*;
3. class LabelTextDemo implements ActionListener,TextListener,FocusListener,WindowL
istener
4. {
5. Frame frame;
6. Panel panel1,panel2,panel3,panelfirst;
7. Label namelbl,agelbl,passwordlbl;
8. TextField nametxt,agetxt,passwordtxt;
9. Button okcmd,clearcmd,quitcmd;
10. Label namedisplaylbl,agedisplaylbl,passworddisplaylbl;
11. LabelTextDemo()
12. {
13. objectCreator();
14. effectsProvider();
15. layoutProvider();
16. register();
17. addControlsToFrame();
18. }
19. void layoutProvider()
20. {
21. frame.setLayout(new BorderLayout());
22. panelfirst.setLayout(new BorderLayout());
23. panel1.setLayout(new GridLayout(3,2,400,50));
24. panel2.setLayout(new GridLayout(1,3,200,300));
25. panel3.setLayout(new GridLayout(2,2));

Page 490 of 660


Java Book - Chidambaram.S

26. }
27. void objectCreator()
28. {
29. frame=new Frame("Label Text Demo");
30. panel1=new Panel();
31. panel2=new Panel();
32. panel3=new Panel();
33. panelfirst=new Panel();
34. namelbl=new Label("Enter The Name",Label.RIGHT);
35. agelbl=new Label("Enter The Age",Label.RIGHT);
36. passwordlbl=new Label("Enter The Password",Label.RIGHT);
37. nametxt=new TextField(10);
38. nametxt.setName("name");
39. agetxt=new TextField();
40. agetxt.setName("age");
41. passwordtxt=new TextField(10);
42. passwordtxt.setName("Password");
43. okcmd=new Button("Ok");
44. clearcmd=new Button("Clear");
45. quitcmd=new Button("Quit");
46. namedisplaylbl=new Label("Display Name");
47. agedisplaylbl=new Label("Display Age");
48. passworddisplaylbl=new Label("Display PassWord");
49. }
50. void effectsProvider()
51. {
52. //frame.setBackground(Color.yellow);
53. namedisplaylbl.setBackground(new Color(100,0,0));
54. passwordtxt.setEchoChar('*');
55. //jf.SetDefaultCloseOperation(jf.
56. }
57. void register()
58. {
59. okcmd.addActionListener(this);
60. clearcmd.addActionListener(this);

Page 491 of 660


Java Book - Chidambaram.S

61. quitcmd.addActionListener(this);
62. //nametxt.addTextListener(this);
63. nametxt.addFocusListener(this);
64. agetxt.addFocusListener(this);
65. passwordtxt.addFocusListener(this);
66. frame.addWindowListener(this);
67. }
68. void addControlsToFrame()
69. {
70. panel1.add(namelbl);
71. panel1.add(nametxt);
72. panel1.add(agelbl);
73. panel1.add(agetxt);
74. panel1.add(passwordlbl);
75. panel1.add(passwordtxt);
76. panel2.add(okcmd);
77. panel2.add(clearcmd);
78. panel2.add(quitcmd);
79. frame.add(panel1,BorderLayout.NORTH);
80. panel3.add(namedisplaylbl);
81. panel3.add(agedisplaylbl);
82. panel3.add(passworddisplaylbl);
83. panelfirst.add(panel1,BorderLayout.NORTH);
84. panelfirst.add(panel2,BorderLayout.SOUTH);
85. frame.add(panelfirst,BorderLayout.NORTH);
86. frame.add(panel3,BorderLayout.SOUTH);
87. frame.setSize(300,300);
88. frame.show();
89. }
90. public void textValueChanged(TextEvent te)
91. {
92. System.out.println(((TextField)te.getSource()).getText());
93. System.out.println("TextListener="+nametxt.getText());
94. }
95. public void actionPerformed(ActionEvent ae)

Page 492 of 660


Java Book - Chidambaram.S

96. {
97. System.out.println(ae.getActionCommand());
98. Button b=(Button)ae.getSource();
99. String str=b.getLabel();
100. if (str.equals("Ok"))
101. {
102. System.out.println(nametxt.getText());
103. System.out.println(agetxt.getText());
104. System.out.println(passwordtxt.getText());
105. nametxt.select(1,5);
106. nametxt.requestFocus();
107. System.out.println(nametxt.getSelectedText());
108. namedisplaylbl.setText("The Name is ="+nametxt.getText());
109. agedisplaylbl.setText("The age is ="+agetxt.getText());
110. passworddisplaylbl.setText("The password is ="+passwordtxt.getText());
111. agetxt.setEnabled(false);
112. agetxt.setEchoChar('?');
113. System.out.println(agetxt.echoCharIsSet());
114. System.out.println(agetxt.getEchoChar());
115. }
116. else if (str.equals("Clear"))
117. {
118. nametxt.setText("");
119. agetxt.setText("");
120. passwordtxt.setText("");
121. }
122. else if(str.equals("Quit"))
123. {
124. System.out.println("quit");
125. frame.remove(panelfirst);
126. frame.remove(panel3);
127. frame=null;
128. frame.setVisible(false);
129. }
130. }

Page 493 of 660


Java Book - Chidambaram.S

131. public void focusGained(FocusEvent fe)


132. {
133. if (fe.getOppositeComponent()!=null)
134. System.out.println("Focus Lost="+fe.getOppositeComponent().getName());
135. }
136. public void focusLost(FocusEvent fe)
137. {
138. if (fe.getOppositeComponent()!=null)
139. System.out.println("Focus Gained="+fe.getOppositeComponent().getName());
140. //System.out.println(fe.paramString());
141. }
142. public void windowClosing(WindowEvent we)
143. {
144. System.out.println("Window Closing");
145. //jf.SetDefaultCloseOperation(jf.
146. }
147. public void windowClosed(WindowEvent we)
148. {
149. System.out.println("Window Closed");
150. }
151. public void windowIconified(WindowEvent we)
152. {
153. System.out.println("Window Iconified");
154. }
155. public void windowDeiconified(WindowEvent we)
156. {
157. System.out.println("Window DeIconified");
158. }
159. public void windowActivated(WindowEvent we)
160. {
161. System.out.println("Window Activated");
162. }
163. public void windowDeactivated(WindowEvent we)
164. {
165. System.out.println("Window DeActivated");

Page 494 of 660


Java Book - Chidambaram.S

166. }
167. public void windowOpened(WindowEvent we)
168. {
169. }
170. public static void main(String args[])
171. {
172. new LabelTextDemo();
173. }
174. }//class

Output

Window Activated

Window Iconified

Window DeActivated

Window DeIconified

Window Activated

Window Closing

Page 495 of 660


Java Book - Chidambaram.S

JList Demonstration

1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. import javax.swing.event.*;
5. import javax.swing.border.*;
6. class AddRemoveDemo implements ActionListener,ListSelectionListener
7. {
8. JFrame jf;
9. JScrollPane scrollpane1,scrollpane2;
10. String str[]={"Dindigul","Madurai","Coimbatore","Trichy","Chennai","Natham
","Pudukottai"};
11. JList citylist;
12. JList citylistcopy;
13. JPanel panel1,panel2,panel3;
14. int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
15. int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
16. AddRemoveDemo()
17. {
18. objectCreator();
19. effectsProvider();
20. layoutProvider();
21. register();
22. addControlsToJFrame();
23. showJFrame();
24. }
25. void objectCreator()
26. {
27. citylist=new JList(str);
28. jf=new JFrame("Action Event Demo");
29. citylistcopy=new JList();
30. panel1=new JPanel();
31. panel2=new JPanel();
32. panel3=new JPanel();

Page 496 of 660


Java Book - Chidambaram.S

33. scrollpane1=new JScrollPane(citylist,v,h);


34. scrollpane2=new JScrollPane(citylistcopy,v,h);
35. }
36. void addControlsToJFrame()
37. {
38. panel1.add(scrollpane1);
39. panel1.add(scrollpane2);
40. jf.getContentPane().add(panel1);
41. jf.getContentPane().add(panel2);
42. jf.getContentPane().add(panel3);
43. }
44. void showJFrame()
45. {
46. jf.setSize(300,300);
47. jf.show();
48. }
49. void layoutProvider()
50. {
51. jf.getContentPane().setLayout(new BoxLayout(jf.getContentPane(),BoxLayout.
Y_AXIS));
52. }
53. void effectsProvider()
54. {
55. citylist.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

56. citylist.setSelectionForeground(Color.red);
57. panel1.setBorder(new CompoundBorder(new LineBorder(Color.red,3,true),new T
itledBorder("ListEventListener")));
58. panel2.setBorder(new CompoundBorder(new LineBorder(Color.green,3,true),new
TitledBorder("AdjustmentEvent")));
59. panel3.setBorder(new CompoundBorder(new LineBorder(Color.yellow,3,true),ne
w TitledBorder("ListEventListener")));
60. citylist.setVisibleRowCount(5);
61. citylistcopy.setVisibleRowCount(5);
62. scrollpane1.getViewport().setView(citylist);

Page 497 of 660


Java Book - Chidambaram.S

63. scrollpane2.getViewport().setView(citylistcopy);
64. }
65. void register()
66. {
67. citylist.addListSelectionListener(this);
68. }
69. public void actionPerformed(ActionEvent ae)
70. {
71. System.out.println(ae.getActionCommand());
72. }
73. public void valueChanged(ListSelectionEvent e)
74. {
75. JList list=(JList)e.getSource();
76. //int item[]=list.selectedIndices();
77. Object ob[]=list.getSelectedValues();
78. citylistcopy.setListData(ob);
79. }
80.
81. public static void main(String args[])
82. {
83. new AddRemoveDemo();
84. }
85. }

Page 498 of 660


Java Book - Chidambaram.S

Output :

Menu Demonstration

1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. import javax.swing.border.*;
5. import java.applet.*;
6. import javax.swing.event.*;
7. public class MenuDemo1 implements ActionListener,MenuKeyListener
8. {
9. JFrame frame;
10. JMenuBar menubar;
11. JMenu coursemenu;
12. JMenu feesmenu;
13. JMenuItem mcomitem;
14. JMenuItem mscitem;
15. JMenuItem mbaitem;
16. JMenuItem mcomfeesitem;
17. JMenuItem mscfeesitem;
18. JMenuItem mbafeesitem;

Page 499 of 660


Java Book - Chidambaram.S

19. MenuDemo1()
20. {
21. objectCreator();
22. effectsProvider();
23. layoutProvider();
24. register();
25. addControlsToPanels();
26. addPanelsToJFrame();
27. jframeShow();
28. }
29. void objectCreator()
30. {
31. frame=new JFrame("Menu");
32. menubar=new JMenuBar();
33. coursemenu=new JMenu("Course");
34. feesmenu=new JMenu("Fees");
35. mcomitem=new JMenuItem("M.Com.,");
36. mbaitem=new JMenuItem("MBA",65);
37. mscitem=new JMenuItem("M.Sc.,");
38. mcomfeesitem=new JMenuItem("M.Com Fees.,");
39. mbafeesitem=new JMenuItem("MBA Fees");
40. mscfeesitem=new JMenuItem("M.Sc., Fees");
41. }
42. void effectsProvider()
43. {
44. coursemenu.add(mcomitem);
45. coursemenu.add(mscitem);
46. coursemenu.add(mbaitem);
47. feesmenu.add(mcomfeesitem);
48. feesmenu.add(mbafeesitem);
49. feesmenu.add(mscfeesitem);
50. menubar.add(coursemenu);
51. menubar.add(feesmenu);
52. }
53. void addControlsToPanels()

Page 500 of 660


Java Book - Chidambaram.S

54. {
55. }
56. void addPanelsToJFrame()
57. {
58. frame.setJMenuBar(menubar);
59. }
60. void register()
61. {
62. mcomitem.addMenuKeyListener(this);
63. mscitem.addMenuKeyListener(this);
64. mbaitem.addMenuKeyListener(this);
65. mcomfeesitem.addMenuKeyListener(this);
66. mscfeesitem.addMenuKeyListener(this);
67. mbafeesitem.addMenuKeyListener(this);
68. mbafeesitem.addActionListener(this);
69. }
70.
71. void jframeShow()
72. {
73. //frame.setExtendedState(Frame.MAXIMIZED_BOTH);
74. frame.setSize(300,300);
75. frame.show();
76. }
77. void layoutProvider()
78. {
79. }
80. public void menuKeyTyped(MenuKeyEvent e){
81. System.out.println("Menu Key Typed");
82. }
83. public void menuKeyPressed(MenuKeyEvent e){
84. System.out.println("Menu Key Pressed");
85. }
86. public void menuKeyReleased(MenuKeyEvent e){
87. System.out.println("Menu Key Released");
88. }

Page 501 of 660


Java Book - Chidambaram.S

89. public void actionPerformed(ActionEvent ae)


90. {
91. System.out.println(ae.getActionCommand());
92. }
93. public static void main(String args[])
94. {
95. new MenuDemo1();
96. }
97. }

Output :

Menu Key Pressed

Menu Key Pressed

Menu Key Pressed

Menu Key Released

Menu Key Released

Menu Key Released

Page 502 of 660


Java Book - Chidambaram.S

Checked Menu Item example

1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. import javax.swing.border.*;
5. class MenuDemo implements ActionListener
6. {
7. int x,y;
8. JPanel panel;
9. Timer timer=new Timer(1000,this);
10. JFrame frame;
11. JMenuBar menubar;
12. JMenu coursemenu;
13. JMenu feesmenu;
14. JMenuItem mcomitem;
15. JMenuItem mscitem;
16. JMenuItem mbaitem;
17. JCheckBoxMenuItem mcomfeesitem;
18. JMenuItem mscfeesitem;
19. JMenuItem mbafeesitem;
20. Graphics g;
21. MenuDemo()
22. {
23. //timer.addActionListener(this);
24. timer.start();
25. objectCreator();
26. effectsProvider();
27. layoutProvider();
28. register();
29. addControlsToPanels();
30. addPanelsToJFrame();
31. jframeShow();
32. }
33. void objectCreator()

Page 503 of 660


Java Book - Chidambaram.S

34. {
35. panel=new JPanel();
36. frame=new JFrame("Menu");
37. //g=frame.getGraphics();
38. menubar=new JMenuBar();
39. coursemenu=new JMenu("Course");
40. feesmenu=new JMenu("Fees");
41. mcomitem=new JMenuItem("M.Com.,",65);
42. mbaitem=new JMenuItem("MBA");
43. mscitem=new JMenuItem("M.Sc.,");
44. mcomfeesitem=new JCheckBoxMenuItem("M.Com Fees.,",new ImageIcon("Ms.jpg"),
true);
45. mbafeesitem=new JMenuItem("MBA Fees");
46. mscfeesitem=new JMenuItem("M.Sc., Fees");
47. }
48. void effectsProvider()
49. {
50. coursemenu.add(mcomitem);
51. coursemenu.addSeparator();
52. coursemenu.add(mscitem);
53. coursemenu.addSeparator();
54. coursemenu.add(mbaitem);
55. coursemenu.addSeparator();
56. coursemenu.add(new JButton("Button"));
57. feesmenu.add(mcomfeesitem);
58. feesmenu.addSeparator();
59. feesmenu.add(mbafeesitem);
60. feesmenu.addSeparator();
61. feesmenu.add(mscfeesitem);
62. menubar.add(coursemenu);
63. feesmenu.addSeparator();
64. menubar.add(feesmenu);
65. }
66.
67. void addControlsToPanels()

Page 504 of 660


Java Book - Chidambaram.S

68. {
69. }
70. void addPanelsToJFrame()
71. {
72. frame.getContentPane().add(panel);
73. frame.setJMenuBar(menubar);
74. }
75. void register()
76. {
77. mbaitem.addActionListener(this);
78. mcomitem.addActionListener(this);
79. mscitem.addActionListener(this);
80. mcomfeesitem.addActionListener(this);
81. }
82.
83. public void actionPerformed(ActionEvent ae)
84. {
85. if (ae.getSource()==mcomitem)
86. System.out.println("Mcom is selected");
87.
88. if (ae.getSource()==mcomfeesitem)
89. {
90. if (mcomfeesitem.getState()==true)
91. System.out.println("Mcom Fees Item is selected");
92. else
93. System.out.println("Mcom Fees Item is deselected");
94. }
95. }
96.
97. void jframeShow()
98. {
99. //frame.setExtendedState(Frame.MAXIMIZED_BOTH);
100. frame.setSize(300,300);
101. frame.show();
102. }

Page 505 of 660


Java Book - Chidambaram.S

103. void layoutProvider()


104. {
105. }
106. public static void main(String args[])
107. {
108. new MenuDemo();
109. }
110. }

Page 506 of 660


Java Book - Chidambaram.S

Checked Menu example

1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. import javax.swing.border.*;
5. class MenuDemo implements ActionListener
6. {
7. int x,y;
8. JPanel panel;
9. Timer timer=new Timer(1000,this);
10. JFrame frame;
11. JMenuBar menubar;
12. JMenu coursemenu;
13. JMenu feesmenu;
14. JMenuItem mcomitem;
15. JMenuItem mscitem;
16. JMenuItem mbaitem;
17. JCheckBoxMenuItem mcomfeesitem;
18. JMenuItem mscfeesitem;
19. JMenuItem mbafeesitem;
20. Graphics g;
21. MenuDemo()
22. {
23. //timer.addActionListener(this);
24. timer.start();
25. objectCreator();
26. effectsProvider();
27. layoutProvider();
28. register();
29. addControlsToPanels();
30. addPanelsToJFrame();
31. jframeShow();
32. }
33. void objectCreator()

Page 507 of 660


Java Book - Chidambaram.S

34. {
35. panel=new JPanel();
36. frame=new JFrame("Menu");
37. //g=frame.getGraphics();
38. menubar=new JMenuBar();
39. coursemenu=new JMenu("Course");
40. feesmenu=new JMenu("Fees");
41. mcomitem=new JMenuItem("M.Com.,",65);
42. mbaitem=new JMenuItem("MBA");
43. mscitem=new JMenuItem("M.Sc.,");
44. mcomfeesitem=new JCheckBoxMenuItem("M.Com Fees.,",new ImageIcon("Ms.jpg"),
true);
45. mbafeesitem=new JMenuItem("MBA Fees");
46. mscfeesitem=new JMenuItem("M.Sc., Fees");
47. }
48. void effectsProvider()
49. {
50. coursemenu.add(mcomitem);
51. coursemenu.addSeparator();
52. coursemenu.add(mscitem);
53. coursemenu.addSeparator();
54. coursemenu.add(mbaitem);
55. coursemenu.addSeparator();
56. coursemenu.add(new JButton("Button"));
57. feesmenu.add(mcomfeesitem);
58. feesmenu.addSeparator();
59. feesmenu.add(mbafeesitem);
60. feesmenu.addSeparator();
61. feesmenu.add(mscfeesitem);
62. menubar.add(coursemenu);
63. feesmenu.addSeparator();
64. menubar.add(feesmenu);
65. }
66.
67. void addControlsToPanels()

Page 508 of 660


Java Book - Chidambaram.S

68. {
69. }
70. void addPanelsToJFrame()
71. {
72. frame.getContentPane().add(panel);
73. frame.setJMenuBar(menubar);
74. }
75. void register()
76. {
77. mbaitem.addActionListener(this);
78. mcomitem.addActionListener(this);
79. mscitem.addActionListener(this);
80. mcomfeesitem.addActionListener(this);
81. }
82.
83. public void actionPerformed(ActionEvent ae)
84. {
85. if (ae.getSource()==mcomitem)
86. System.out.println("Mcom is selected");
87.
88. if (ae.getSource()==mcomfeesitem)
89. {
90. if (mcomfeesitem.getState()==true)
91. System.out.println("Mcom Fees Item is selected");
92. else
93. System.out.println("Mcom Fees Item is deselected");
94. }
95. }
96.
97. void jframeShow()
98. {
99. //frame.setExtendedState(Frame.MAXIMIZED_BOTH);
100. frame.setSize(300,300);
101. frame.show();
102. }

Page 509 of 660


Java Book - Chidambaram.S

103. void layoutProvider()


104. {
105. }
106. public static void main(String args[])
107. {
108. new MenuDemo();
109. }
110. }

Menu with combo Demonstration

1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. import javax.swing.event.*;
5. class MenuDemo implements ActionListener,PopupMenuListener,MenuListener
6. {
7. JFrame frame;
8. JMenuBar menubar;
9. JMenu imagemenu,fontmenu;
10. JMenuItem loaditem,exititem;

Page 510 of 660


Java Book - Chidambaram.S

11. JButton clearcmd;


12. JComboBox combobox,fontcmb,sizecmb;
13. JCheckBoxMenuItem checkbolditem;
14. JTextField fonttxt,addmenutxt;
15. void start()
16. {
17. fonttxt=new JTextField(20);
18. addmenutxt=new JTextField(20);
19. frame=new JFrame();
20. //frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
21. frame.setSize(300,300);
22. menubar=new JMenuBar();
23. imagemenu=new JMenu("Image",true);
24. fontmenu=new JMenu("Font");
25.
26. loaditem=new JMenuItem("Load",new ImageIcon("MS.jpg"));
27. clearcmd=new JButton("Clear");
28. clearcmd.setMnemonic('C');
29. String str[]={"a.jpg","b.jpg","c.jpg"};
30. combobox=new JComboBox(str);
31. JMenuItem exititem=new JMenuItem("Exit",'E');
32. /* To get all font names defined in your system */
33. GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();

34. String font[]=ge.getAvailableFontFamilyNames();


35. fontcmb=new JComboBox(font);
36.
37. String size[]={"8","10","16","24","28","32"};
38. sizecmb=new JComboBox(size);
39.
40. checkbolditem=new JCheckBoxMenuItem("Bold");
41.
42. imagemenu.add(loaditem);
43. imagemenu.addSeparator();
44. imagemenu.add(clearcmd);

Page 511 of 660


Java Book - Chidambaram.S

45. imagemenu.addSeparator();
46. imagemenu.add(combobox);
47. imagemenu.addSeparator();
48. imagemenu.add(exititem);
49. imagemenu.addSeparator();
50.
51. fontmenu.add(fontcmb);
52. fontmenu.addSeparator();
53. fontmenu.add(sizecmb);
54. fontmenu.addSeparator();
55. fontmenu.add(checkbolditem);
56.
57. combobox.addActionListener(this);
58. fontcmb.addActionListener(this);
59. sizecmb.addActionListener(this);
60. clearcmd.addActionListener(this);
61. combobox.addPopupMenuListener(this);
62. fontcmb.addPopupMenuListener(this);
63. sizecmb.addPopupMenuListener(this);
64. imagemenu.addMenuListener(this);
65. fontmenu.addMenuListener(this);
66.
67. addmenutxt.addKeyListener(new KeyAdapter()
68. {
69. public void keyPressed(KeyEvent ke)
70. {
71. if (ke.getKeyCode()==ke.VK_ENTER)
72. {
73. fontmenu.add(new JMenuItem(addmenutxt.getText(),new ImageIcon("MS.jpg")));

74. addmenutxt.setText("");
75. }
76. }
77. });
78.

Page 512 of 660


Java Book - Chidambaram.S

79. frame.addMouseListener(new MouseAdapter(){


80. public void mouseClicked(MouseEvent me)
81. {
82. fontmenu.setPopupMenuVisible(false);
83. imagemenu.setPopupMenuVisible(false);
84. }
85. }
86. );
87.
88. menubar.add(imagemenu);
89. menubar.add(fontmenu);
90. frame.setJMenuBar(menubar);
91. frame.setLayout(new FlowLayout());
92. frame.add(fonttxt);
93. frame.add(addmenutxt);
94. Dimension dimension=new Dimension(600,30);
95. clearcmd.setPreferredSize(dimension);
96. frame.show();
97. }
98.
99.
100. public static void main(String args[])
101. {
102. MenuDemo md=new MenuDemo();
103. md.start();
104. }
105. /* Listener Section */
106.
107.
108. public void actionPerformed(ActionEvent ae)
109. {
110. System.out.println("1");
111. if (ae.getSource()==clearcmd)
112. imagemenu.doClick(2);
113. if ((ae.getSource()==fontcmb) || (ae.getSource()==sizecmb))

Page 513 of 660


Java Book - Chidambaram.S

114. {
115. System.out.println("2");
116. fontmenu.setPopupMenuVisible(false);
117. }
118. if ((ae.getSource()==combobox))
119. {
120. System.out.println("3");
121. imagemenu.setPopupMenuVisible(false);
122. }
123. }
124.
125. public void menuCanceled(MenuEvent e){
126. Component c=((JMenu)e.getSource()).getComponent();
127. c.setForeground(Color.blue);
128. }
129. public void menuDeselected(MenuEvent e){
130. Component c=((JMenu)e.getSource()).getComponent();
131. c.setForeground(Color.yellow);
132. }
133. public void menuSelected(MenuEvent e){
134. Component c=((JMenu)e.getSource()).getComponent();
135. c.setForeground(Color.red);
136. }
137.
138. public void popupMenuWillBecomeInvisible(PopupMenuEvent e){}
139. public void popupMenuCanceled(PopupMenuEvent e){}
140. public void popupMenuWillBecomeVisible(PopupMenuEvent ae)
141. {
142. System.out.println("popup 1");
143. if ((ae.getSource()==fontcmb) || (ae.getSource()==sizecmb))
144. {
145. System.out.println("popup 2");
146. fontmenu.setPopupMenuVisible(true);
147. }
148. if ((ae.getSource()==combobox))

Page 514 of 660


Java Book - Chidambaram.S

149. {
150. System.out.println("popup 3");
151. imagemenu.setPopupMenuVisible(true);
152. }
153. }
154. }

Output

Menu with Submenu

1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. import javax.swing.border.*;
5. class MenuDemo implements ActionListener
6. {
7. int x,y;

Page 515 of 660


Java Book - Chidambaram.S

8. JPanel panel;
9. Timer timer=new Timer(1000,this);
10. JFrame frame;
11. JMenuBar menubar;
12. JMenu coursemenu,feessubmenu;
13. JMenu feesmenu;
14. JMenuItem mcomitem;
15. JMenuItem mscitem;
16. JMenuItem mbaitem;
17. JCheckBoxMenuItem mcomfeesitem;
18. JMenuItem mscfeesitem;
19. JMenuItem mbafeesitem;
20. JMenuItem a,b,c,d;
21. Graphics g;
22. MenuDemo()
23. {
24. //timer.addActionListener(this);
25. timer.start();
26. objectCreator();
27. effectsProvider();
28. layoutProvider();
29. register();
30. addControlsToPanels();
31. addPanelsToJFrame();
32. jframeShow();
33. }
34. void objectCreator()
35. {
36. panel=new JPanel();
37. frame=new JFrame("Menu");
38. //g=frame.getGraphics();
39. menubar=new JMenuBar();
40. coursemenu=new JMenu("Course");
41. feesmenu=new JMenu("Fees");
42. feessubmenu=new JMenu("feessub");

Page 516 of 660


Java Book - Chidambaram.S

43. a=new JMenuItem("A");


44. b=new JMenuItem("B");
45. c=new JMenuItem("C");
46. d=new JMenuItem("D");
47. feessubmenu.add(a);
48. feessubmenu.add(b);
49. feessubmenu.add(c);
50. feessubmenu.add(d);
51. feesmenu.add(feessubmenu);
52. mcomitem=new JMenuItem("M.Com.,",65);
53. mbaitem=new JMenuItem("MBA");
54. mscitem=new JMenuItem("M.Sc.,");
55. mcomfeesitem=new JCheckBoxMenuItem("M.Com Fees.,",new ImageIcon("Ms.jpg"),
true);
56. mbafeesitem=new JMenuItem("MBA Fees");
57. mscfeesitem=new JMenuItem("M.Sc., Fees");
58. }
59. void effectsProvider()
60. {
61. coursemenu.add(mcomitem);
62. coursemenu.addSeparator();
63. coursemenu.add(mscitem);
64. coursemenu.addSeparator();
65. coursemenu.add(mbaitem);
66. coursemenu.addSeparator();
67. coursemenu.add(new JButton("Button"));
68. feesmenu.add(mcomfeesitem);
69. feesmenu.addSeparator();
70. feesmenu.add(mbafeesitem);
71. feesmenu.addSeparator();
72. feesmenu.add(mscfeesitem);
73. menubar.add(coursemenu);
74. feesmenu.addSeparator();
75. menubar.add(feesmenu);
76. }

Page 517 of 660


Java Book - Chidambaram.S

77.
78. void addControlsToPanels()
79. {
80. }
81. void addPanelsToJFrame()
82. {
83. frame.getContentPane().add(panel);
84. frame.setJMenuBar(menubar);
85. }
86. void register()
87. {
88. mbaitem.addActionListener(this);
89. mcomitem.addActionListener(this);
90. mscitem.addActionListener(this);
91. mcomfeesitem.addActionListener(this);
92. }
93.
94. public void actionPerformed(ActionEvent ae)
95. {
96. if (ae.getSource()==mcomitem)
97. System.out.println("Mcom is selected");
98.
99. if (ae.getSource()==mcomfeesitem)
100. {
101. if (mcomfeesitem.getState()==true)
102. System.out.println("Mcom Fees Item is selected");
103. else
104. System.out.println("Mcom Fees Item is deselected");
105. }
106. }
107.
108. void jframeShow()
109. {
110. //frame.setExtendedState(Frame.MAXIMIZED_BOTH);
111. frame.setSize(400,400);

Page 518 of 660


Java Book - Chidambaram.S

112. frame.show();
113. }
114. void layoutProvider()
115. {
116. }
117.
118. public static void main(String args[])
119. {
120. new MenuDemo();
121. }
122. }

Output

Page 519 of 660


Java Book - Chidambaram.S

Mouse Listener, MouseMotionListener Demonstration

1. import java.awt.*;
2. import java.awt.event.*;
3. import javax.swing.*;
4. class MouseEventDemo implements MouseListener,MouseMotionListener
5. {
6. JFrame frame=new JFrame("My Frame");
7. JButton okcmd=new JButton("Ok");
8. JButton cancelcmd=new JButton("Cancle");
9. MouseEventDemo()
10. {
11. frame.setLayout(new FlowLayout());
12. frame.add(okcmd);
13. frame.add(cancelcmd);
14. //frame.setExtendedState(Frame.MAXIMIZED_BOTH);
15. frame.setSize(300,300);
16. frame.show();
17. okcmd.addMouseListener(this);
18. cancelcmd.addMouseListener(this);
19. frame.addMouseMotionListener(this);
20. }
21. public void mouseExited(MouseEvent me)
22. {
23. Object obj=me.getSource();
24. JButton jb=(JButton)obj;
25. if (jb==okcmd)
26. jb.setBackground(Color.blue);
27. else
28. jb.setBackground(Color.yellow);
29. }
30. public void mousePressed(MouseEvent me)
31. {

Page 520 of 660


Java Book - Chidambaram.S

32.
33. }
34. public void mouseClicked(MouseEvent me)
35. {
36. }
37. public void mouseReleased(MouseEvent me)
38. {
39. }
40. public void mouseEntered(MouseEvent me)
41. {
42. Object obj=me.getSource();
43. JButton jb=(JButton)obj;
44. jb.setBackground(Color.red);
45. }
46. public void mouseDragged(MouseEvent me)
47. {
48. System.out.println("Dragged x="+me.getX());
49. System.out.println("Dragged y="+me.getY());
50. }
51. public void mouseMoved(MouseEvent me)
52. {
53. System.out.println("Moved x="+me.getX());
54. System.out.println("Moved y="+me.getY());
55. }
56. public static void main(String args[])
57. {
58. new MouseEventDemo();
59. }
60. }

Output

Moved x=23

Moved y=93

Page 521 of 660


Java Book - Chidambaram.S

Moved x=32

Moved y=96

Moved x=43

Moved y=96

Msgbox Demonstration

1. import javax.swing.*;
2. import javax.swing.event.*;
3. import java.awt.*;
4. import java.awt.event.*;
5. class MsgBox
6. {
7. JFrame frame=new JFrame("Message");

Page 522 of 660


Java Book - Chidambaram.S

8. JOptionPane pane;
9. MsgBox()
10. {
11. frame.setExtendedState(Frame.MAXIMIZED_BOTH);
12. frame.show();
13. /*pane=new JOptionPane("Are You Sure");
14. int result=pane.showConfirmDialog(frame,"Are We Sure","Confirm Dialog",JOp
tionPane.YES_NO_CANCEL_OPTION,JOptionPane.ERROR_MESSAGE);
15. System.out.println(result);
16. if (result==JOptionPane.YES_OPTION)
17. {
18. System.out.println("Yes is Pressed");
19. }
20. else if (result==JOptionPane.NO_OPTION)
21. {
22. System.out.println("NO is Pressed");
23. }
24. else if (result==JOptionPane.CANCEL_OPTION)
25. {
26. System.out.println("CANCEL is Pressed");
27. }
28.
29. result=pane.showConfirmDialog(frame,"Are We Sure","Confirm Dialog",JOption
Pane.YES_NO_OPTION);
30. System.out.println(result);
31. result=pane.showConfirmDialog(frame,"Are We Sure","Confirm Dialog",JOption
Pane.YES_NO_OPTION,JOptionPane.ERROR_MESSAGE);
32. System.out.println(result);
33. result=pane.showConfirmDialog(frame,"Are We Sure","Confirm Dialog",JOption
Pane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE);
34. System.out.println(result);
35. result=pane.showConfirmDialog(frame,"Are We Sure","Confirm Dialog",JOption
Pane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE);
36. System.out.println(result);

Page 523 of 660


Java Book - Chidambaram.S

37. result=pane.showConfirmDialog(frame,"Are We Sure","Confirm Dialog",JOption


Pane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
38. System.out.println(result);
39. result=pane.showConfirmDialog(frame,"Plain Message","Confirm Dialog",JOpti
onPane.YES_NO_OPTION,JOptionPane.PLAIN_MESSAGE);
40. System.out.println(result);
41. result=pane.showConfirmDialog(frame,"Plain Message","Confirm Dialog",JOpti
onPane.YES_NO_OPTION,JOptionPane.ERROR_MESSAGE,new ImageIcon("Ms.jpg"));
42. System.out.println(result); */
43.
44. String answer=pane.showInputDialog(frame,"Get The Salary");
45. System.out.println(answer);
46. answer=pane.showInputDialog(frame,"Enter The City","Dindigul");
47. System.out.println(answer);
48. answer=pane.showInputDialog(frame,"Get The Salary","From Soft & CO",JOptio
nPane.ERROR_MESSAGE);
49. System.out.println(answer);
50.
51. /*int result=pane.showInternalConfirmDialog(null,"Hai");
52. System.out.println(result);*/
53. }
54. public static void main(String args[])
55. {
56. new MsgBox();
57. }
58. }
59.
60. /* Yes - 0
61. No - 1
62. Cancel -2 */
63.
64.
65. /*
66. messageType -
an integer designating the kind of message this is; primarily used to determine

Page 524 of 660


Java Book - Chidambaram.S

the icon from the pluggable Look and Feel: ERROR_MESSAGE, INFORMATION_MESSAGE,
WARNING_MESSAGE, QUESTION_MESSAGE, or PLAIN_MESSAGE
67. */

Output

Password Field Demonstration

1. import javax.swing.*;
2. import javax.swing.event.*;
3. import java.awt.event.*;
4. import java.awt.*;
5. import java.io.*;
6.
7. class PasswordField extends JFrame implements ActionListener
8. {
9. Container con;

Page 525 of 660


Java Book - Chidambaram.S

10. JPasswordField passwordfield=new JPasswordField(20);


11. PasswordField()
12. {
13. con=getContentPane();
14. passwordfield.setEchoChar('?');
15. System.out.println(passwordfield.getEchoChar());
16. passwordfield.addActionListener(this);
17. con.setLayout(new FlowLayout());
18. con.add(passwordfield);
19. setExtendedState(Frame.MAXIMIZED_BOTH);
20. setVisible(true);
21. }
22. public void actionPerformed(ActionEvent ae)
23. {
24. System.out.println(passwordfield.getText());
25. }
26. public static void main(String args[])
27. {
28. new PasswordField();
29. }
30. }

Output

Page 526 of 660


Java Book - Chidambaram.S

Page 527 of 660


Java Book - Chidambaram.S

JPopup Menu Demonstration

1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. import javax.swing.border.*;
5. import java.applet.*;
6. import javax.swing.event.*;
7. class JPopupMenuDemo implements ActionListener
8. {
9. JPanel panel;
10. JTextArea jta;
11. JPopupMenu pop;
12. JFrame frame;
13. JMenu menu;
14. JMenuItem red=new JMenuItem("Red");
15. JMenuItem green=new JMenuItem("Green");
16. JMenuItem blue=new JMenuItem("Blue");
17. JPopupMenuDemo()
18. {
19. frame=new JFrame();
20. //pop=new JPopupMenu();
21. menu=new JMenu();
22. red.setName("red");
23. green.setName("green");
24. blue.setName("blue");
25. menu.add(green);
26. menu.addSeparator();
27. menu.add(red);
28. menu.addSeparator();
29. menu.add(blue);
30. pop=menu.getPopupMenu();
31. red.addActionListener(this);
32. green.addActionListener(this);

Page 528 of 660


Java Book - Chidambaram.S

33. blue.addActionListener(this);
34. frame.getContentPane().setLayout(new BorderLayout());
35. jta=new JTextArea();
36. panel=new JPanel();
37. panel.setLayout(new BorderLayout());
38. JScrollPane jsp=new JScrollPane(jta,ScrollPaneConstants.VERTICAL_SCROLLBAR
_ALWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
39. //panel.add(jsp,BorderLayout.CENTER);
40. frame.add(panel,BorderLayout.CENTER);
41. panel.addMouseListener(new MouseAdapter()
42. {
43. public void mouseClicked(MouseEvent me)
44. {
45. // To check right click
46. if (me.getModifiers()==InputEvent.BUTTON3_MASK)
47. {
48. pop.show(panel,me.getX(),me.getY());
49. }//if
50. }//method
51. }//inner class
52. );
53. frame.setExtendedState(Frame.MAXIMIZED_BOTH);
54. frame.show();
55. }
56. public void actionPerformed(ActionEvent ae)
57. {
58. String color=ae.getActionCommand();
59. System.out.println(color);
60. if (color.equals("Red"))
61. {
62. panel.setBackground(Color.blue);
63. }
64. else if (color.equals("Green"))
65. {
66. panel.setBackground(Color.green);

Page 529 of 660


Java Book - Chidambaram.S

67. }
68. else if (color.equals("Blue"))
69. {
70. panel.setBackground(Color.blue);
71. }
72. }
73. public void popupMenuWillBecomeVisible(PopupMenuEvent pe)
74. {
75. }
76. public void popupMenuCanceled(PopupMenuEvent e)
77. {
78. }
79. public static void main(String args[])
80. {
81. new JPopupMenuDemo();
82. }
83. }

Output

Page 530 of 660


Java Book - Chidambaram.S

ProgressBar Demonstration

1. import javax.swing.border.*;
2. import javax.swing.*;
3. import java.awt.*;
4. import java.awt.event.*;
5. import java.util.concurrent.*;
6. class ProgressBarDemo implements Runnable
7. {
8. JFrame frame;
9. JProgressBar progressbar;
10. Thread t;
11. JPanel panel1;
12. ProgressBarDemo()
13. {
14. objectCreator();
15. effectsProvider();
16. layoutProvider();
17. addControlsToPanels();
18. addPanelsToJFrame();
19. jframeShow();
20. t.start();
21. }
22. void effectsProvider()
23. {
24. panel1.setBorder(new TitledBorder("Progress Bar Demo"));
25. }
26. void objectCreator()
27. {
28. panel1=new JPanel();
29. frame=new JFrame("Progress Bar Demo");
30. progressbar=new JProgressBar(JProgressBar.HORIZONTAL,1,100);
31. progressbar.setStringPainted(true);
32. progressbar.setString("Progressing...");
33. t=new Thread(this);

Page 531 of 660


Java Book - Chidambaram.S

34. progressbar.setBorderPainted(true);
35. }
36. void addControlsToPanels()
37. {
38. panel1.add(progressbar);
39. }
40. void addPanelsToJFrame()
41. {
42. frame.getContentPane().add(panel1);
43. }
44. void layoutProvider()
45. {
46. panel1.setLayout(new FlowLayout(FlowLayout.CENTER));
47. frame.getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER));
48. }
49. public void run()
50. {
51. while (true)
52. {
53. try
54. {
55. Thread.sleep(50);
56. }
57. catch(Exception e){}
58. if (progressbar.getValue()<=100)
59. progressbar.setValue(progressbar.getValue()+1);
60. else
61. {
62. t=null;
63. frame.getContentPane().remove(progressbar);
64. }
65. }//while
66. }//method
67. void jframeShow()
68. {

Page 532 of 660


Java Book - Chidambaram.S

69. frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
70. frame.setVisible(true);
71. }
72. public static void main(String args[])
73. {
74. new ProgressBarDemo();
75. }

Output

Page 533 of 660


Java Book - Chidambaram.S

Screen Capturing using Robot

1. import java.awt.*;
2. import java.awt.image.*;
3. import javax.swing.*;
4. import com.sun.image.codec.jpeg.*;
5. import java.io.*;
6. public class RobotDemo implements Runnable
7. {
8. int i=0;
9. Robot robot;
10. RobotDemo()
11. {
12. try
13. {
14. robot=new Robot();
15. //robot.delay(100);
16. Thread t=new Thread(this);
17. t.start();
18. }
19. catch(Exception e){}
20. }
21. public void run()
22. {
23. try
24. {
25. while (true)
26. {
27. BufferedImage bi=robot.createScreenCapture(new Rectangle(8
00,600));
28. FileOutputStream fout=new FileOutputStream("a"+i+".jpg");

29. JPEGImageEncoder k=JPEGCodec.createJPEGEncoder(fout) ;


30. k.encode(bi);
31.

Page 534 of 660


Java Book - Chidambaram.S

32. fout.close();
33. i++;
34. Thread.sleep(5000);
35. }
36. }
37. catch(Exception e)
38. {
39. System.out.println(e);
40. }
41. }
42.
43. public static void main(String args[])
44. {
45. new RobotDemo();
46. }
47. }

Output

The .jpg files will be created…

Page 535 of 660


Java Book - Chidambaram.S

Scrollbar Demonstration

1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. import javax.swing.border.*;
5. class JScrollBarDemo implements AdjustmentListener,ActionListener
6. {
7. JFrame frame;
8. JTextField redtxt,bluetxt,greentxt;
9. JPanel northpanel,centerpanel,mainpanel,southpanel;
10. JLabel titlelbl,redlbl,greenlbl,bluelbl,previewlbl;
11. JScrollBar redscrollbar,greenscrollbar,bluescrollbar;
12. JButton applycmd;
13. int redvalue,greenvalue,bluevalue;
14. JScrollBarDemo()
15. {
16. objectCreator();
17. effectsProvider();
18. layoutProvider();
19. register();
20. addControlsToPanels();
21. addPanelsToJFrame();
22. jframeShow();
23. }
24.
25. void objectCreator()
26. {
27. titlelbl=new JLabel("JSCROLLBAR",JLabel.CENTER);
28. frame=new JFrame("Scrollbar demo");
29. redtxt=new JTextField(10);
30. greentxt=new JTextField(10);
31. bluetxt=new JTextField(10);
32. northpanel=new JPanel();
33. centerpanel=new JPanel();

Page 536 of 660


Java Book - Chidambaram.S

34. mainpanel=new JPanel();


35. southpanel=new JPanel();
36.
37. redscrollbar=new JScrollBar();
38. greenscrollbar=new JScrollBar();
39. bluescrollbar=new JScrollBar();
40. redscrollbar.setVisibleAmount(0); // To set tick size
41. redscrollbar.setMinimum(0);
42. greenscrollbar.setMinimum(0);
43. bluescrollbar.setMinimum(0);
44. redscrollbar.setMaximum(265);
45. bluescrollbar.setMaximum(265);
46. greenscrollbar.setMaximum(265);
47. redlbl=new JLabel("Red");
48. greenlbl=new JLabel("Green");
49. bluelbl=new JLabel("Blue");
50. previewlbl=new JLabel("preview");
51. applycmd=new JButton("Apply");
52.
53. }
54. void effectsProvider()
55. {
56. titlelbl.setForeground(new Color(97,125,222));
57. titlelbl.setFont(new Font("Arial",Font.BOLD,35));
58.
59. northpanel.setBorder(new LineBorder(Color.yellow));
60. centerpanel.setBorder(new LineBorder(Color.yellow));
61. southpanel.setBorder(new LineBorder(Color.yellow));
62.
63. northpanel.setBackground(new Color(26,20,100));
64. centerpanel.setBackground(new Color(26,20,100));
65. southpanel.setBackground(new Color(26,20,100));
66. redtxt.setEnabled(false);
67.
68. redlbl.setForeground(Color.red);

Page 537 of 660


Java Book - Chidambaram.S

69. greenlbl.setForeground(Color.green);
70. bluelbl.setForeground(Color.blue);
71. previewlbl.setForeground(Color.red);
72. applycmd.setForeground(Color.red);
applycmd.setBackground(Color.black);
73.
74. redlbl.setFont(new Font("Arial",Font.BOLD,16));
75. greenlbl.setFont(new Font("Arial",Font.BOLD,16));
76. bluelbl.setFont(new Font("Arial",Font.BOLD,16));
77. previewlbl.setFont(new Font("Arial",Font.BOLD,16));
78. applycmd.setFont(new Font("Arial",Font.BOLD,16));
79.
80.
81. //jsb.setMinimum(0);
82. //jsb.setMaximum(255);
83.
84.
85. // redscrollbar.setValue(255);
86. }
87. void addControlsToPanels()
88. {
89. northpanel.add(titlelbl,BorderLayout.CENTER);
90. centerpanel.add(redlbl);
91. centerpanel.add(greenlbl);
92. centerpanel.add(bluelbl);
93. centerpanel.add(redtxt);
94. centerpanel.add(greentxt);
95. centerpanel.add(bluetxt);
96. centerpanel.add(redscrollbar);
97. centerpanel.add(greenscrollbar);
98. centerpanel.add(bluescrollbar);
99.
100. southpanel.add(previewlbl,BorderLayout.WEST);
101. previewlbl.setBorder(new BevelBorder(BevelBorder.LOWERED));
102. southpanel.add(applycmd,BorderLayout.EAST);

Page 538 of 660


Java Book - Chidambaram.S

103.
104. mainpanel.add(northpanel,BorderLayout.NORTH);
105. mainpanel.add(centerpanel,BorderLayout.CENTER);
106. mainpanel.add(southpanel,BorderLayout.SOUTH);
107.
108. }
109. void addPanelsToJFrame()
110. {
111. frame.add(mainpanel,BorderLayout.CENTER);
112. redscrollbar.setPreferredSize(new Dimension(50,200));
113. greenscrollbar.setPreferredSize(new Dimension(50,200));
114. bluescrollbar.setPreferredSize(new Dimension(50,200));
115.
116. }
117. void register()
118. {
119. applycmd.addActionListener(this);
120. redscrollbar.addAdjustmentListener(this);
121. greenscrollbar.addAdjustmentListener(this);
122. bluescrollbar.addAdjustmentListener(this);
123. }
124. void jframeShow()
125. {
126. frame.setSize(750,600);
127. frame.show();
128.
129. }
130. void layoutProvider()
131. {
132. frame.getContentPane().setLayout(new BorderLayout());
133. mainpanel.setLayout(new BorderLayout());
134. northpanel.setLayout(new BorderLayout());
135. centerpanel.setLayout(new FlowLayout(FlowLayout.CENTER,90,30));
136. southpanel.setLayout(new BorderLayout());
137. }

Page 539 of 660


Java Book - Chidambaram.S

138.
139.
140. public void adjustmentValueChanged(AdjustmentEvent ae)
141. {
142. if (ae.getSource()==redscrollbar)
143. {
144. redlbl.setForeground(new Color(redscrollbar.getValue(),0,0));

145. previewlbl.setForeground(new Color(redscrollbar.getValue(),gre


enscrollbar.getValue(),bluescrollbar.getValue()));
146. redvalue=redscrollbar.getValue();
147. redtxt.setText("Red:"+redvalue);
148. }
149. else if (((JScrollBar)(ae.getSource()))==bluescrollbar)
150. {
151. bluevalue=bluescrollbar.getValue();
152. bluelbl.setForeground(new Color(0,0,bluescrollbar.getValue()))
;
153. previewlbl.setForeground(new Color(redscrollbar.getValue(),gre
enscrollbar.getValue(),bluescrollbar.getValue()));
154. bluetxt.setText("Blue:"+bluevalue);
155. }
156.
157. else if (((JScrollBar)(ae.getSource()))==greenscrollbar)
158. {
159. greenvalue=greenscrollbar.getValue();
160. greenlbl.setForeground(new Color(0,greenscrollbar.getValue(),0
));
161. previewlbl.setForeground(new Color(redscrollbar.getValue(),gre
enscrollbar.getValue(),bluescrollbar.getValue()));
162. greentxt.setText("Green:"+greenvalue);
163. }//if
164.
165. }//method
166. public void actionPerformed(ActionEvent ea)

Page 540 of 660


Java Book - Chidambaram.S

167. {
168. String caption=ea.getActionCommand();
169. if (caption.equals("Apply"))
170. {
171. northpanel.setBackground(new Color(redvalue,greenvalue,blueval
ue));
172.
173. southpanel.setBackground(new Color(redvalue,greenvalue,blueval
ue));
174.
175. centerpanel.setBackground(new Color(redvalue,greenvalue,blueva
lue));
176. }//if
177. }//method
178.
179.
180.
181. public static void main(String args[])
182. {
183.
184. JScrollBarDemo jsb=new JScrollBarDemo();
185. }
186. }

Page 541 of 660


Java Book - Chidambaram.S

Button with key Events

1. /*CTRL = 18
2. SHIFT =17
3. ALT =24
4. */
5. import java.awt.*;
6. import java.awt.event.*;
7. import javax.swing.*;
8. class First implements ActionListener
9. {
10. JFrame frame;
11. JButton cmd;
12. First()
13. {
14. frame=new JFrame("My Frame");
15. cmd=new JButton("Click");
16. frame.setLayout(new FlowLayout());
17. frame.add(cmd);
18. cmd.addActionListener(this);
19. frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
20. frame.show();
21. }
22.
23. public static void main(String args[])
24. {
25. First f=new First();
26. //first f1=new First();
27. }
28. public void actionPerformed(ActionEvent ae)
29. {
30. System.out.println("Action Event Raised"+ae.getActionCommand());
31. System.out.println("getModifiers="+ae.getModifiers());
32. if (ae.getModifiers()==24)
33. System.out.println("Alt Key Pressed");

Page 542 of 660


Java Book - Chidambaram.S

34. else if (ae.getModifiers()==18)


35. System.out.println("CTRL Key Pressed");
36. else if (ae.getModifiers()==17)
37. System.out.println("Shift Key Pressed");
38. else
39. System.out.println("Mouse Pressed");
40. }
41. }

Output

Action Event RaisedClick

getModifiers=16

Mouse Pressed

Action Event RaisedClick

getModifiers=18

CTRL Key Pressed

Page 543 of 660


Java Book - Chidambaram.S

Action Event RaisedClick

getModifiers=24

Alt Key Pressed

Action Event RaisedClick

getModifiers=17

Shift Key Pressed

JSlider Demonstration

1. import javax.swing.*;
2. import java.awt.*;
3. import javax.swing.event.*;
4. import java.awt.event.*;
5. import javax.swing.border.*;
6. class Slider implements ChangeListener
7. {
8. JFrame frame;
9. JPanel panel;
10. JSlider slider1,slider2,slider3;
11. JLabel redlbl,greenlbl,bluelbl;
12. JPanel redpanel,greenpanel,bluepanel;
13. Slider()
14. {
15. redpanel=new JPanel();
16. greenpanel=new JPanel();
17. bluepanel=new JPanel();
18. redlbl=new JLabel();
19. greenlbl=new JLabel();
20. bluelbl=new JLabel();
21. slider1=new JSlider();
22. slider2=new JSlider(0,255,1);
23. slider3=new JSlider(SwingConstants.VERTICAL,0,255,1);
24. slider1.addChangeListener(this);

Page 544 of 660


Java Book - Chidambaram.S

25. slider2.addChangeListener(this);
26. slider3.addChangeListener(this);
27. panel=new JPanel();
28. frame=new JFrame();
29. frame.getContentPane().setLayout(new BorderLayout());
30. panel.setLayout(new FlowLayout(FlowLayout.CENTER,50,100));
31. redlbl.setForeground(Color.white);
32. bluelbl.setForeground(Color.white);
33. greenlbl.setForeground(Color.white);
34. redlbl.setFont(new Font("Arial",Font.BOLD,20));
35. greenlbl.setFont(new Font("Arial",Font.BOLD,20));
36. bluelbl.setFont(new Font("Arial",Font.BOLD,20));
37. redpanel.add(redlbl);
38. greenpanel.add(greenlbl);
39. bluepanel.add(bluelbl);
40. redpanel.setBorder(new LineBorder(Color.red));
41. greenpanel.setBorder(new LineBorder(Color.red));
42. bluepanel.setBorder(new LineBorder(Color.red));
43. panel.add(redpanel);
44. panel.add(slider1);
45. panel.add(greenpanel);
46. panel.add(slider2);
47. panel.add(bluepanel);
48. panel.add(slider3);
49. frame.getContentPane().add(panel);
50. frame.setSize(500,500);
51. frame.show();
52. }
53. public void stateChanged(ChangeEvent ce)
54. {
55. int r=0;
56. int g=0;
57. int b=0;
58. if (ce.getSource()==slider1)
59. {

Page 545 of 660


Java Book - Chidambaram.S

60. redlbl.setText(Integer.toString(slider1.getValue()));
61. redpanel.setBackground(new Color(slider1.getValue(),0,0));
62. }
63. else if (((JSlider)(ce.getSource()))==slider2)
64. {
65. greenlbl.setText(Integer.toString(slider2.getValue()));
66. greenpanel.setBackground(new Color(0,slider2.getValue(),0));
67. }
68. else if (((JSlider)(ce.getSource()))==slider3)
69. {
70. bluelbl.setText(Integer.toString(slider3.getValue()));
71. bluepanel.setBackground(new Color(0,0,slider3.getValue()));
72. }
73. panel.setBackground(new Color(slider1.getValue(),slider2.getValue(),slider
3.getValue()));
74. }
75. public static void main(String args[])
76. {
77. new Slider();
78. }
79. }

Output

Page 546 of 660


Java Book - Chidambaram.S

Page 547 of 660


Java Book - Chidambaram.S

JTable Demonstration

1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. import javax.swing.border.*;
5. import javax.swing.event.*;
6. class TableDemo implements ListSelectionListener
7. {
8. JFrame frame;
9. JTable table;
10. JScrollPane jsp;
11. JLabel titlelbl;
12. int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
13. int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
14. JPanel p1,p2;
15. TableDemo()
16. {
17. objectCreator();
18. effectsProvider();
19. layoutProvider();
20. register();
21. addControlsToPanels();
22. addPanelsToJFrame();
23. jframeShow();
24. }
25.
26. void objectCreator()
27. {
28. frame=new JFrame("Table");
29. String data[][]={{"Rama.A","55","50"},{"Raja.B","65","60"},{"Ragava.A","55
","50"}};
30. String column[]={"Name","Tamil","English"};
31. table=new JTable(data,column);
32. jsp=new JScrollPane(table,v,h);

Page 548 of 660


Java Book - Chidambaram.S

33. p1=new JPanel();


34. p2=new JPanel();
35. titlelbl=new JLabel("Table Demonstration");
36. table.setRowSelectionAllowed(false);
37. table.setColumnSelectionAllowed(true);
38. table.moveColumn(0,2);
39. }
40. void effectsProvider()
41. {
42. p1.setBorder(new LineBorder(Color.red,5));
43. p2.setBorder(new LineBorder(Color.red,5));
44. titlelbl.setFont(new Font("Arial",Font.BOLD|Font.ITALIC,20));
45. titlelbl.setBorder(new LineBorder(Color.red,5));
46. titlelbl.setForeground(new Color(97,125,222));
47. p1.setBackground(new Color(26,87,123));
48. p2.setBackground(new Color(26,87,123));
49. titlelbl.setBackground(new Color(26,87,123));
50. table.setBackground(new Color(26,87,123));
51. table.setForeground(new Color(97,125,222));
52. table.setRowMargin(50);
53. table.setRowHeight(100);
54. }
55. void addControlsToPanels()
56. {
57. p1.add(titlelbl);
58. p2.add(jsp,BorderLayout.CENTER);
59. }
60. void addPanelsToJFrame()
61. {
62. frame.getContentPane().add(p1,BorderLayout.NORTH);
63. frame.getContentPane().add(p2,BorderLayout.CENTER);
64. }
65. void register()
66. {
67. try

Page 549 of 660


Java Book - Chidambaram.S

68. {
69. table.print();
70. }
71. catch(Exception e){}
72. //table.addListSelectionListener(this);
73. }
74. void jframeShow()
75. {
76. frame.setExtendedState(Frame.MAXIMIZED_BOTH);
77. frame.show();
78. /*try
79. {
80. table.print();
81. }
82. catch(Exception e){}*/
83. }
84. void layoutProvider()
85. {
86. p2.setLayout(new BorderLayout());
87. p1.setLayout(new FlowLayout(FlowLayout.CENTER));
88. frame.getContentPane().setLayout(new BorderLayout());
89. }
90. public void valueChanged(ListSelectionEvent ce)
91. {
92. JTable jt=(JTable)ce.getSource();
93. int rowno=jt.getSelectedRow();
94. System.out.println(jt.getValueAt(rowno,0).toString());
95. }
96. public static void main(String args[])
97. {
98. new TableDemo();
99. }
100. }

Output

Page 550 of 660


Java Book - Chidambaram.S

JToolBar Demonstration

1. import java.awt.*;
2. import javax.swing.*;
3. class JToolBarDemo
4. {
5. public static void main(String args[])
6. {
7. JFrame jframe=new JFrame();
8. jframe.setExtendedState(Frame.MAXIMIZED_BOTH);
9. JToolBar jtoolbar=new JToolBar("Name",JToolBar.HORIZONTAL);
10. jtoolbar.setLayout(new FlowLayout(FlowLayout.CENTER,0,0));
11. for (int i=0;i<10;i++)
12. {
13. jtoolbar.add(new JButton("Button "+i));
14. jtoolbar.addSeparator();
15. }

Page 551 of 660


Java Book - Chidambaram.S

16. jframe.setLayout(new FlowLayout());


17. jtoolbar.setFloatable(true);
18. jframe.add(jtoolbar);
19. jframe.show();
20. }
21. }

Output

Page 552 of 660


Java Book - Chidambaram.S

Chapter 35 - Applet

In java to develop GUI application there are two types of window available.

Frame

Applet

Frame can be used in Desktop Application, Network Application

Applet can be used in web application.

In simple words, applet is the interfacing tool between web development and
swing. It means swing functionalities can be applied by using applet in web.

All swing functionalities can be applied in applet(some features are restricted


by JRE because of security problem) and applet can be called from html or jsp
page.

The main reason is that applet is highly secured tool, because sun assures
applet cannot make any changes in client machine. Because applet is used in
web.

javax.swing.JApplet extends java.applet.Applet

Applet Program Creation

Each one Applet class must be the sub class of java.applet.Applet or


javax.swing.JApplet.

Main() is not allowed in applet program.

Each one applet program must have following html tab to run applet in
appletviewer tool

<applet code=”AppletClassName” width=400 height=400>

Page 553 of 660


Java Book - Chidambaram.S

</applet>

After creating applet program it can be run in two ways

using appletviewer tool

call applet from html page

applet viewer

Open command prompt

Type

appletviewer <filename>.java

Now you will get applet window

Html calling

To do this you must separate html page with appletviewer tag.

So applet program should be compiled separately and html file should be created
separately. Then you can run html page and view the output in browser.

Note:

The default layout of applet is FlowLayout.

Arranging controls in applet is similar to arranging controls in Frame.

Life Cycle methods of Applet

public void init()

This method will be called when applet is initialized in memory. This method is
called only once.

public void start()

Page 554 of 660


Java Book - Chidambaram.S

When applet is shown in screen and after the applet is loaded and initialized.
And it is called when the user returns to the HTML page that contains the
applet after browsing through other webpages.

public void stop()

When applet is minimized or goes to back in browser.

public void destroy()

When applet is destroyed(closed)

public void paint(Graphics g)

when runtime needs draw in applet.

Except paint() other methods are in Applet class

paint() is java.awt.Component class

Graphics is the class of java.awt package.

Applet Tag

Applet tag comes from Html

Compulsory attributes are

Code – To specify the class file

Width – specify the width of applet

Height – specify the height of applet

Optional attributes are

Codebase – specify the folder path of applet, if applet class and html file are
in different folder.

Page 555 of 660


Java Book - Chidambaram.S

Alt – Alternate text, if applet is not supported by browser.

Align – Alignment of applet

(Left,Right,Top,Bottom)

Vspace=pixels – Vertical space.

Hspace=pixels – Horizontal space.

Ex. Codebase

<applet codebase="H:\GTNJava\swing\Applet\FirstApplet" code="FirstApplet"


width=200 height=200>

</applet>

Example program using JApplet

Keyboard events JApplet with JFrame

1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. import java.applet.*;
5. /* <applet code="KeyEventsDemo" width=500 height=500>
6. </applet> */
7. public class KeyEventsDemo extends Applet implements KeyListener,MouseListener,M
ouseMotionListener
8. {
9. int x,y;
10. JFrame jf;
11. String msg="";
12. public void init()
13. {
14. objectCreator();
15. effectsProvider();

Page 556 of 660


Java Book - Chidambaram.S

16. register();
17. layoutProvider();
18. addControlsToJFrame();
19. //showJFrame();
20. setBackground(Color.red);
21. requestFocus();
22. }
23. public void register()
24. {
25. addKeyListener(this);
26. addMouseListener(this);
27. addMouseMotionListener(this);
28. }
29. public void mouseEntered(MouseEvent me)
30. {
31. showStatus("Mouse Entered into Frame");
32. msg="Mouse is in x="+me.getX()+"y="+me.getY();
33. repaint();
34. }
35. public void mouseExited(MouseEvent me)
36. {
37. showStatus("Mouse Exited into Frame");
38. }
39. public void mousePressed(MouseEvent me)
40. {
41. showStatus("Mouse Pressed into Frame");
42. msg="Mouse is in x="+me.getX()+"y="+me.getY();
43. repaint();
44. }
45. public void mouseReleased(MouseEvent me)
46. {
47. showStatus("Mouse Released into Frame");
48. msg="Mouse is in x="+me.getX()+"y="+me.getY();
49. repaint();
50. }

Page 557 of 660


Java Book - Chidambaram.S

51. public void mouseClicked(MouseEvent me)


52. {
53. showStatus("Mouse Clicked into Frame");
54. msg="Mouse is in x="+me.getX()+"y="+me.getY();
55. repaint();
56. }
57.
58. public void keyPressed(KeyEvent ke)
59. {
60. System.out.println("From Key Pressed getKeyCode()="+ke.getKeyCode());
61. System.out.println("From key Pressed getKeyChar()="+ke.getKeyChar());
62. if (ke.getKeyCode()==ke.VK_HOME)
63. {
64. msg="Home Key Pressed";
65. repaint();
66. }
67. if (ke.getKeyCode()==ke.VK_END)
68. {
69. msg="End Key Pressed";
70. repaint();
71. }
72.
73. if (ke.getKeyCode()==ke.VK_PAGE_UP)
74. {
75. msg="Page Up Key Pressed";
76. repaint();
77. }
78. }
79. public void keyReleased(KeyEvent ke)
80. {
81. System.out.println("Key Released getKeyCode()="+ke.getKeyCode());
82. System.out.println("Key Released getKeyChar()"+ke.getKeyChar());
83. }
84.
85. public void mouseDragged(MouseEvent me)

Page 558 of 660


Java Book - Chidambaram.S

86. {
87. x=me.getX();
88. y=me.getY();
89. msg="Mouse Dragged"+"x="+x+"y="+y;
90. repaint();
91. }
92. public void mouseMoved(MouseEvent me)
93. {
94. x=me.getX();
95. y=me.getY();
96. msg="Mouse Moved "+"x="+x+"y="+y;
97. repaint();
98. }
99.
100. public void keyTyped(KeyEvent ke)
101. {
102. msg=ke.getKeyChar()+" is pressed";
103. System.out.println("From key Typed getKeyChar() ="+msg);
104. System.out.println("From Key Typed getKeyCode()="+ke.getKeyCode());
105. repaint();
106. }
107.
108. void objectCreator()
109. {
110. jf=new JFrame("Key Board Events");
111. }
112. void effectsProvider()
113. {
114. jf.setSize(600,500);
115. }
116. void layoutProvider()
117. {
118.
119. }
120. void addControlsToJFrame()

Page 559 of 660


Java Book - Chidambaram.S

121. {
122.
123. }
124. /*void showJFrame()
125. {
126. jf.setSize(500,400);
127. jf.show();
128. }*/
129. /*public static void main(String args[])
130. {
131. KeyEventsDemo ked=new KeyEventsDemo();
132. }*/
133. public void paint(Graphics g)
134. {
135. g.drawString(msg,x,y);
136. }
137. }

Output

Page 560 of 660


Java Book - Chidambaram.S

JTree Demonstration with Applet

1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. import javax.swing.border.*;
5. import javax.swing.tree.*;
6. import java.util.*;
7. /*
8. <applet code="TreeDemo" width=800 height=500>
9. </applet>
10. */
11.
12. public class TreeDemo extends JApplet
13. {
14. JTree tree;
15. JTextField jtf;
16. public void init()
17. {
18. setLayout(new BorderLayout());
19. DefaultMutableTreeNode top=new DefaultMutableTreeNode("Top");
20. DefaultMutableTreeNode courses=new DefaultMutableTreeNode("Courses");
21. top.add(courses);
22. DefaultMutableTreeNode mcom=new DefaultMutableTreeNode("M.Com.,");
23. courses.add(mcom);
24. DefaultMutableTreeNode msc=new DefaultMutableTreeNode("M.Sc.,");
25. courses.add(msc);
26. DefaultMutableTreeNode mba=new DefaultMutableTreeNode("MBA");
27. courses.add(mba);
28.
29. DefaultMutableTreeNode fees=new DefaultMutableTreeNode("Fees");
30. top.add(fees);

Page 561 of 660


Java Book - Chidambaram.S

31. DefaultMutableTreeNode mcomfees=new DefaultMutableTreeNode("M.Com., Fees")


;
32. fees.add(mcomfees);
33. DefaultMutableTreeNode mscfees=new DefaultMutableTreeNode("M.Sc., Fees");

34. fees.add(mscfees);
35. DefaultMutableTreeNode mbafees=new DefaultMutableTreeNode("MBA Fees");
36. fees.add(mbafees);
37.
38. /*DefaultMutableTreeNode top1=new DefaultMutableTreeNode("Top");
39. DefaultMutableTreeNode courses1=new DefaultMutableTreeNode("Courses");
40. top1.add(courses1);
41. DefaultMutableTreeNode mcom1=new DefaultMutableTreeNode("M.Com.,");
42. courses.add(mcom1);
43. DefaultMutableTreeNode msc1=new DefaultMutableTreeNode("M.Sc.,");
44. courses.add(msc1);
45. DefaultMutableTreeNode mba1=new DefaultMutableTreeNode("MBA");
46. courses.add(mba1);
47.
48. DefaultMutableTreeNode fees1=new DefaultMutableTreeNode("Fees");
49. top1.add(fees1);
50. DefaultMutableTreeNode mcomfees1=new DefaultMutableTreeNode("M.Com., Fees"
);
51. fees1.add(mcomfees1);
52. DefaultMutableTreeNode mscfees1=new DefaultMutableTreeNode("M.Sc., Fees");

53. fees1.add(mscfees1);
54. DefaultMutableTreeNode mbafees1=new DefaultMutableTreeNode("MBA Fees");
55. fees1.add(mbafees1);
56. Vector vector=new Vector();
57. vector.addElement(top);
58. vector.addElement(top1);*/
59.
60. tree=new JTree(top);
61.

Page 562 of 660


Java Book - Chidambaram.S

62. int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;


63. int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
64.
65. JScrollPane jsp=new JScrollPane(tree,v,h);
66. add(jsp,BorderLayout.CENTER);
67. jtf=new JTextField("",20);
68. add(jtf,BorderLayout.NORTH);
69. tree.addMouseListener(new MouseAdapter()
70. {
71. public void mouseClicked(MouseEvent me)
72. {
73. TreePath tp=tree.getPathForLocation(me.getX(),me.getY());
74. if (tp!=null)
75. jtf.setText(tp.toString());
76. else
77. jtf.setText("");
78. }
79. });
80. }//init
81. }//class

Output

Page 563 of 660


Java Book - Chidambaram.S

Applet with Images

1. import java.awt.*;
2. import javax.swing.*;
3. import java.applet.*;
4. /* <applet code="ImageDemo" width=600 height=600>
5. </applet>
6. */
7. public class ImageDemo extends Applet
8. {
9. JPanel jp;
10. JLabel jl;
11. Image img;
12. public void init()
13. {
14. jp=new JPanel();
15. img=getImage(getDocumentBase(),"Wave.jpg");
16. jl=new JLabel(new ImageIcon(img));
17. jp.add(jl);

Page 564 of 660


Java Book - Chidambaram.S

18. add(jp,BorderLayout.CENTER);
19. jp.setPreferredSize(new Dimension(500,500));
20. }
21. }

Output

Page 565 of 660


Java Book - Chidambaram.S

JTabbedPane Demonstration

1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. import javax.swing.event.*;
5. import java.util.*;
6. /* <applet code="TabbedPane" width=600 height=600>
7. </applet> */
8.
9. public class TabbedPane extends JApplet implements ChangeListener
10. {
11. JTabbedPane jtp=new JTabbedPane();
12. JPanel firstpanel=new JPanel();
13. JPanel secondpanel=new JPanel();
14. JPanel thirdpanel=new JPanel();
15. JScrollPane jsp1,jsp2,jsp3;
16. JList fontnamelist;
17. JList fontsizelist;
18. JList fontstylelist;
19. GraphicsEnvironment ge;
20. public void init()
21. {
22. ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
23. String fontnames[]=ge.getAvailableFontFamilyNames();
24. fontnamelist=new JList(fontnames);
25. String style[]={"Bold","Italic","BoldItalic","Normal"};
26. fontstylelist=new JList(style);
27. Vector v=new Vector();
28. for (int i=8;i<=100;i+=2)
29. v.addElement(i);
30. fontsizelist=new JList(v);
31. setLayout(new BorderLayout());
32. jsp1=new JScrollPane(fontnamelist,ScrollPaneConstants.VERTICAL_SCROLLBAR_A
LWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);

Page 566 of 660


Java Book - Chidambaram.S

33. jsp2=new JScrollPane(fontstylelist,ScrollPaneConstants.VERTICAL_SCROLLBAR_


ALWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
34. jsp3=new JScrollPane(fontsizelist,ScrollPaneConstants.VERTICAL_SCROLLBAR_A
LWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
35. firstpanel.setLayout(new FlowLayout(FlowLayout.CENTER,50,50));
36. secondpanel.setLayout(new FlowLayout(FlowLayout.CENTER,50,50));
37. thirdpanel.setLayout(new FlowLayout(FlowLayout.CENTER,50,50));
38. firstpanel.add(jsp1);
39. firstpanel.add(jsp2);
40. firstpanel.add(jsp3);
41. jtp.add(firstpanel,"Formatting");
42. jtp.add(secondpanel,"Color");
43. jtp.add(thirdpanel,"Image");
44. add(jtp);
45. jtp.addChangeListener(this);
46. jtp.addMouseListener(new MouseAdapter()
47. {
48. public void mouseClicked(MouseEvent me)
49. {
50. System.out.println("Mouse Clicked");
51. JTabbedPane jtabbedpane=(JTabbedPane)me.getSource();
52. int ind=jtabbedpane.indexAtLocation(me.getX(),me.getY());
53. jtabbedpane.setBackgroundAt(ind,Color.red);
54. jtabbedpane.setForegroundAt(ind,Color.blue);
55. String str=jtabbedpane.getTitleAt(ind);
56. System.out.println("="+str+"index="+ind);
57. }//method
58. }//class
59. );
60. }//method
61.
62. public void stateChanged(ChangeEvent ce)
63. {
64. }
65. }

Page 567 of 660


Java Book - Chidambaram.S

Output

Page 568 of 660


Java Book - Chidambaram.S

Chapter 36 - Java 7 features

Binary Literals

This option enables us to assign binary numbers to integral types


byte, short, int, and long. To specify a binary literal, add the
prefix 0b or 0B to the number. The following examples show binary literals

byte aByte = (byte)0b00100001;

short aShort = (short)0b1010000101000101;

int anInt3 = 0B101; // The B can be upper or lower case.

Let's see the example below

1. public class BinaryLiteralsDemo1 {


2.
3. public static void main(String rgs[])
4. {
5. // An 8-bit 'byte' value:
6. byte aByte = (byte)0b0010;
7.
8. // A 16-bit 'short' value:
9. short aShort = (short)0b101001;
10.
11. // Some 32-bit 'int' values:
12. int anInt1 = 0b101;
13. int anInt2 = 0B101; // The B can be upper or lower case.
14.
15. // A 64-bit 'long' value. Note the "L" suffix:
16. long aLong = 0b10100001L;

Page 569 of 660


Java Book - Chidambaram.S

17.
18. System.out.println("aByte="+aByte);
19. System.out.println("aShort="+aShort);
20. System.out.println("anInt1="+anInt1);
21. System.out.println("anInt2="+anInt2);
22. System.out.println("aLong="+aLong);
23. }
24. }
25.
26. Output
27.
28. aByte=2
29. aShort=41
30. anInt1=5
31. anInt2=5
32. aLong=161

Underscores in Numeric Literals

Any number of underscore characters (_) can appear anywhere between digits in a
numerical literal to separate digits in groups to understand better.

long creditCardNumber = 1234_5678_9012_3456L;

long socialSecurityNumber = 999_99_9999L;

float pi = 3.14_15F;

Page 570 of 660


Java Book - Chidambaram.S

String in Switch

Before 1.7, only integral literals(int,short,byte and long) could be used.

We can use String in switch statement. Runtime checks the string literals
equality using String.equals().

1. public class StringInSwitch {


2. public static void main(String args[])
3. {
4. String typeOfDay;
5. String dayOfWeekArg="Monday";
6. switch (dayOfWeekArg) {
7. case "Monday":
8. typeOfDay = "Start of work week";
9. break;
10. case "Tuesday":
11. case "Wednesday":
12. case "Thursday":
13. typeOfDay = "Midweek";
14. break;
15. case "Friday":
16. typeOfDay = "End of work week";
17. break;
18. case "Saturday":
19. case "Sunday":
20. typeOfDay = "Weekend";
21. break;
22. default:
23. throw new IllegalArgumentException("Invalid day of the week: "
+ dayOfWeekArg);
24. }
25. System.out.println(typeOfDay);
26. }
27.

Page 571 of 660


Java Book - Chidambaram.S

28. }
29.
30. Output:
31.
32. Start of work week

Type Inference for Generic Instance Creation


Map<String, List<String>> myMap = new HashMap<String, List<String>>(); \\before 1.7

Map<String, List<String>> myMap1 = new HashMap<>(); \\since 1.7

Since 1.7, type inference in right side not required. Note that diamond
operator <> must be specified in right side. Otherwise compiler throws warning
"HashMap is a raw type. References to generic type HashMap<K,V> should be
parameterized"

try with resources

try with resources closes an object declared within try automatically when try
block is completed or try block is exited even abruptly.

Prior 1.7 Example

BufferedReader br = new BufferedReader(new FileReader(path));

try {

return br.readLine();

} finally {

if (br != null) br.close();

Page 572 of 660


Java Book - Chidambaram.S

1.7 Example

try (BufferedReader br = new BufferedReader(new FileReader(path))) {

return br.readLine();

In above example br is a resource and will be closed after the try block by
runtime. The resource must be the subclass of java.lang.AutoCloseable
interface(added in 1.7).

The object must be completely declared and used within try block. This is the
drawback of this feature.

So prior 1.7 example would be better if we want to use an object declared


outside of try block.

Handling More Than One Type of Exception

In Java SE 7 and later, a single catch block can handle more than one type of
exception. This feature can reduce code duplication.

Prior 1.7 Example

try

//statements

catch (IOException ex) {

logger.log(ex);

Page 573 of 660


Java Book - Chidambaram.S

throw ex;

catch (SQLException ex) {

logger.log(ex);

throw ex;

Since 1.7 Example

try

//statements

catch (IOException|SQLException ex) {

logger.log(ex);

throw ex;

throw in 1.7

Example 1

1. public class RethrowExceptionDemo {


2.

Page 574 of 660


Java Book - Chidambaram.S

3. void m1()
4. {
5. try {
6. throw new ArrayIndexOutOfBoundsException();
7. } catch (Exception e) {
8. System.out.println("m1=" + e.getClass().getName());
9. }
10.
11. }
12.
13. public static void main(String[] args) {
14. // TODO Auto-generated method stub
15. try {
16. RethrowExceptionDemo rethrowExceptionDemo = new RethrowExcepti
onDemo();
17. rethrowExceptionDemo.m1();
18.
19. } catch (Exception e) {
20. System.out.println(e.getClass().getName());
21. }
22.
23. }
24. }
25.
26. Output :
27.
28. m1=java.lang.ArrayIndexOutOfBoundsException

Example 2

1. public class RethrowExceptionDemo {


2.
3. void m1()
4. {

Page 575 of 660


Java Book - Chidambaram.S

5. throw new ArrayIndexOutOfBoundsException();


6. }
7.
8. public static void main(String[] args) {
9. // TODO Auto-generated method stub
10. try {
11. RethrowExceptionDemo rethrowExceptionDemo = new RethrowExcepti
onDemo();
12. rethrowExceptionDemo.m1();
13.
14. } catch (Exception e) {
15. System.out.println(e.getClass().getName());
16. }
17.
18. }
19.
20. }
21.
22. Output:
23.
24. java.lang.ArrayIndexOutOfBoundsException

In Example 1, the same method catches the exception thrown by try block.

In Example 2, the same method doesn't have the catch block so the caller catch
catches the exception thrown method.

In Example 3, there is no catch in the same method and caller so runtime catche
s the exception.

Example 3:

1. public class RethrowExceptionDemo {

Page 576 of 660


Java Book - Chidambaram.S

2.
3. void m1() {
4. throw new ArrayIndexOutOfBoundsException();
5. }
6.
7. public static void main(String[] args) {
8. // TODO Auto-generated method stub
9.
10. RethrowExceptionDemo rethrowExceptionDemo = new RethrowExceptionDe
mo();
11. rethrowExceptionDemo.m1();
12.
13. }
14.
15. }
16.
17. Output:
18.
19. Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
20. at com.book.java7.prgs.RethrowExceptionDemo.m1(RethrowExceptionDemo.ja
va:6)
21. at com.book.java7.prgs.RethrowExceptionDemo.main(RethrowExceptionDemo.
java:13)

Page 577 of 660


Java Book - Chidambaram.S

Chapter 37 Java 8 Features

It is the first LTS(Long Term Support Version), released at March 2014. Its
support details as below.

January 2019 for Oracle (commercial)


December 2020 for Oracle (personal use)
At least September 2023 for AdoptOpenJDK

Extended support until March 2025

Lets start the features of JDK 8.

Method References

Method references is the feature to create the reference for static method.

Lets see about the syntax and example program below.

Method Reference Syntax

ClassName::methodName

Program without method reference - Simple program to invoke


static method

As we know above program is the normal one to invoke the static method.

1. class MyStringClass
2. {
3. static String processString()
4. {
5. return "test";
6. }
7. }
8.
9. public class MethodReference1 {
10.
11. public static void main(String args[])
12. {
13. String outStr=MyStringClass.processString();
14. }

Page 578 of 660


Java Book - Chidambaram.S

15. }

Simple program to invoke static method using method reference.

1. //Functional Interface
2. interface MyStringInterface {
3. String processString();
4. }
5.
6. //Class with static method to return the string
7. class MyStringClass {
8. static String processString() {
9. return "test";
10. }
11. }
12.
13. public class MethodReference1 {
14. //static method to accept MyStringInterface type as the parameter and invoke the processString() /
/ of MyStringInterface.
15. static String invokeProcessString(MyStringInterface myStringInterface) {
16. return myStringInterface.processString();
17. }
18.
19. public static void main(String args[]) {
20. String outStr = invokeProcessString(MyStringClass::processString);
21. System.out.println(outStr);
22. }
23. }
24. Output
25. test

The notable points listed below

invokeProcessString(MyStringClass::processString) - the statement invokes


invokeProcessString() and passing MyStringClass::processString method reference

Page 579 of 660


Java Book - Chidambaram.S

as the parameter. The method gets this parameter as MyStringInterface type.


This is the key point to understand in clear way.

Then this method invokes the processString() of MyStringInterface, which in


turns invoke MyStringClass.processString().

Multiple invocation example with one Functional Interface


type

1. // A functional interface
2. interface StringInterface {
3. String processString(String str);
4. }
5.
6. class StringClass1 {
7. static String returnString(String str) {
8. return str + " StringClass1";
9. }
10. }
11.
12. class StringClass2 {
13. static String returnString(String str) {
14. return str + " StringClass2";
15. }
16. }
17.
18. class StringClass3 {
19. String returnString(String str) {
20. return str + " StringClass3";
21. }
22. }
23.
24. class InvokeStringClass {

Page 580 of 660


Java Book - Chidambaram.S

25. static String invokeProcessString(StringInterface stringInterface, Str


ing s) {
26. return stringInterface.processString(s);
27. }
28. }
29.
30. public class MethodReferenceDemo1 {
31. public static void main(String args[]) {
32. String inStr = "input string";
33. String outStr;
34. outStr = InvokeStringClass.invokeProcessString(StringClass1::retur
nString, inStr);
35. System.out.println(outStr);
36. outStr = InvokeStringClass.invokeProcessString(StringClass2::retur
nString, inStr);
37. System.out.println(outStr);
38. outStr = InvokeStringClass.invokeProcessString(new StringClass3():
:returnString, inStr);
39. System.out.println(outStr);
40. }
41. }
42.
43. Output
44.
45. input string StringClass1
46. input string StringClass2
47. input string StringClass3

In above program, below statements are invoking the corresponding methods


specified in method reference.

Initially invokeProcessString() accepts StringInterface object for all three


statements below and invocating redirected to the corresponding classes.

Page 581 of 660


Java Book - Chidambaram.S

First two statements are the examples of Static Method References and third one
statement is the example of Instance Method Reference.

//StringClass1 and StringClass2 have only static method returnString()

outStr = InvokeStringClass.invokeProcessString(StringClass1::returnString,
inStr);

outStr = InvokeStringClass.invokeProcessString(StringClass2::returnString,
inStr);

//StringClass3 has only instance method returnString()

outStr = InvokeStringClass.invokeProcessString(new
StringClass3()::returnString, inStr);

Constructor Reference

Constructor reference is the way to create the reference using Functional


Interface for any type.

Below Functional Interface ObjectFactoryInterface accepts T,V. Here T is the


object of type to be created and V is the argument to the Type T.

Here MyClass accepts V. So we can pass any type to MyClass as V.

The below one parameter constructor accepts V value and getValue() returns the
same V value.

Empty constructor added to avoid the compile time error as if any parameterized
constructor is added the empty constructor should be added explicitly.

In below three statements, the statement 1 creates the object


ObjectFactoryInterface to refer MyClass type.

ObjectFactoryInterface<MyClass, Integer> - MyClass will be assigned as T and


Integer will be assigned as V.

Page 582 of 660


Java Book - Chidambaram.S

MyClass<Integer> - The MyClass constructor argument is now ready to accept any


Integer type.

The statement 2 assigns value=100 of MyClass and returns the MyClass object.

The statement 3 invokes getValue() MyClass and prints value.

MyClass<Integer>::new; - This is the constructor reference.

ObjectFactoryInterface<MyClass, Integer> objectFactoryInterface1 =


MyClass<Integer>::new;

MyClass<Integer> myClass1 = objectFactoryInterface1.func(100);

System.out.println("val in mc is " + myClass1.getValue());

MyClass(V value) {

this.value = value;

1. //Functional Interface
2. interface ObjectFactoryInterface<T, V> {
3. T func(V v);
4. }
5.
6. class MyClass<V> {
7. V value;
8. MyClass(V value) {
9. this.value = value;
10. }
11. MyClass() {
12. value = null;
13. }
14. V getValue() {
15. return value;

Page 583 of 660


Java Book - Chidambaram.S

16. };
17. }
18.
19. public class ConstructorReferenceDemo {
20. public static void main(String args[]) {
21. ObjectFactoryInterface<MyClass, Integer> objectFactoryInterface1 =
MyClass<Integer>::new;
22. MyClass<Integer> myClass1 = objectFactoryInterface1.func(100);
23. System.out.println("val in mc is " + myClass1.getValue());
24.
25. ObjectFactoryInterface<MyClass, Double> objectFactoryInterface2 =
MyClass<Double>::new;
26. MyClass<Integer> myClass2 = objectFactoryInterface2.func(100D);
27. System.out.println("val in mc is " + myClass2.getValue());
28. }
29. }

Benefit

By using constructor reference and this example, we can create the interface to
accept to any type of parameter and returns any type of parameter. So this will
be useful to create the factory method design pattern.

Class Collectors - java.util.stream.Collectors

public final class Collectors extends Object

Collector is useful for reduction operations such as accumulating elements


into collections, summarizing elements according to various criteria, etc.

Lets see the example program to understand how we can use Collectors better

1.
2. public class Employee {

Page 584 of 660


Java Book - Chidambaram.S

3.
4. String name;
5.
6. int salary;
7.
8. public String getName() {
9. return name;
10. }
11.
12. public void setName(String name) {
13. this.name = name;
14. }
15.
16. public int getSalary() {
17. return salary;
18. }
19.
20. public void setSalary(int salary) {
21. this.salary = salary;
22. }
23.
24. }

1. package java12Project;
2.
3. import java.util.ArrayList;
4. import java.util.List;
5. import java.util.stream.Collectors;
6.
7. public class CollectorsDemo {
8.
9. public static void main(String[] args) {
10. // TODO Auto-generated method stub
11.
12. List<String> names = new ArrayList<>();
13. List<Employee> employeesList = new ArrayList<>();
14.
15. Employee employee1 = new Employee();
16. employee1.name = "Ram";
17. employee1.salary = 6000;
18.
19. Employee employee2 = new Employee();
20. employee2.name = "Raj";
21. employee2.salary = 3000;
22.
23. employeesList.add(employee1);
24. employeesList.add(employee2);
25.
26. names.add("Ram");
27. names.add("Raju");
28.
29. // Convert elements to strings and concatenate them, separated by commas
30. String joinedNames = names.stream().map(Object::toString).collect(Collectors.joining(", ")
);
31.
32. System.out.println("joinedNames=" + joinedNames);
33.
34. // Compute sum of salaries of employee
35.
36. int total = employeesList.stream().collect(Collectors.summingInt(Employee::getSalary));
37.

Page 585 of 660


Java Book - Chidambaram.S

38. System.out.println(total);
39.
40. }
41.
42. }
43.
44. Output
45.
46. joinedNames=Ram, Raju
47. 9000

Lambda Experssions

Lambda Expressions, enable us to treat functionality as a method argument, or


code as data. A lambda expression is an anonymous ( unnamed) method to
implement a method defined by a functional interface.

Lambda expressions are also commonly referred to as closures.

Java Lambda Expression Syntax

(Parameters for Lambda expressions) -> {Lambda expression}

Java lambda expression is consisted of three components.

1) Parameters for Lambda expressions: Parameter list that can be used in Lambda
expression empay paranthesis if no parameters.

2) Arrow Operator It divides Parameters for Lambda expressions and Lambda expression

3) Lambda expressions: It contains expressions and statements for lambda expression.

Functional Interface

A functional interface is an interface that contains one and only one abstract method.

and functional interface can be known as SAM(Single Abstract Method) type.

Example of Functional Interface

@FunctionalInterface // Optional annotation

Page 586 of 660


Java Book - Chidambaram.S

interface DrawingBoard{

public void startDrawing(); // only one method declaration.

Lambda Example Program without parameter

1. @FunctionalInterface

2. interface DrawingBoard{

3. public void startDrawing();

4. }

5. public class LambdaDemo1 {

6. public static void main(String[] args)

7. {

8. DrawingBoard drawingBoard =()->

9. {

10. System.out.println("Start Drawing method is called ");

11. };

12. drawingBoard.startDrawing();

13. }

14. }

Step by step explanation of above program

Page 587 of 660


Java Book - Chidambaram.S

@FunctionalInterface is an optional one

2 to 4 interface and only one method defined. Functional Interface should have
only one method.

8 to 11 Using lambda expression, added the definition for startDrawing(). The


notable point is without implementing the interface, the class defined the
method using lambda.

12 invoking startDrawing()

Lambda Example Program with parameter

1. @FunctionalInterface
2. interface DrawingBoard{
3. public void startDrawing(String color);
4. }
5. public class LambdaDemo1 {
6. public static void main(String[] args)
7. {
8. DrawingBoard drawingBoard =(String color)->
9. {
10. System.out.println("Start Drawing using "+color);
11. };
12. drawingBoard.startDrawing("Green);
13. }
14. }

Step by step explanation of above program

Same as like above program with the below differences.

3. One String parameter is declared as method argument.

Page 588 of 660


Java Book - Chidambaram.S

8. Lambda Expression's argument list comes with parameter name and type.

12. startDrawing method is invoked with the argument.

Below example comes with Lambda expressions with stream. Comments


included to understand more better.

1. import java.util.Arrays;
2. // Functional Interface with only one abstract method to accept array and return
array.
3. @FunctionalInterface
4. interface NumberInterface
5. {
6. int[] processArray(int num[]);
7. }
8.
9. public class LambdaExpressionBody {
10.
11. public static void main(String[] args) {
12. int numberArrays[]= {2,5,7,4,9,15,34};
13. /*
14. * Lambda expression returns ever Functional Interface type.
15. * In below example return type is NumberInterface
16. * paramArray is the input parameter for Lambda expression
17. * Lambda expression returns one Array
18. * */
19. NumberInterface numberInterface1 = (paramArray) -> {
20. return Arrays.stream(paramArray).filter(number -
> number % 2 != 0).toArray();
21.
22. };
23.
24. NumberInterface numberInterface2 = (paramArray) -> {
25. return Arrays.stream(paramArray).filter(number -
> number % 2 == 0).toArray();

Page 589 of 660


Java Book - Chidambaram.S

26. };
27.
28. int oddArray[]= numberInterface1.processArray(numberArrays);
29. int evenArray[]= numberInterface2.processArray(numberArrays);
30.
31.
32. Arrays.stream(oddArray).forEach(System.out::println);
33. Arrays.stream(evenArray).forEach(System.out::println);
34. }
35. }

return Arrays.stream(paramArray).filter(number -> number % 2 != 0).toArray();

Arrays.stream(paramArray) - returns java.util.Stream object

filter() - method of Stream interface

number -> number % 2 != 0 - > Lambda expression as the argument of


filter() to filter out odd number.

filter() returns Stream object and toArray of Stream returns array of


final odd number array.

Arrays.stream(oddArray).forEach(System.out::println);

stream() of Arrays class returns java.util.stream.IntStream interface


object and array as the argument. Here oddArray is the argument.

We invokde IntStream forEach() by passing System.out::println as the


argument, which is the method reference to pring all the values in oddArray.

1. import java.util.ArrayList;
2. import java.util.Collections;
3. import java.util.Comparator;
4. import java.util.List;

Page 590 of 660


Java Book - Chidambaram.S

5.
6. class Employee {
7. String name;
8. double salary;
9. int age;
10.
11. Employee(String name, double salary, int age) {
12. this.name = name;
13. this.salary = salary;
14. this.age = age;
15. }
16.
17. public String getName() {
18. return name;
19. }
20.
21. public void setName(String name) {
22. this.name = name;
23. }
24.
25. public double getSalary() {
26. return salary;
27. }
28.
29. public void setSalary(double salary) {
30. this.salary = salary;
31. }
32.
33. public int getAge() {
34. return age;
35. }
36.
37. public void setAge(int age) {
38. this.age = age;
39. }

Page 591 of 660


Java Book - Chidambaram.S

40. }
41.
42. public class LambdaComparator {
43.
44. public static void main(String[] args) {
45.
46. List<Employee> listEmployees = getEmployees();
47.
48. System.out.println("Before Sort");
49. for (Employee employee : listEmployees) {
50. System.out.println(
51. "Name=" + employee.getName() + " Salary=" + employee.getSalary()
+ " Age=" + employee.getAge());
52. }
53.
54. // using lambda - java 8 - sort by salary ascending
55.
56. listEmployees.sort((Employee employee1, Employee
57. employee2)->(int)(employee1.getSalary()-employee2.getSalary()));
58.
59.
60. // using lambda - java 8 - sort by salary ascending - type is optional
61. listEmployees.sort((employee1, employee2) -
> (int) (employee1.getSalary() - employee2.getSalary()));
62.
63. System.out.println("============= After Sort by salary ascending =========
==========");
64.
65. for (Employee employee : listEmployees) {
66. System.out.println("Name=" + employee.getName() + " Salary=" + employ
ee.getSalary() + " Age=" + employee.getAge());
67. }
68.
69. // using lambda - java 8 - sort by salary descending

Page 592 of 660


Java Book - Chidambaram.S

70. listEmployees.sort((employee1, employee2) -


> (int) (employee2.getSalary() - employee1.getSalary()));
71.
72.
73. System.out.println(" =================== After Sort by salary descending
===================");
74.
75. for (Employee employee : listEmployees) {
76. System.out.println("Name=" + employee.getName() + " Salary=" + employ
ee.getSalary() + " Age=" + employee.getAge());
77. }
78.
79. }
80.
81.
82. private static List<Employee> getEmployees() {
83.
84. List<Employee> result = new ArrayList<Employee>();
85. result.add(new Employee("Ram", 60000, 33));
86. result.add(new Employee("Ragav", 50000, 20));
87. result.add(new Employee("Krishna", 90000, 10));
88. result.add(new Employee("Siva", 70000, 55));
89. return result;
90. }
91. }

Sort by salary ascending using classic model

1. Collections.sort(listEmployees, new Comparator<Employee>() {


2. @Override
3. public int compare(Employee o1, Employee o2)
4. {

Page 593 of 660


Java Book - Chidambaram.S

5. return (int)(o1.getSalary() - o2.getSalary());


6. }
7. }

Page 594 of 660


Java Book - Chidambaram.S

For Each

1. import java.util.ArrayList;
2. import java.util.List;
3. public class ForEachDemo {
4. public static void main(String args[])
5. {
6. List<String> itemsList = new ArrayList<>();
7. itemsList.add("A");
8. itemsList.add("B");
9. itemsList.add("C");
10. itemsList.add("D");
11. itemsList.add("E");
12.
13. // Class model
14. for (String item : itemsList) {
15. System.out.println("Item : " + item);
16. }
17. //Java 8 way for each
18. itemsList.forEach((itemStr) ->System.out.println("Item : " + itemStr ));
19. }
20. }

below one example is also correct with type "String itemStr"

//Java 8 way for each List

itemsList.forEach((String itemStr) ->System.out.println("Item : " + itemStr ));

//Java 8 way for each with Map

map.forEach((k,v) -> System.out.println(k+v));

Page 595 of 660


Java Book - Chidambaram.S

java.util.Stream

Stream and lambda are the most important features in java 8.

Stream reperesents a sequence of objects. Stream is an object to perform the


operations like search, filter, sort or map reduce the data. The source of
stream cen be collection or arrays. Stream will not have any storage and will
not modify the orginal data.

All stream interfaces are packaged in java.util.stream and extend the


java.util.stream.BaseStream

Methods of BaseStream

void close( ) Closes the invoking stream

boolean isParallel( ) Returns true if the invoking stream is parallel.


Returns false if the stream is sequential.

Iterator<T> iterator( ) Obtains an iterator to the stream and returns a


reference to it.(Terminal operation.)

S onClose(Runnable handler) Returns a new stream with the close handler


specified by handler. This handler will be called
when the stream is closed. (Intermediate
operation.)

S parallel( ) Returns a parallel stream based on the invoking


stream. If the invoking stream is already parallel,
then that stream is returned. (Intermediate operation.)

S sequential( ) Returns a sequential stream based on the invoking


stream. If the invoking stream is already
sequential, then that stream is returned.
(Intermediate operation.)

Spliterator<T> spliterator( ) Obtains a spliterator to the stream and returns a


reference to it. (Terminal operation.)

Page 596 of 660


Java Book - Chidambaram.S

S unordered( ) Returns an unordered stream based on the invoking


stream. If the invoking stream is already
unordered, then that stream is returned.
(Intermediate operation.)

How to get the Stream object

Stream<Integer> myStream = myList.stream();

myList - ArrayList

myStream - stream

stream()- method to get the stream for myList

Terminal and Intermediate operations in Stream

A terminal operation consumes the stream and produce a result, such as finding
the minimum value in the stream,or to execute some action. Once a stream has
been consumed, it cannot be reused.

Intermediate operations produce another stream. Thus,intermediate operations


can be used to create a pipeline that performs a sequence of actions.

Terminal Operation

A terminal operation consumes the stream, to produce a result, such as


finding the minimum value in the stream.

Once a stream has been consumed, it cannot be reused. For example below
example will produce the below exception.

Exception in thread "main" java.lang.IllegalStateException: stream has already


been operated upon or closed

Page 597 of 660


Java Book - Chidambaram.S

Stream<Integer> numberListStream = numbersList.stream();

Optional<Integer> minVal = numberListStream.min(Integer::compare);

if (minVal.isPresent())

System.out.println("Minimum value: " + minVal.get());

Optional<Integer> maxVal = numberListStream.max(Integer::compare);


// numberListStream can't be reused

if (maxVal.isPresent())

System.out.println("Minimum value: " + maxVal.get());

Lazy behavior of Intermediate Stream

Terminal operation percedes intermediate operations, thus if intermediate and


terminal operations in a statement, terminal operations will be completed then
intermediate operation will take in place to complete. This mechanism is
referred to as lazy behavior, and the intermediate operations are referred to
as lazy. The use of lazy behavior enables the stream API to perform more
efficiently.

Stateless and stateful Intermediate operation

Page 598 of 660


Java Book - Chidambaram.S

Another key aspect of streams is that some intermediate operations are


stateless and some are stateful. In a stateless operation, each element is
processed independently of the others.

In a stateful operation, the processing of an element may depend on aspects of


the other elements. For example, sorting is a stateful operation because an
element’s order depends on the values of the other elements. Thus, the sorted(
) method is stateful. However, filtering elements based on a stateless
predicate is stateless because each element is handled individually. Thus,
filter( ) can (and should be) stateless. The difference between stateless and
stateful operations is especially important when parallel processing of a
stream is

desired because a stateful operation may require more than one pass to
complete.

Intermediate operation examples

// Sort the stream by use of sorted(), here numberListStream is the stream


obtained using numberList.

Stream<Integer> numberListStream = numbersList.stream();

Stream<Integer> sortedStream = numberListStream.sorted();

Convert stream to List

collect() comes with Stream interface and it requires java.util.Collectors


interface object. Below example illustrates how to use the collect method with
the argument Collectors to get the List from Stream.

List<Integer> distinctList =
numbersList.stream().distinct().collect(Collectors.toList());

Page 599 of 660


Java Book - Chidambaram.S

In below example, we will get odd numbers from the list and the comments added
in the program to understand how each line works.

1. import java.util.ArrayList;
2. import java.util.List;
3. import java.util.stream.Collectors;
4.
5. public class StreamDemo1 {
6.
7. public static void main(String[] args) {
8. // TODO Auto-generated method stub
9.
10. List<Integer> numbersList = new ArrayList<>();
11. numbersList.add(5);
12. numbersList.add(7);
13. numbersList.add(2);
14. numbersList.add(9);
15. numbersList.add(4);
16.
17. List<Integer> oddNumbersList = numbersList.stream() // convert list to str
eam
18. .filter(number -
> number % 2 != 0) // filter() Stream to map reduce operation
19. .collect(Collectors.toList()); // collect and convert stream to a List
20.
21. oddNumbersList.forEach(System.out::println); // java 8 forEach style and S
ystem.out::println is the method to just print the list
22. }
23. }
24.

Page 600 of 660


Java Book - Chidambaram.S

ParallelStream

ParallelStream as the name implies it works in parallel way.

The parallelStream() of java.util.Collection or parallel() of


java.util.stream.BaseStream are using to get the ParallelStream.

Once a parallel stream has been obtained, operations on the stream can occur in
parallel way.

You can switch a parallel stream to sequential by calling the sequential( )


method, which

is specified by BaseStream.

Stream with Iterator

you can use an iterator with a stream in just the same way that you do with a
collection. Iterators

1. import java.util.ArrayList;
2. import java.util.Iterator;
3. import java.util.List;
4.
5. public class StreamWithIteratorDemo {
6.
7. public static void main(String[] args) {
8. // TODO Auto-generated method stub
9. List<String> itemsList = new ArrayList<>();
10. itemsList.add("A");
11. itemsList.add("B");
12. itemsList.add("C");
13. itemsList.add("D");
14. itemsList.add("E");
15.

Page 601 of 660


Java Book - Chidambaram.S

16. Iterator iterator = itemsList.stream().iterator();


17. while (iterator.hasNext()) {
18. System.out.println(iterator.next().toString());
19. }
20.
21. }
22.
23. }
24.
25. Output
26.
27. A
28. B
29. C
30. D
31. E

Date and Time handling added in Java 8

LocalDate

It is a class added in Java 8 under package java.time to reperesent date only


without time using ISO-8601 calendar system in the format of yyyy-mm-dd.

This class is immutable and thread-safe (java.util.Date is not thread safe).


Using synchronized, == operator, identity hash code with this object may
provide unpredictable results.

To check the equality between dates equals method can be used.

java.time.LocalDate and java.time.LocalDateTime demonstrated in below example


along with DateTimeFormatter style and Locale.

Page 602 of 660


Java Book - Chidambaram.S

1. import java.time.LocalDate;
2. import java.time.LocalDateTime;
3. import java.time.Month;
4. import java.time.format.DateTimeFormatter;
5. import java.time.format.FormatStyle;
6. import java.util.Locale;
7.
8. public class LocalDateDemo {
9. public static void main(String args[]) {
10.
11. // LocaleDate
12. System.out.println(LocalDate.now());
13. System.out.println(LocalDate.of(2019, 6, 19));
14. System.out.println(LocalDate.of(2019, Month.JUNE, 19));
15. System.out.println(LocalDate.of(2019, Month.JUNE, 19));
16. System.out.println(LocalDate.ofYearDay(2019, 120));
17. System.out.println(LocalDate.parse("2019-05-20"));
18.
19. LocalDate date = LocalDate.now();
20. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-
yyyy");
21. String text = date.format(formatter);
22. System.out.println(text);
23. LocalDate parsedDate = LocalDate.parse("18-06-2019", formatter);
24.
25. System.out.println(parsedDate);
26. // LocaleDateTime
27. System.out.println(LocalDateTime.now());
28. System.out.println(LocalDateTime.of(2019, 6, 19, 10, 21));
29. System.out.println(LocalDateTime.of(2019, Month.JUNE, 19, 10, 21,
40));
30. System.out.println(LocalDateTime.of(2019, Month.JUNE, 19, 10, 21,
40, 403));

Page 603 of 660


Java Book - Chidambaram.S

31.
32. // Date and Time Formatting with Locale
33.
34. LocalDateTime todayLocalDateTime = LocalDateTime.now();
35.
36. DateTimeFormatter localeSpecficFormatter = DateTimeFormatter.ofLoc
alizedDateTime(FormatStyle.MEDIUM) .withLocale(Locale.CANADA);
37. System.out.println("Locale Specific Date=" + localeSpecficFormatte
r.format(todayLocalDateTime));
38.
39. }
40. }
41.
42. Output
43.
44. 2019-06-18
45. 2019-06-19
46. 2019-06-19
47. 2019-06-19
48. 2019-04-30
49. 2019-05-20
50. 18-06-2019
51. 2019-06-18
52. 2019-06-18T18:38:30.470
53. 2019-06-19T10:21
54. 2019-06-19T10:21:40
55. 2019-06-19T10:21:40.000000403
56. Locale Specific Date=18-Jun-2019 6:38:30 PM

Default and static methods of interface

Page 604 of 660


Java Book - Chidambaram.S

In prior versions, in interfaces we can have only public methods declarations.


In Java8, we can add default and static methods in interface with definitions.
By using this feature, we can add the common behavior for implemented classes
and other interfaces.

Below program illustrates how the feature is working.

1. interface MyInterface {
2.
3. default void m1() {
4. System.out.println("m1()-default method of MyInterface");
5. }
6.
7. static void m2() {
8. System.out.println("m2()-static method of MyInterface");
9. }
10. }
11.
12. class MyClass implements MyInterface {
13. void invokeM1() {
14. m1();
15. }
16. }
17.
18. public class DefaultStaticMethodsInterfaceDemo {
19. public static void main(String args[]) {
20. MyInterface myInterface = new MyClass();
21. MyClass myClass = new MyClass();
22. myInterface.m1();
23. myClass.m1();
24. MyInterface.m2();
25. myClass.invokeM1();
26. }
27. }
28.

Page 605 of 660


Java Book - Chidambaram.S

29. Output
30.
31. m1()-default method of MyInterface
32. m1()-default method of MyInterface
33. m2()-static method of MyInterface
34. m1()-default method of MyInterface

MyInterface has default and static methods with the definitions.

MyClass is the subclass of MyInterface

The m1() is default method and can be accessed using myInterface object and
myClass object. m2() is static, so it is invoked by using MyInterface.m2().

invokeM1() is defined in MyClass so it is invoked using myClass object.

By using this feature, MyInterface class can be extended by many classess and
the default, private, static methods we can distribute common functionality to
all sub classes.

Page 606 of 660


Java Book - Chidambaram.S

Chapter 38 Java 9 Features

of()

In java 9, there is an easy way to create the List or Map using of().

In prior release we have to instantiate the object snf add(),to add the items
to the list and put() to add the key value pairs in Map.

Instead, we can use below example in easier way to create List or Map

of() List

The List.of() static factory methods provide a convenient way to create


immutable lists. The List instances created by these methods have the following
characteristics

The list created by of() is immutable and can't be modified (add, remove or
replace). The null will not be allowed. The below example illustrates how
of() can be used and exception raised when we use null or trying to change the
list.

Example Program for of() in java.util.List

1. import java.util.List;
2. public class ListOfMethodDemo {
3. public static void main(String args[]) {
4. List list1 = List.of();
5. List list2 = List.of("Ram", "Rama", "Ragava", "Anbu");
6.
7. System.out.println(list1);
8. System.out.println(list2);
9. // Below statements are not supported with of() list and raises the
10. // java.lang.UnsupportedOperationException
11. /*

Page 607 of 660


Java Book - Chidambaram.S

12. * list1.add("Mani");
13. * list1.add(null);
14. */
15. }
16. }
17.
18. Output
19.
20. []
21. [Ram, Rama, Ragava, Anbu]
22.

1. import java.util.Map;
2.
3. public class MapOfMethodDemo {
4. public static void main(String args[]) {
5. Map map1 = Map.of();
6. Map map2 = Map.of("Name", "Ram", "Age", "23", "Salary", "24000");
7. map2.forEach((k, v) -> System.out.println(k + "," + v));
8. // Below statements are not supported with of() Map and raises the
9. // java.lang.UnsupportedOperationException
10. /*
11. * map2.put("City", "chennai");
12. * map2.put("MS",null);
13. */
14. }
15. }
16.
17. Output
18.
19. Age,23
20. Name,Ram

Page 608 of 660


Java Book - Chidambaram.S

21. Salary,24000

JShell

The Java Shell tool (JShell) is added in java 9 to learn and evaluate Java
programming language. JShell is a Read-Evaluate-Print Loop (REPL), which
evaluates declarations, statements, and expressions as they are entered and
immediately shows the results.

Starting and Stopping JShell

1) Open the command prompt

2) Type Jshell and press enter

Now the prompt will be changed as like below

jshell>

3) To exit from jshell

jshell>/exit

As like below you can enter and evaluate any java statements, and you will get the
results or errors immediatelty.

Valid statement example

jshell> int x=45

x ==> 45

Error statement example

Page 609 of 660


Java Book - Chidambaram.S

jshell> byte b1=209423

| Error:

| incompatible types: possible lossy conversion from int to byte

| byte b1=209423;

private method in interface

in Java9, we can add private methods in iterface with definitions to provide


the mandatory common feature to sub classes of the interface. As we know this
private method can be invoked by the same interface method.

In below example the MyInterface9 has one private method m1() and it is called
by default void m2() of same interface.

The MyClass9 is the sub class of MyInterface9 and it has invokeM2() to call
m2() of MyInterface9, in turns it calls m1() private method of MyInterface9.

1. interface MyInterface9 {
2. private void m1() {
3. System.out.println("m1() - private method of MyInterface");
4. }
5. default void m2() {
6. m1();
7. }
8. }
9.
10. class MyClass9 implements MyInterface9 {
11. void invokeM2() {

Page 610 of 660


Java Book - Chidambaram.S

12. m2();
13. }
14. }
15. public class PrivateMethodInterfaceDemo {
16. public static void main(String args[]) {
17. MyClass9 myClass9 = new MyClass9();
18. myClass9.invokeM2();
19. }
20. }
21.
22. Output
23.
24. m1() - private method of MyInterface
25.

Usage the variable declared outside can be used in


try with resources

In java7 try with resources were introduced. The feature allows the runtime to
close the objects automatically (The class must implement
java.io.AutoCloseable) when try block is completed. But the object must be
declared within the try block and this is the blockage of this feature.

In Java9, we can even use the objects that are declared outside can be used
within try with resources block.

The below example illustrates the feature.

1. import java.io.BufferedReader;
2. import java.io.FileNotFoundException;
3. import java.io.FileReader;
4. import java.io.IOException;

Page 611 of 660


Java Book - Chidambaram.S

5.
6. public class TryWithResourceDemo {
7. public static void main(String[] args) throws FileNotFoundException, IOExcep
tion {
8. // TODO Auto-generated method stub
9. String path = "d:\\abc.txt";
10. BufferedReader br = new BufferedReader(new FileReader(path));
11. try (br) {
12. System.out.println(br.readLine());
13. }
14. System.out.println();
15. }
16. }

The BufferedReader declared outside of try block, used within try and it will
be closed automatically when try block is completed.

Page 612 of 660


Java Book - Chidambaram.S

Chapter 39 Java 9 Modular System

Prior approach before Java 9 Modular system

Prior we have packages to group classes and interfaces. These packages can be
imported to other classes using import statement.

Also we have access modifiers to control which properties of the class can be
used in other classes in different or same package.

Drawbacks of above Prior approach

Packages and import statements are completely compile time dependencies thus
these dependencies should be resolved at compile time. There is no way to tell
java about runtime dependencies.

Massive amounts of legacy code are there in monolithic approach, because the
Java platform has primarily been a monolithic.

Monolithic means one project comes with all the solutions and, the developers
depend Maven, Gradle like build tool to separate the project like service
layer, common layer, business layer for enterprise project development.

For example below image illustrates how the enterprise project is packed and
prior Java 9 Modular system, we completely depend other tool such Maven, Gradle
to acheive this.

Page 613 of 660


Java Book - Chidambaram.S

Exapnded view

It is one jar module created as Maven project


type.

It is one ear module created as Maven project


type.

The above project is created using Maven. This is the structure of enterprise java
project. Ear file will contain all other modules as a jar file as like below.

Page 614 of 660


Java Book - Chidambaram.S

EmployeeEAR.ear

EmployeeBusiness.jar

EmployeeDAO.jar

EmployeeDomain.jar

EmployeeFacade.jar

EmployeeRest.jar

EmployeeService.jar

EmployeeWeb.jar

Java 9 Modular System resolves this important problam by introducing Java 9 Modular
System.

What is Java 9 Modular System

Java 9 Platform Module System (JPMS), is the most important feature in java
since its inception and it is the result of Project Jigsaw.

Modularity adds a higher level of aggregation above packages. The key new
language element is the module—a uniquely named to group the packages, as well
as resources (such as images and XML files).

A Java module can specify which of the Java packages it contains that should be
visible to other Java modules using this module.

a class is a container of fields and methods

a package is a container of classes and interfaces

a module is a container of packages

Page 615 of 660


Java Book - Chidambaram.S

Module Descriptor (module-info.java)

Each Java module needs a Java module descriptor named module-info.java which has
to be located in the corresponding module root directory. The module descriptor
specifies which packages a module exports, and what other modules the module
requires. These details will be explained in the following sections.

In below diagram

JavaModularApplication1 - Project Name

EmployeeBusiness |

EmployeeDAO | Module Name

EmployeeWeb |

Page 616 of 660


Java Book - Chidambaram.S

In every one module, module-info.java will be automatically created and you can
see the code in that file as like above image.

Modular Application Creation

Below sample application is created by using Netbeans IDE 10.0

Page 617 of 660


Java Book - Chidambaram.S

1) Using File -> New Project create the Java Modular Application as like
"JavaModularApplication1" in above image

2) Right Click the "JavaModularApplication1" and select New->Module, create the


Module "EmployeeBusiness","EmployeeDAO","EmployeeWeb"

3) You can see the module-info.java in each module.

4) module-info.java of EmployeeBusiness module add below code

module EmployeeBusiness {

exports com.mycomp.info.layer;

Page 618 of 660


Java Book - Chidambaram.S

5) module-info.java of EmployeeDAO module add below code

module EmployeeDAO {

requires EmployeeBusiness;

6)Now you can import EmployeeBusinessProcess in EmployeeDAOProcess using below


code.

package com.mycomp.dao.layer;

import com.mycomp.info.layer.EmployeeBusinessProcess;

/**

* @author Chidambaram

*/

public class EmployeeDAOProcess {

Benefits of above approach.

EmployeeWeb module can have UI part of the application.

EmployeeBusiness module can have business logic of the application

EmployeeDAO module can have database logic of the application

Page 619 of 660


Java Book - Chidambaram.S

Now the UI can invoke business logic in businss module and business module
invokes DAO module to do the database logics and return the result web module.

This is the clean separation of one enterprise project and debugging,


maitenance also easier than monolithic approach.

Page 620 of 660


Java Book - Chidambaram.S

Chapter 40 Java 10 Features

2018/03/20 - General Availability

JEP 286: Local-Variable Type Inference

Variable declaration using var

var is used to declared the variable without speciifying data type


explicitely.

The identifier var is not a keyword; instead it is a reserved type name.

Lets see the example

1. public class VarDemo1 {


2.
3. public static void main(String[] args) {
4.
5. var y = 100;
6.
7. System.out.println("y=" + y);
8.
9. }
10. }
11.
12. Output
13.
14. y=100

Some more points on var

Only local varible can be declared

Page 621 of 660


Java Book - Chidambaram.S

When the declaration, the value should be assigned.

Method and constructor parameters can be var where as the formal parameter
should not be var and we should declare variable explicitely in formal
parameter.

Below statements are not allowed and error with var

var b=null;

var k = { 1 , 2 }; // (array initializer needs an explicit target-type)

1. public class VarDemo1 {


2.
3. VarDemo1(int y1)
4. {
5. System.out.println("constructor="+y1);
6. }
7. void method1(int y1) {
8. System.out.println("method="+y1);
9. }
10.
11. int method2()
12. {
13. var x=100;
14. return x;
15. }
16. public static void main(String[] args) {
17.
18. var y = 100;
19. VarDemo1 varDemo1 = new VarDemo1(10);
20. varDemo1.method1(y);
21. System.out.println("method2="+varDemo1.method2());
22. }
23. }
24.
25. Output
26.
27. constructor=10
28. method=100
29. method2=100

Creating Unmodifiable Collections

Page 622 of 660


Java Book - Chidambaram.S

Several new APIs have been added that facilitate the creation of unmodifiable
collections. The List.copyOf, Set.copyOf, and Map.copyOf methods create new
collection instances from existing instances. New
methods toUnmodifiableList, toUnmodifiableSet, and toUnmodifiableMap have been
added to the Collectors class in the Stream package. These allow the elements of
a Stream to be collected into an unmodifiable collection.

Lets see the example program below to understand to get the unmodifiable
collections.

Collector toUnmodifiableList()

static Collector toUnmodifiableSet()

static Collector toUnmodifiableMap()

1. package Java10Project;
2.
3. import java.util.ArrayList;
4. import java.util.Arrays;
5. import java.util.List;
6. import java.util.stream.Collectors;
7. import java.util.stream.Stream;
8.
9. public class CollectionChangesDemo2 {
10.
11. public static void main(String[] args) {
12. // TODO Auto-generated method stub
13.
14. List<String> namesList = new ArrayList<>();
15. namesList.add("Ram");
16. namesList.add("Ragu");
17. namesList.add("Sundar");
18. namesList.add("Anbu");
19. List<String> namesListCopy = List.copyOf(namesList);

Page 623 of 660


Java Book - Chidambaram.S

20. namesList.add("Subbu");
21. System.out.println(namesList);
22. /*
23. * Below line throws Exception in thread "main"
24. * java.lang.UnsupportedOperationException
25. */
26.
27. // namesListCopy.add("Siva");
28. System.out.println(namesListCopy);
29.
30. List<Integer> intList = new ArrayList<Integer>();
31. intList.add(5);
32. intList.add(10);
33. intList.add(50);
34.
35. // toUnmodifiableList example
36. List<String> result = namesList.stream().collect(Collectors.toUnmo
difiableList());
37.
38. /*
39. * Below line throws Exception in thread "main"
40. * java.lang.UnsupportedOperationException
41. */
42. result.add("test");
43.
44. }
45. }
46.
47. Output
48.
49. [Ram, Ragu, Sundar, Anbu, Subbu]
50. [Ram, Ragu, Sundar, Anbu]

Page 624 of 660


Java Book - Chidambaram.S

java.util.Optional orElseThrow()

orElseThrow() is a method in java.util.Optional added in java 10. It is


synonymous with and is now the preferred alternative to the
existing get method.

If a value is present, returns the value, otherwise throws NoSuchElementException

Below example demonstrates the orElseThrow instead get

1. import java.util.ArrayList;
2. import java.util.List;
3. import java.util.Optional;
4. import java.util.stream.Collectors;
5. import java.util.stream.Stream;
6.
7. public class OptionalOrElseThrowDemo {
8. // TODO Auto-generated method stub
9. public static void main(String args[]) {
10.
11. List<Integer> numbersList = new ArrayList<>();
12. numbersList.add(5);
13. numbersList.add(7);
14. numbersList.add(2);
15. numbersList.add(9);
16. numbersList.add(4);
17. numbersList.add(4);
18.
19. Stream<Integer> numberListStream = numbersList.stream();
20.
21. Optional<Integer> minVal = numberListStream.min(Integer::compare);

22.

Page 625 of 660


Java Book - Chidambaram.S

23. if (minVal.isPresent())
24. /*
25. * java 8 way System.out.println("Minimum value: " + minVal.ge
t());
26. */
27. //java 10 way
28. System.out.println("Minimum value: " + minVal.orElseThrow());

29. }
30. }
31.
32. Output
33.
34. Minimum value: 2

JEP 296: Consolidate the JDK Forest into a Single


Repository

For many years, the full code base of the JDK has been broken into numerous Mercurial repositories.

In JDK 9 there are eight repos: root, corba, hotspot, jaxp, jaxws, jdk, langtools, and nashorn.

This feature aims to consolidated the repositories into single repository.

During JDK's evolution it was separated into multiple repositories where as the bug fixes for even
single and simple bug fix affect different repositories and different commit operations, which increases
the over manitenance for current and future bug fixes.

To overcome this situation the JEP 296 is implemented.

This is internal change and doesn't affect our development process.

Page 626 of 660


Java Book - Chidambaram.S

JEP 304: Garbage Collector Interface

To make it simpler to add a new GC to HotSpot without disturbing the current


code base

and to make it easier to exclude a GC from a JDK build.

For GC developers, implementing a new garbage collector requires knowledge about all those
various places, and how to extend them for their specific needs in prior releases.

A cleaner GC interface would make it much easier to implement new collectors, it would make the code
much cleaner, and simpler to exclude one or several collectors at build time. Adding a new garbage
collector should be a matter of implementing a well documented set of interfaces such as
CollectedHeap and BarrierSet, rather than figuring out all the places in HotSpot that needs
changing.

This is mainly a refactoring of HotSpot internal code and GC developers can use this technique to
create new GC interface.

JEP 307: Parallel Full GC for G1


The G1 garbage collector is designed to avoid full collections, but when the concurrent collections can't
reclaim memory fast enough a fall back full GC will occur. The current implementation of the full GC for
G1 uses a single threaded mark-sweep-compact algorithm. We intend to parallelize the mark-sweep-
compact algorithm and use the same number of threads as the Young and Mixed collections do. The
number of threads can be controlled by the -XX:ParallelGCThreads option, but this will also affect the
number of threads used for Young and Mixed collections.

JEP 310: Application Class-Data Sharing


To improve startup and footprint, extend the existing Class-Data Sharing ("CDS") feature to allow
application classes to be placed in the shared archive.

Class-Data Sharing, introduced in JDK 5, allows a set of classes to be pre-processed into a shared
archive file that can then be memory-mapped at runtime to reduce startup time. It can also reduce
dynamic memory footprint when multiple JVMs share the same archive file.

Page 627 of 660


Java Book - Chidambaram.S

Currently CDS only allows the bootstrap class loader to load archived classes. Application CDS
("AppCDS") extends CDS to allow the built-in system class loader (a.k.a., the "app class loader"), the
built-in platform class loader, and custom class loaders to load archived classes.

JEP 312: Thread-Local Handshakes

Introduce a way to execute a callback on threads without performing a global VM


safepoint.

Make it both possible and cheap to stop individual threads and not just all
threads or none.

A handshake operation is a callback that is executed for each thread while that
thread is in a safepoint safe state. The callback is executed either by the
thread itself or by the VM thread while keeping the thread in a blocked state.

In new feature, the per thread operation will be performed on all threads as
soon as possible and they will continue to execute as soon as it’s own
operation is completed.

JEP 313: Remove the Native-Header Generation Tool

javah tool has been removed from JDK and which was used to generate C header
and source files that are needed to implement native methods.

In JDK 8, javac -h is introduced and this functionality provides the ability


to write native header files at the time that Java source code is compiled.

JEP 314: Additional Unicode Language-Tag Extensions

Page 628 of 660


Java Book - Chidambaram.S

Enhance java.util.Locale and related APIs to implement additional Unicode extensions of BCP 47
language tags. Support for BCP 47 language tags was initially added in Java SE 7, with support for the
Unicode locale extension limited to calendars and numbers. This JEP will implement more of the
extensions specified in the latest LDML specification, in the relevant JDK classes.

JEP 316: Heap Allocation on Alternative Memory


Devices
Some operating systems already expose non-DRAM memory through the file system. Examples
are NTFS DAX mode and ext4 DAX. Memory-mapped files in these file systems bypass the page cache
and provide a direct mapping of virtual memory to the physical memory on the device.

JEP 317: Experimental Java-Based JIT Compiler


Enable the Java-based JIT compiler, Graal, to be used as an experimental JIT compiler on the
Linux/x64 platform.

JEP 319: Root Certificates

Provide a default set of root Certification Authority (CA) certificates in the JDK. Open-source the root
certificates in Oracle's Java SE Root CA program in order to make OpenJDK builds more attractive to
developers, and to reduce the differences between those builds and Oracle JDK builds

Page 629 of 660


Java Book - Chidambaram.S

JEP 322: Time-Based Release Versioning

The Java language has undergone several changes since JDK 1.0 as well as
numerous additions of classes and packages to the standard library. Since
J2SE 1.4, the evolution of the Java language has been governed by the Java
Community Process (JCP), which uses Java Specification Requests (JSRs) to
propose and specify additions and changes to the Java platform. The language is
specified by the Java Language Specification (JLS); changes to the JLS are
managed under JSR 901.

Since java 9, proposed to change the release train to "one feature release every
six months" and LTS(Long Term Support) release once in three year. Currently
java 11 is the LTS release.

In prior releases, the version system idetified as JDK 7 Update 55, or JDK 7
Update 60. In this phrase

There is no way to understand about what this release contains.

For example, the version standards don't reveal the answer for the question
what's the difference between releases named "JDK 7 Update 60", "1.7.0_60", and
"JDK 7u60"?

The new model resolves this one with below naming standards.

$FEATURE.$INTERIM.$UPDATE.$PATCH

 $FEATURE — This counter will be incremented at every feature release regardless of release
content. The feature counter for the current release is 10. (Formerly $MAJOR.).
It will be incremented every six months: The March 2018 release is JDK 10, the September
2018 release is JDK 11, and so forth.
 $INTERIM — The interim-release counter, incremented for non-feature releases that
contain compatible bug fixes and enhancements but no incompatible changes, no feature
removals, and no changes to standard APIs. (Formerly $MINOR.)

Page 630 of 660


Java Book - Chidambaram.S

Since the six-month model does not include interim releases, this will always be zero. It is
reserved for flexibility, so that a future revision may include something like JDK $N.1 and
JDK $N.2 etc. For example, JDK 1.4.1 and 1.4.2 releases were interim releases, and
according to the new versioning system, they would have been numbered 4.1 and 4.2.
 $UPDATE — The update-release counter, incremented for compatible update releases that
fix security issues, regressions, and bugs in newer features. (Formerly $SECURITY, but with
a non-trivial incrementation rule.)
 The update-release counter, incremented for compatible update releases.
The April 2018 release will be JDK 10.0.1 with the update counter 1, the July release will
be JDK 10.0.2 with the update counter 2, and so forth.
 $PATCH — The emergency patch-release counter, incremented only when it's necessary to
produce an emergency release to fix a critical issue. (Using an additional element for this
purpose minimizes disruption to both developers and users of in-flight update releases.)
 The emergency patch-release counter, incremented only when it's necessary to produce an
emergency release to fix a critical issue

Page 631 of 660


Java Book - Chidambaram.S

Chapter 41 Java 11 Features

2018/09/25 General Availability

JEP 181: Nest-Based Access Control

Introduce nests, an access-control context that aligns with the existing notion
of nested types in the Java programming language. Nests allow classes that are
logically part of the same code entity, but which are compiled to distinct
class files, to access each other's private members without the need for
compilers to insert accessibility-broadening bridge methods.

JEP 330: Launch Single-File Source-Code Programs

This feature enables java command to directly run the program and internally it
will complete the compilation. This feature supports only run the single file
java program.

In this below example, HelloWorld.java contains the single file java program
and in java 8 it didn't work, where as after the path set to java 12 it is
working fine. The feature is added in java 11.

1. public class HelloWorld {


2. public static void main(String args[])
3. {
4. System.out.println("Hello Java");
5. }
6. }
7.
8.
9. Output in Dos console
10.
11. F:\Java_Office\sample_prgs\java11>set path=C:\Program Files\Java\jdk1.8.0_
66\bin
12.

Page 632 of 660


Java Book - Chidambaram.S

13. F:\Java_Office\sample_prgs\java11>java HelloWorld.java


14. Error: Could not find or load main class HelloWorld.java
15.
16. F:\Java_Office\sample_prgs\java11>set path=C:\Program Files\Java\jdk-
12.0.2\bin
17.
18. F:\Java_Office\sample_prgs\java11>java HelloWorld.java
19. Hello Java

Additions in java.lang.String

public boolean isBlank()

Returns true if the string is empty or contains only white space codepoints,
otherwise false.

It differs with isEmpty() - return true if length is 0 - added in java 1.6.


Let's see the below example with these two methods.

1. public class StringJava11Changes {


2. public static void main(String args[])
3. {
4. String str1=new String("Java 11 Features");
5. String str2=new String();
6. String str3=new String(" ");
7.
8. System.out.println("str1:isBlank()="+str1.isBlank());
9. System.out.println("str1:isEmpty()="+str1.isEmpty());
10.
11. System.out.println("str2:isBlank()="+str2.isBlank());
12. System.out.println("str2:isEmpty()="+str2.isEmpty());
13.
14. System.out.println("str3:isBlank()="+str3.isBlank());
15. System.out.println("str3:isEmpty()="+str3.isEmpty());
16.
17. }
18. }
19.
20. Output
21.
22. str1:isBlank()=false
23. str1:isEmpty()=false
24. str2:isBlank()=true
25. str2:isEmpty()=true

Page 633 of 660


Java Book - Chidambaram.S

26. str3:isBlank()=true
27. str3:isEmpty()=false

public Stream<String> lines()

Below program illustrates how lines() is working and splits into lines using \r
or \r\n delimiters

1. import java.util.Set;
2. import java.util.stream.Collectors;
3. import java.util.stream.Stream;
4.
5. public class StringIsBlankDemo {
6. public static void main(String args[])
7. {
8. String str1=new String("Java 11 Features\r\nJava 12 Features\rJava 13 Features");
9. Stream stream = str1.lines();
10. Set<String> set=(Set)stream.collect(Collectors.toSet());
11. set.forEach(System.out::println);
12.
13. }
14. }
15.
16. Output
17.
18. Java 13 Features
19. Java 11 Features
20. Java 12 Features

strip methods in String class

String strip()

Removes all leading and trailing whitespace removed.

String stripLeading():

Removing all leading whitespace removed.

String stripTrailing():

Removes trailing whitespace removed.

Page 634 of 660


Java Book - Chidambaram.S

You probably look at strip() and ask, “How is this different to the existing
trim() method?” The answer is that how whitespace is defined differs between
the two.

1. public class StringStripDemo {


2. public static void main(String args[])
3. {
4. String str1="\n Java Features in \n11 \n12 ";
5. String str2="Second String";
6. String stripedStr1=str1.strip();
7.
8. System.out.println("****** str1 ******");
9. System.out.println(str1);
10. System.out.println("End\n");
11.
12. System.out.println("****** striped str1 ******");
13. System.out.print("striped str1 strip()="+str1.strip());
14. System.out.println("End\n");
15.
16. System.out.println("****** leading striped str1 ******");
17. System.out.print("striped str1 stripLeading()="+str1.stripLeading());
18. System.out.println("End\n");
19.
20. System.out.println("****** trailing striped str1 ******");
21. System.out.print("striped str1 stripTrailing()="+str1.stripTrailing());
22. System.out.println("End");
23. }
24. }
25.
26. Output
27.
28. ****** str1 ******
29.
30. Java Features in
31. 11
32. 12
33. End
34.
35. ****** striped str1 ******
36. striped str1 strip()=Java Features in
37. 11
38. 12End
39.
40. ****** leading striped str1 ******
41. striped str1 stripLeading()=Java Features in
42. 11
43. 12 End
44.
45. ****** trailing striped str1 ******
46. striped str1 stripTrailing()=
47. Java Features in
48. 11
49. 12End

public String repeat(int count)


Page 635 of 660
Java Book - Chidambaram.S

1. class StringRepeatDemo {
2. public static void main(String args[])
3. {
4. String str = "String ";
5. System.out.println(str.repeat(10));
6. }
7. }
8.
9. Output
10.
11. String String String String String String String String String String

Local-Variable Syntax for Lambda Parameters

This feature allows var to be used when declaring the formal parameters of
implicitly typed lambda expressions.

In below example, the lambda expression formal parameters do not have types as
it is optional. This feature allows us to mention var along with the data type
as usual.

if we mention the type as var, must add param type to all formal parameter

Below examples are incorrect.

BigNumbers bigNumbers = (int num1, num2)

BigNumbers bigNumbers = (var num1, num2)

Below examples are correct

BigNumbers bigNumbers = (var num1,var num2)

BigNumbers bigNumbers = (int num1, int num2)

Page 636 of 660


Java Book - Chidambaram.S

1.
2. @FunctionalInterface
3. interface Addition {
4. public int addTwoNumbers(int num1, int mum2);
5. }
6.
7. @FunctionalInterface
8. interface BigNumbers {
9. public int findBigNumber(int num1, int mum2);
10. }
11.
12. public class LambdaAdditionsDemo {
13. public static void main(String[] args) {
14.
15. Addition addition = (num1, num2) -> num1 + num2;
16. BigNumbers bigNumbers = (num1, num2) -> {
17. if (num1 > num2)
18. return num1;
19. else
20. return num2;
21. };
22.
23. System.out.println(addition.addTwoNumbers(10, 5));
24.
25. System.out.println(bigNumbers.findBigNumber(10, 5));
26. System.out.println(bigNumbers.findBigNumber(1, 2));
27. }
28. }
29.
30. Output
31.
32. 15
33. 10
34. 2

Page 637 of 660


Java Book - Chidambaram.S

JEP 181: Nest-Based Access Control

In nested classes, Inner class can access the outer class private members. Let's see the below example.

Today private access between nestmates is not permitted by the JVM access rules. To provide the
permitted access a Java source code compiler has to introduce a level of indirection. For example, an
invocation of a private member is compiled into an invocation of a compiler-generated package-
private, bridging method in the target class, which in turn invokes the intended private method. These
access bridges are generated only as needed to satisfy the member accesses requested within the
nest.

1. class Outer {
2. private int pri_var = 10;
3.
4. private void privateMethod() {
5. System.out.println("private method");
6. }
7.
8. class Inner {
9. void innerMethod() {
10. System.out.println(pri_var);
11. privateMethod();
12. }
13. }
14. }
15.
16. public class NestDemo {
17.
18. public static void main(String[] args) {
19. // TODO Auto-generated method stub
20. Outer outer = new Outer();
21. Outer.Inner inner = outer.new Inner();
22. inner.innerMethod();
23. }
24.
25. }
26.
27. Output
28.
29. 10
30. private method

1. Using Java 8
2.
3. F:\Java_Office\sample_prgs\java11\nest>set path=C:\Program Files\Java\jdk1.8.0_66\bin
4.
5. F:\Java_Office\sample_prgs\java11\nest>javac NestDemo.java
6.
7. F:\Java_Office\sample_prgs\java11\nest>javap NestDemo.class
8. Compiled from "NestDemo.java"
9. public class NestDemo {
10. public NestDemo();
11. public static void main(java.lang.String[]);
12. }

Page 638 of 660


Java Book - Chidambaram.S

13.
14. F:\Java_Office\sample_prgs\java11\nest>javap Outer.class
15. Compiled from "NestDemo.java"
16. class Outer {
17. Outer();
18. static int access$000(Outer);
19. static void access$100(Outer);
20. }
21.
22. F:\Java_Office\sample_prgs\java11\nest>javap Outer$Inner.class
23. Compiled from "NestDemo.java"
24. class Outer$Inner {
25. final Outer this$0;
26. Outer$Inner(Outer);
27. void innerMethod();
28. }
29. Using Java 12
30.
31. F:\Java_Office\sample_prgs\java11\nest>set path=C:\Program Files\Java\jdk-12.0.2\bin
32.
33. F:\Java_Office\sample_prgs\java11\nest>javac NestDemo.java\
34. error: invalid flag: NestDemo.java\
35. Usage: javac <options> <source files>
36. use --help for a list of possible options
37.
38. F:\Java_Office\sample_prgs\java11\nest>javac NestDemo.java
39.
40. F:\Java_Office\sample_prgs\java11\nest>javap NestDemo.class
41. Compiled from "NestDemo.java"
42. public class NestDemo {
43. public NestDemo();
44. public static void main(java.lang.String[]);
45. }
46.
47. F:\Java_Office\sample_prgs\java11\nest>javap Outer.class
48. Compiled from "NestDemo.java"
49. class Outer {
50. Outer();
51. }
52.
53. F:\Java_Office\sample_prgs\java11\nest>javap Outer$Inner.class
54. Compiled from "NestDemo.java"
55. class Outer$Inner {
56. final Outer this$0;
57. Outer$Inner(Outer);
58. void innerMethod();
59. }

JEP 309: Dynamic Class-File Constants


Page 639 of 660
Java Book - Chidambaram.S

Just as the linkage of an invokedynamic call site involves an upcall from the JVM to Java-based linkage
logic, we can apply this same trick to the resolution of a constant-pool entry.
A CONSTANT_Dynamic constant-pool entry encodes the bootstrap method to perform the resolution
(a MethodHandle), the type of the constant (a Class), and any static bootstrap arguments (an
arbitrary sequence of constants, barring cycles in the constant pool between dynamic constants.)
We add a new constant-pool form, CONSTANT_Dynamic (new constant tag 17), which has two
components following its tag byte: the index of a bootstrap method, in the same format as the index
found in a CONSTANT_InvokeDynamic, and a CONSTANT_NameAndType, which encodes the expected type.

JEP 315: Improve Aarch64 Intrinsics

Improve the existing string and array intrinsics, and implement new intrinsics for
the java.lang.Math sin, cos and log functions, on AArch64 processors. Intrinsics are used to leverage
CPU architecture-specific assembly code which is executed instead of generic Java code for a given
method to improve performance. While most of the intrinsics are already implemented in AArch64 port,
optimized intrinsics for the following java.lang.Math methods are still missing:

 sin (sine trigonometric function)


 cos (cosine trigonometric function)
 log (logarithm of a number)
This JEP is intended to cover this gap by implementing optimized intrinsics for these methods.

JEP 318: Epsilon: A No-Op Garbage Collector


(Experimental)

Develop a GC that handles memory allocation but does not implement any actual memory reclamation
mechanism. Once the available Java heap is exhausted, the JVM will shut down.

Page 640 of 660


Java Book - Chidambaram.S

JEP 321: HTTP Client (Standard)

java.net.http.HttpClient API standardaized in Java 11 from its incubating version Java 9. The API provides non-blocking
request and response semantics through CompletableFutures, which can be chained to trigger
dependent actions. Back-pressure and flow-control of request and response bodies is provided for via
the Platform's reactive-streams support in thejava.util.concurrent.Flow API.

The implementation is now completely asynchronous (the previous HTTP/1.1 implementation was
blocking). Use of the RX Flow concept has been pushed down into the implementation, which
eliminated many of the original custom concepts needed to support HTTP/2. The flow of data can now
be more easily traced, from the user-level request publishers and response subscribers all the way
down to the underlying socket. This significantly reduces the number of concepts and complexity in the
code, and maximizes the possibility of reuse between HTTP/1.1 and HTTP/2.

HttpClient Example - Synchronous model

1. import java.net.URI;
2. import java.net.http.HttpClient;
3. import java.net.http.HttpClient.Redirect;
4. import java.net.http.HttpClient.Version;
5. import java.net.http.HttpRequest;
6. import java.net.http.HttpResponse;
7. import java.net.http.HttpResponse.BodyHandlers;
8. import java.time.Duration;
9. /* Synchronous HttpClient example */
10.
11. public class SyncHttpClientDemo {
12. public static void main(String args[])
13. {
14. try
15. {
16. HttpClient client = HttpClient.newBuilder()
17. .version(Version.HTTP_1_1)
18. .followRedirects(Redirect.NORMAL)
19. .connectTimeout(Duration.ofSeconds(20))
20.
21. .build();
22.
23. HttpRequest request1 = HttpRequest.newBuilder()
24. .uri(URI.create("http://www.example.com/"))
25. .GET()//used by default if we don't specify
26. .build();
27. HttpResponse<String> response1 = client.send(request1, BodyHandlers.ofString());
28. System.out.println(response1.statusCode());
29. System.out.println(response1.body());
30.
31.
32. HttpRequest request2 = HttpRequest.newBuilder()
33. .uri(URI.create("http://www.google.co.in/"))
34. .GET()//used by default if we don't specify

Page 641 of 660


Java Book - Chidambaram.S

35. .build();
36. HttpResponse<String> response2 = client.send(request2, BodyHandlers.ofString()
);
37. System.out.println(response2.statusCode());
38. System.out.println(response2.body());
39.
40.
41. }
42. catch(Exception e)
43. {
44. e.printStackTrace();
45. }
46. }
47. }
48.
49. Output
50.
51. Output from the HTML files

HttpClient example - Asynchronous model

1.
2. import java.net.URI;
3. import java.net.http.HttpClient;
4. import java.net.http.HttpRequest;
5. import java.net.http.HttpResponse;
6. import java.util.concurrent.CompletableFuture;
7. import java.util.concurrent.Executor;
8.
9. /* Asynchronous HttpClient example */
10. public class AsyncHttpClientDemo {
11.
12. public static void main(String[] args) {
13. //building request
14. HttpRequest request1 = HttpRequest.newBuilder()
15. .uri(URI.create("http://www.example.com/"))
16. .GET()//used by default if we don't specify
17. .build();
18.
19.
20. HttpRequest request2 = HttpRequest.newBuilder()
21. .uri(URI.create("http://www.google.co.in/"))
22. .GET()//used by default if we don't specify
23. .build();
24.
25.
26. //creating response body handler
27. HttpResponse.BodyHandler<String> bodyHandler = HttpResponse.BodyHandlers.ofString();
28.
29. //sending request and receiving response via HttpClient
30. HttpClient client = HttpClient.newHttpClient();
31.
32. System.out.println("Starting to access ... www.example.com");
33.
34. CompletableFuture<HttpResponse<String>> future1 = client.sendAsync(request1, bodyHandler);

Page 642 of 660


Java Book - Chidambaram.S

35. future1.thenApply(HttpResponse::body)
36. .thenAccept(System.out::println);
37.
38.
39. System.out.println("Completed access ... www.example.com");
40.
41. System.out.println("Starting to access ... www.google.co.in");
42.
43. CompletableFuture<HttpResponse<String>> future2 = client.sendAsync(request2, bodyHandler);
44. future2.thenApply(HttpResponse::body)
45. .thenAccept(System.out::println);
46.
47.
48. System.out.println("Completed ... www.google.co.in");
49.
50. }
51.
52. class ThreadPerTaskExecutor implements Executor {
53. public void execute(Runnable r) {
54. new Thread(r).start();
55. }
56. }
57. }
58. Output
59.
60. Output from the HTML files

Java 11 cahnges to note

JEP 324: Key Agreement with Curve25519 and Curve448


Implement key agreement using Curve25519 and Curve448 as described in RFC 7748. RFC 7748
defines a key agreement scheme that is more efficient and secure than the existing elliptic curve Diffie-
Hellman (ECDH) scheme. The primary goal of this JEP is an API and an implementation for this
standard.

JEP 327: Unicode 10


Upgrade existing platform APIs to support version 10.0 of the Unicode Standard.

Support the latest version of Unicode, mainly in the following classes:

 Character and String in the java.lang package,


 NumericShaper in the java.awt.font package, and
 Bidi, BreakIterator, and Normalizer in the java.text package.

Page 643 of 660


Java Book - Chidambaram.S

JEP 335: Deprecate the Nashorn JavaScript Engine


Deprecate the Nashorn JavaScript script engine and APIs and the jjs tool (added in Java 8) with the
intent to remove them in a future release.

The Nashorn JavaScript engine was first incorporated into JDK 8 via JEP 174 as a replacement for the
Rhino scripting engine. When it was released, it was a complete implementation of the ECMAScript-262
5.1 standard.

With the rapid pace at which ECMAScript language constructs, along with APIs, are adapted and
modified, we have found Nashorn challenging to maintain.

JEP 320: Remove the Java EE and CORBA Modules

Remove the Java EE and CORBA modules from the Java SE Platform and the JDK. These modules
were deprecated in Java SE 9 with the declared intent to remove them in a future release.

Java SE 6 included a full Web Services stack for the convenience of Java developers. The stack
consisted of four technologies that were originally developedfor the Java EE Platform: JAX-WS (Java
API for XML-Based Web Services), JAXB (Java Architecture for XML Binding), JAF (the JavaBeans
Activation Framework), and Common Annotations. At the time of inclusion, the versions in Java SE
were identical to the versions in Java EE, except for Java SE dropping a package in Common
Annotations that concerned the Java EE security model. However, over time, the versions in Java EE
evolved, which led to difficulties for the versions in Java SE:

1. Removal of thread functions: stop(Throwable obj) and destroy() objects have been
removed from the JDK 11 because they only
throw UnSupportedOperation and NoSuchMethodError respectively. Other than that, they
were of no use.

JEP 329: ChaCha20 and Poly1305 Cryptographic


Algorithms
Implement the ChaCha20 and ChaCha20-Poly1305 ciphers as specified in RFC 7539. ChaCha20 is a
relatively new stream cipher that can replace the older, insecure RC4 stream cipher. Provide ChaCha20
and ChaCha20-Poly1305 Cipher implementations. These algorithms will be implemented in the SunJCE
provider.

 Provide a KeyGenerator implementation that creates keys suitable for ChaCha20 and
ChaCha20-Poly1305 algorithms.

Page 644 of 660


Java Book - Chidambaram.S

 Provide an AlgorithmParameters implementation for use with the ChaCha20-Poly1305


algorithm.

The ChaCha20 and ChaCha20-Poly1305 algorithms will implement the javax.crypto.CipherSpi API
within the SunJCE provider. Ciphers will be instantiated in the same way as other ciphers, using
the Cipher.getInstance() method. For both ciphers, two acceptable transforms are allowed. The
single-name transform is the preferred approach, "ChaCha20" for ChaCha20 as a simple stream cipher
with no authentication, and "ChaCha20-Poly1305" for ChaCha20 as an AEAD cipher using Poly1305 as
the authenticator. "ChaCha20/None/NoPadding" and "ChaCha20-Poly1305/None/NoPadding" are also
acceptable transform strings, though no other mode or padding values
besides "None" and "NoPadding" will be accepted. Use of other mode or padding values will cause an
exception to be thrown.

JEP 328: Flight Recorder

About Java Flight Recorder

Flight Recorder records events originating from applications, the JVM and the OS. Events are stored in
a single file that can be attached to bug reports and examined by support engineers, allowing after-
the-fact analysis of issues in the period leading up to a problem. Tools can use an API to extract
information from recording files.

JFR is profiling tool used to gather diagnostics and profiling data from a running Java
application. It’s performance overhead is negligible and that’s usually below 1%. For short
running apps this overhead might be above that, because JFR requires some warm-up time on the
start.
Diagnosing faulty apps with JFR might shorten resolution times significantly. An anomaly can be
seem from its first emergence, as it unfolds and finally until that point when it causes the
application die. Of course, not all of the issues are that severe. JFR collects data about the
running threads, GC cycles, locks, sockets, memory usage and about a lot more.

Java Mission Control was also open sourced

JMC is a client tool used to open those production time performance and diagnostic
recordings JFR produced. JMC also delivers other features, such as a JMX console and a heap
dump analyzer. Oracle JDK releases from 7 to 10 contain JMC, but it has been separated and it’s
now available as a separate download.
JMC has was recently open sourced as well and that means that now the whole toolset
(JFR + JMC) are available to anyone using OpenJDK 11. At the time of writing, the first open
source JMC version 7 hasn’t reached GA yet, but early access builds are provided.
Page 645 of 660
Java Book - Chidambaram.S

JEP 331: Low-Overhead Heap Profiling

Provide a low-overhead way of sampling Java heap allocations, accessible via JVMTI.

Provide a way to get information about Java object heap allocations from the JVM that:
 Is low-overhead enough to be enabled by default continuously,
 Is accessible via a well-defined, programmatic interface,
 Can sample all allocations (i.e., is not limited to allocations that are in one particular heap
region or that were allocated in one particular way),
 Can be defined in an implementation-independent way (i.e., without relying on any
particular GC algorithm or VM implementation), and
 Can give information about both live and dead Java objects.

JEP 332: Transport Layer Security (TLS) 1.3

Implement version 1.3 of the Transport Layer Security (TLS) Protocol RFC 8446. TLS 1.3 is a new TLS
version which supersedes and obsoletes previous versions of TLS including version 1.2 (RFC 5246). It
also obsoletes or changes other TLS features such as the OCSP stapling extensions (RFC 6066, RFC
6961), and the session hash and extended master secret extension (RFC 7627).

The Java Secure Socket Extension (JSSE) in the JDK provides a framework and a Java implementation
of the SSL, TLS, and DTLS protocols. Currently, the JSSE API and JDK implementation supports SSL
3.0, TLS 1.0, TLS 1.1, TLS 1.2, DTLS 1.0 and DTLS 1.2.

JEP 333: ZGC: A Scalable Low-Latency Garbage


Collector (Experimental)
The Z Garbage Collector, also known as ZGC, is a scalable low-latency garbage collector. At a glance,
ZGC is a concurrent, single-generation, region-based, NUMA-aware, compacting collector. Stop-the-
world phases are limited to root scanning, so GC pause times do not increase with the size of the heap
or the live set.

A core design principle/choice in ZGC is the use of load barriers in combination with colored object
pointers (i.e., colored oops). This is what enables ZGC to do concurrent operations, such as object
relocation, while Java application threads are running. From a Java thread's perspective, the act of
loading a reference field in a Java object is subject to a load barrier. In addition to an object address, a
colored object pointer contains information used by the load barrier to determine if some action needs
to be taken before allowing a Java thread to use the pointer. For example, the object might have been
relocated, in which case the load barrier will detect the situation and take appropriate action.

Page 646 of 660


Java Book - Chidambaram.S

JEP 336: Deprecate the Pack200 Tools and API


Deprecate the pack200 and unpack200 tools, and the Pack200 API in java.util.jar.

Page 647 of 660


Java Book - Chidambaram.S

Chapter 42 Java 12 Features

2019/03/19 General Availability

Internal changes

JEP 189: Shenandoah: A Low-Pause-Time Garbage


Collector (Experimental)

Modern machines have more memory and more processors than ever before. Service
Level Agreement (SLA) applications guarantee response times of 10-500ms. In
order to meet the lower end of that goal we need garbage collection algorithms
which are efficient enough to allow programs to run in the available memory,
but also optimized to never interrupt the running program for more than a
handful of milliseconds. Shenandoah is an open-source low-pause time collector
for OpenJDK designed to move us closer to those goals.

Shenandoah trades concurrent cpu cycles and space for pause time improvements.
We've added an indirection pointer to every Java object which enables the GC
threads to compact the heap while the Java threads are running. Marking and
compacting are performed concurrently so we only need to pause the Java threads
long enough to scan the thread stacks to find and update the roots of the
object graph.

JEP 230: Microbenchmark Suite

The microbenchmark suite will be co-located with the JDK source code in a
single directory and, when built, will produce a single JAR file. Co-location
will simplify adding and locating benchmarks during development. When running
benchmarks, JMH provides powerful filtering capabilities that allow the user to

Page 648 of 660


Java Book - Chidambaram.S

run only the benchmarks that are currently of interest. The exact location
remains to be determined.

JEP 334: JVM Constants API

We define a family of value-based symbolic reference (JVMS 5.1) types, in the


new package java.lang.invoke.constant, capable of describing each kind of
loadable constant. A symbolic reference describes a loadable constant in purely
nominal form, separate from class loading or accessibility context. Some
classes can act as their own symbolic references (e.g., String); for linkable
constants we define a family of symbolic reference types
(ClassDesc, MethodTypeDesc, MethodHandleDesc, and DynamicConstantDesc) that contain
the nominal information to describe these constants

JEP 340: One AArch64 Port, Not Two

Two 64-bit ARM ports exist in the JDK. The main sources for these are in
the src/hotspot/cpu/arm and open/src/hotspot/cpu/aarch64 directories. Although both
ports produce aarch64 implementations, for the sake of this JEP we shall refer
to the former, which was contributed by Oracle, as arm64, and the latter
as aarch64.

JEP 341: Default CDS Archives

Modify the JDK build to run java -Xshare:dump after linking the image.
(Additional command-line options may be included to fine-tune GC heap size,
etc., in order to obtain better memory layout for common cases.) Leave the

Page 649 of 660


Java Book - Chidambaram.S

resulting CDS archive in the lib/server directory, so that it is part of the


resulting image.

Users will benefit from the CDS feature automatically, since -Xshare:auto was
enabled by default for the server VM in JDK 11 (JDK-8197967). To disable CDS,
run with -Xshare:off.

Users with more advanced requirements (e.g., using custom class lists that
include application classes, different GC configurations, etc.) can still
create a custom CDS archive as before.

JEP 344: Abortable Mixed Collections for G1

If G1 discovers that the collection set selection heuristics repeatedly select


the wrong number of regions, switch to a more incremental way of doing mixed
collections: split the collection set into two parts, a mandatory and an
optional part. The mandatory part comprises parts of the collection set that G1
cannot process incrementally (e.g., the young regions) but can also contain old
regions for improved efficiency. This may, e.g., be 80% of the predicted
collection set. The remaining 20% of the predicted collection set, which would
consist of only old regions, then forms the optional part.

After G1 finishes collecting the mandatory part, G1 starts collecting the


optional part at a much more granular level, if there is time left. The
granularity of collection of this optional part depends on the amount of time
left, at most down to one region at a time. After completing collection of any
part of the optional collection set, G1 can decide to stop the collection
depending on the remaining time.

As the predictions get more accurate again, the optional part of a collection
are made smaller and smaller, until the mandatory part once again comprises all
of the collection set (i.e., G1 completely relies on its heuristics). If the
predictions becomes inaccurate again, then the next collections will consist of
both a mandatory and optional part again.

Page 650 of 660


Java Book - Chidambaram.S

JEP 346: Promptly Return Unused Committed Memory


from G1

To accomplish the goal of returning a maximum amount of memory to the operating


system.

During inactivity of the application, periodically try to continue or trigger a


concurrent cycle to determine overall Java heap usage.

This will cause it to automatically return unused portions of the Java heap
back to the operating system. Optionally, under user control, a full GC can be
performed to maximize the amount of memory returned.

Development changes

JEP 12: Preview Language and VM Features

A preview language or VM feature is a new feature of the Java SE Platform


that is fully specified, fully implemented, and yet impermanent.

It is available in a JDK feature release to provoke developer feedback


based on real world use; this may lead to it becoming permanent in a future
Java SE Platform.

Switch Expressions

Page 651 of 660


Java Book - Chidambaram.S

Java 12 imporves the switch statement with the below features and released as a
preview feature.

Switch statement allows lambda expressons as the condition, and one or more
condition labels we can add.

No need to add break for every case. In previous releases it is must to prevent
the flow of control will fall through to subsequent cases. Also break now can
return the value too.

default case is now compulsory in switch Expressions.

To enable preview features in eclipse (version used : Version: 2019-06 (4.12.0)), we must
enable following properties in project properties dialog. To get this dialog,
right click on the project name and select properties.

Page 652 of 660


Java Book - Chidambaram.S

also you can notice that the compiler option selected as Java 12.

Page 653 of 660


Java Book - Chidambaram.S

Lets see the program example of switch

1. package java12Project;
2.
3. class SwitchDemo {
4. public static void main(String args[]) {
5. try {
6. int number = 5;
7. String result = switch (number) {
8. case 0, 1, 2, 3, 4, 5 -> "Number is less than or equal to 5";
9. case 6, 7, 8, 9, 10 -> "Number is greater than 5 and less than or equal to 10";
10. default -> {
11. if (number < 0)
12. break "Number is negative";
13. else
14. break "Number is positive and greater than 10";
15. }
16. };
17. System.out.println("result" + result);
18.
19. } catch (Exception e) {
20. e.printStackTrace();
21. }
22. }
23. }
24.
25. Output
26.
27. result=Number is less than or equal to 5

File.mismatch method

public static long mismatch(Path path, Path path2) throws


IOException

Finds and returns the position of the first mismatched byte in the content of
two files, or -1L if there is no mismatch. The position will be in the
inclusive range of 0L up to the size (in bytes) of the smaller file.

Two files are considered to match if they satisfy one of the following
conditions:

The two paths locate the same file, even if two equal paths locate a file does
not exist, or

Page 654 of 660


Java Book - Chidambaram.S

The two files are the same size, and every byte in the first file is identical
to the corresponding byte in the second file.

Otherwise there is a mismatch between the two files and the value returned by
this method is:

The position of the first mismatched byte, or

The size of the smaller file (in bytes) when the files are different sizes and
every

Parameters:

path the path to the first file

path2 the path to the second file

Returns:

the position of the first mismatch or -1L if no mismatch

Lets see the example program

1. import java.io.File;
2. import java.nio.file.Files;
3.
4. public class FileMismatchDemo {
5.
6. public static void main(String[] args) {
7. // TODO Auto-generated method stub
8. try {
9. File file1 = new File("FileMismatchDemo.java");
10. File file2 = new File("FileMismatchDemo.java");
11. long result = Files.mismatch(file1.toPath(), file2.toPath());
12. System.out.println("result=" + result);
13.
14. } catch (Exception e) {
15. e.printStackTrace();
16. }
17.
18. }
19. }

Page 655 of 660


Java Book - Chidambaram.S

20.
21. Output
22.
23. result=-1

Compact Number Format

public static NumberFormat getCompactNumberInstance()

getCompactNumberInstance method is used to get the compact number format to


format a number in shorter form. For example, 2000 can be formatted
as "2K" in US locale. Use getPercentInstance to get a format for displaying
percentages. With this format, a fraction like 0.53 is displayed as 53%.

Lets see the example below

1.
2. import java.text.NumberFormat;
3. import java.util.Locale;
4.
5. public class CompactNumberFormatDemo {
6.
7. public static void main(String[] args) {
8.
9. System.out.println("***** Default locale en US *****");
10.
11. NumberFormat numberFormat1 = NumberFormat.getCompactNumberInstance
();
12. // we can set the max fraction digits
13. // numberFormat1.setMaximumFractionDigits(1);
14. System.out.println(numberFormat1.format(2592356356534563D));
15. System.out.println(numberFormat1.format(259235));
16. System.out.println("***** en and CA Short format *****");
17. NumberFormat numberFormat2 = NumberFormat.getCompactNumberInstance
(new Locale("en", "CA"),
18. NumberFormat.Style.SHORT);
19. System.out.println(numberFormat2.format(2592356356534563D));
20. System.out.println(numberFormat2.format(259235));
21.

Page 656 of 660


Java Book - Chidambaram.S

22. System.out.println("***** en and CA Long format *****");


23. NumberFormat numberFormat3 = NumberFormat.getCompactNumberInstance
(new Locale("en", "CA"),
24. NumberFormat.Style.LONG);
25. System.out.println(numberFormat3.format(2592356356534563D));
26. System.out.println(numberFormat3.format(259235));
27.
28. }
29.
30. }
31.
32. Output
33.
34. ***** Default locale en US *****
35. 2592T
36. 259K
37. ***** en and CA Short format *****
38. 2592T
39. 259K
40. ***** en and CA Long format *****
41. 2592 trillion
42. 259 thousand

java.util.Stream class teeing() method

public static Collector teeing


(Collector downstream1, Collectordownstream2, BiFunction merger)

Returns a Collector that is a composite of two downstream collectors. Every


element passed to the resulting collector is processed by both downstream
collectors, then their results are merged using the specified merge function
into the final result.

Lets see the example below

1. import java.util.List;
2. import java.util.stream.Collector;
3. import java.util.stream.Collectors;
4. import java.util.stream.Stream;
5.

Page 657 of 660


Java Book - Chidambaram.S

6. public class CollectorsTeeingDemo {


7. public static void main(String[] args) {
8. Collector delimCollector = Collectors.joining("#");
9. Collector listCollector = Collectors.toList();
10.
11. Collector compositeCollector = Collectors.teeing(delimCollector,
listCollector,
12. (delim,list) -> {
13. ((List)list).add(delim);
14. return list.toString();
15. });
16.
17. String strings = Stream.of("item1", "item2").collect(compositeCol
lector).toString();
18. System.out.println(strings);
19. }
20. }
21.
22. Output
23.
24. [item1, item2, item1#item2]

Java Strings New Methods

public String indent(int n)

This method adjusts indentation of the given string's lines based on int n.
Postive numbers adds the space in each line and negative numbers removes the
space in each line.

If n > 0 then n spaces are inserted at the beginning of each line.

If n < 0 then up to n white space characters are removed from the beginning of
each line. Tab character will also be treated as single character.

Lets see the example program below.

1. public class StringIndentDemo {


2.
3. public static void main(String[] args) {
4. // TODO Auto-generated method stub
5.

Page 658 of 660


Java Book - Chidambaram.S

6. String str="\n\n line1 \n\t\t line 2 \n\n line3 ";


7.
8. System.out.println(str.indent(0));
9. System.out.println(str.indent(5));
10. System.out.println(str.indent(-5));
11.
12.
13. }
14.
15. }
16.
17. Output
18.
19.
20. line1
21. line 2
22.
23. line3
24.
25.
26.
27. line1
28. line 2
29.
30. line3
31.
32.
33.
34. line1
35. line 2
36.
37. line3

transform()

public <R> R transform(Function<? super String,? extends R> f)

This method allows the application of a function to this string. The function
should expect a single String argument and produce an R result.

Lets see the example below

Page 659 of 660


Java Book - Chidambaram.S

1.
2. public class StringTransformDemo {
3.
4. public static void main(String[] args) {
5. // TODO Auto-generated method stub
6.
7. String str = "10,15,3";
8.
9. String newStr[] = str.transform(s -> {
10. return s.split(",");
11. });
12.
13. for (String s : newStr)
14. System.out.println(s);
15.
16. }
17.
18. }
19.
20. Output
21.
22. 10
23. 15

Page 660 of 660

You might also like