Search for notes by fellow students, in your own course and all over the country.

Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.

My Basket

You have nothing in your shopping cart yet.

Title: learn java
Description: Beginning work online requires these rules

Document Preview

Extracts from the notes are below, to see the PDF you'll receive please use the links above


Java Tutorial

JAVA TUTORIAL

Simply Easy Learning by tutorialspoint
...
com

ABOUT THE TUTORIAL

Java Tutorial
Java is a high-level programming language originally developed by Sun Microsystems and released in
1995
...

This tutorial gives a complete understanding ofJava
...


Audience
This reference has been prepared for the beginners to help them understand the basic to advanced
concepts related to Java Programming language
...
com
...
com or this tutorial may not be redistributed or reproduced in any way, shape, or form
without the written permission of tutorialspoint
...
Failure to do so is a violation of copyright laws
...
If you discover that the tutorialspoint
...
com

TUTORIALS POINT
Simply Easy Learning

Table of Content
Java Tutorial
...
2
Prerequisites
...
2
Java Overview
...
16
Tools you will need:
...
16

Java Environment Setup
...
17
Setting up the path for windows 95/98/ME:
...
17
Popular Java Editors:
...
18

Java Basic Syntax
...
19
Basic Syntax:
...
20
Java Modifiers:
...
21
Java Arrays:
...
21
Example:
...
22
Comments in Java
...
22
Inheritance:
...
23
What is Next?
...
24
Objects in Java:
...
25
Constructors:
...
26
Implementing Singletons:
...
26
Example 2:
...
27
Accessing Instance Variables and Methods:
...
28
Source file declaration rules:
...
29
Import statements:
...
29
What is Next?
...
32
Primitive Data Types:
...
32
short:
...
33
long:
...
33
double:
...
34
char:
...
34
Java Literals:
...
36

Java Variable Types
...
37
Example:
...
38
Instance variables:
...
39
Class/static variables:
...
40
What is Next?
...
42
1
...
42
Default Access Modifier - No keyword:
...
42
Private Access Modifier - private:
...
43
Public Access Modifier - public:
...
43
Protected Access Modifier - protected:
...
44
Access Control and Inheritance:
...
Non Access Modifiers
...
45
Non Access Modifiers:
...
45
Non Access Modifiers:
...
46

Java Basic Operators
...
47
The Relational Operators:
...
49
The Bitwise Operators:
...
50
The Logical Operators:
...
51
The Assignment Operators:
...
52
Misc Operators
...
53
instanceof Operator:
...
54
What is Next?
...
56
The while Loop:
...
56
Example:
...
while Loop:
...
57
Example:
...
58
Syntax:
...
58
Enhanced for loop in Java:
...
59
Example:
...
59
Syntax:
...
60
TUTORIALS POINT
Simply Easy Learning

The continue Keyword:
...
60
Example:
...
61

Java Decision Making
...
62
Syntax:
...
62
The if
...
63
Syntax:
...
63
The if
...
else Statement:
...
63
Example:
...
else Statement:
...
64
Example:
...
65
Syntax:
...
65
What is Next?
...
67
Example:
...
68
xxxValue()
...
70
equals()
...
72
toString()
...
74
abs()
...
76
floor()
...
78
round()
...
79
max()
...
81
log()
...
82
sqrt()
...
84
cos()
...
86
asin()
...
87
atan()
...
89
toDegrees()
...
90
random()
...
92

Java Characters
...
93
Example:
...
93
Example:
...
94
isLetter()
...
96
isWhitespace()
...
97
isLowerCase()
...
99
toLowerCase()
...
100
What is Next?
...
102
Creating Strings:
...
102
Concatenating Strings:
...
103
String Methods:
...
106
int compareTo(Object o)
...
108
int compareToIgnoreCase(String str)
...
110
TUTORIALS POINT
Simply Easy Learning

boolean contentEquals(StringBuffer sb)
...
112
boolean endsWith(String suffix)
...
114
boolean equalsIgnoreCase(String anotherString)
...
115
byte[] getBytes(String charsetName)
...
118
int hashCode()
...
120
int indexOf(int ch, int fromIndex)
...
123
int indexOf(String str, int fromIndex)
...
125
int lastIndexOf(int ch)
...
128
int lastIndexOf(String str)
...
131
int length()
...
133
boolean regionMatches(boolean ignoreCase, int toffset,
...
134
boolean regionMatches(int toffset, String other, int ooffset, int len)
...
137
String replaceAll(String regex, String replacement)
...
138
String[] split(String regex)
...
141
boolean startsWith(String prefix)
...
143
CharSequence subSequence(int beginIndex, int endIndex)
...
145
String substring(int beginIndex, int endIndex)
...
147
String toLowerCase()
...
149
String toString()
...
150
String toUpperCase(Locale locale)
...
152
static String valueOf(primitive data type x)
...
156
Declaring Array Variables:
...
156
Creating Arrays:
...
157
Processing Arrays:
...
157
The foreach Loops:
...
158
Passing Arrays to Methods:
...
159
The Arrays Class:
...
160
Getting Current Date & Time
...
161
Date Formatting using SimpleDateFormat:
...
162
Date Formatting using printf:
...
164
Parsing Strings into Dates:
...
165
Measuring Elapsed Time:
...
166
Example:
...
170
Capturing Groups:
...
171
Regular Expression Syntax:
...
172
Index Methods:
...
173
Replacement Methods:
...
173
The matches and lookingAt Methods:
...
175
The appendReplacement and appendTail Methods:
...
176
TUTORIALS POINT
Simply Easy Learning

Java Methods
...
177
Example:
...
178
Example:
...
179
Example:
...
179
Example:
...
180
Using Command-Line Arguments:
...
181
The Constructors:
...
182
Example:
...
183
Example:
...
184

Java Streams, Files and I/O
...
185
Character Streams
...
187
Reading and Writing Files:
...
188
ByteArrayInputStream
...
189
DataInputStream
...
191
FileOutputStream:
...
192
Example:
...
194
Example:
...
195
File Navigation and I/O:
...
196
Example:
...
199
Example:
...
200
Example:
...
202
Creating Directories:
...
202

Java Exceptions
...
204
Exceptions Methods:
...
206
Example:
...
207
Example:
...
208
The finally Keyword
...
209
Declaring you own Exception:
...
210
Common Exceptions:
...
213
IS-A Relationship:
...
214
Example:
...
214
HAS-A relationship:
...
216
Example:
...
217
Using the super keyword:
...
219
Example:
...
220

Java Abstraction
...
223
Extending Abstract Class:
...
225

Java Encapsulation
...
227
Benefits of Encapsulation:
...
229
TUTORIALS POINT
Simply Easy Learning

Declaring Interfaces:
...
230
Example:
...
230
Extending Interfaces:
...
232
Tagging Interfaces:
...
233
Creating a package:
...
233
The import Keyword:
...
234
The Directory Structure of Packages:
...
236

Java Data Structures
...
238
Example:
...
239
Example:
...
242
Example:
...
246
Example:
...
247
Map Interface
...
249
The Hashtable
...
251
The Properties
...
253

Java Collections
...
255
The Collection Classes:
...
257
How to use an Iterator?
...
258
The Methods Declared by Iterator:
...
259
Example:
...
260
Using Java Comparator
...
260
The equals Method:
...
261
Summary:
...
263
Generic Methods:
...
263
Bounded Type Parameters:
...
264
Generic Classes:
...
265

Java Serialization
...
268
Deserializing an Object:
...
270
Url Processing
...
271
Example:
...
272
Example:
...
274
ServerSocket Class Methods:
...
276
InetAddress Class Methods:
...
277
Socket Server Example:
...
280
Send a Simple E-mail:
...
281
Send Attachment in E-mail:
...
284

Java Multithreading
...
285
Thread Priorities:
...
286
STEP 1:
...
286
TUTORIALS POINT
Simply Easy Learning

STEP 3
...
287
Create Thread by Extending Thread Class:
...
288
STEP 2
...
288
Thread Methods:
...
290
Major Java Multithreading Concepts:
...
292
Multithreading example without Synchronization:
...
294
Handling threads inter communication
...
296
Handling threads deadlock
...
297
Deadlock Solution Example:
...
299
Example:
...
302
Life Cycle of an Applet:
...
303
The Applet CLASS:
...
304
Getting Applet Parameters:
...
306
Application Conversion to Applets:
...
307
Displaying Images:
...
309

Java Documentation
...
311
The javadoc Tags:
...
313

Java Library Classes
...
0 [J2SE])
...
With the advancement of Java
and its widespread popularity, multiple configurations were built to suite various types of platforms
...

Sun Microsystems has renamed the new J2 versions as Java SE, Java EE and Java ME, respectively
...

Java is:


Object Oriented: In Java, everything is an Object
...




Platform independent: Unlike many other programming languages including C and C++, when Java is
compiled, it is not compiled into platform specific machine, rather into platform independent byte code
...




Simple:Java is designed to be easy to learn
...




Secure: With Java's secure feature, it enables to develop virus-free, tamper-free systems
...




Architectural-neutral:Java compiler generates an architecture-neutral object file format, which makes
the compiled code to be executable on many processors, with the presence of Java runtime system
...
Compiler inJava is written in ANSI C with a clean portability boundary
which is a POSIX subset
...




Multithreaded: With Java's multithreaded feature, it is possible to write programs that can do many tasks
simultaneously
...


TUTORIALS POINT
Simply Easy Learning



Interpreted:Java byte code is translated on the fly to native machine instructions and is not stored
anywhere
...




High Performance: With the use of Just-In-Time compilers, Java enables high performance
...




Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to adapt to an
evolving environment
...


History of Java:
James Gosling initiated the Java language project in June 1991 for use in one of his many set-top box projects
...

Sun released the first public implementation as Java 1
...
It promised Write Once, Run
Anywhere (WORA), providing no-cost run-times on popular platforms
...

On 8 May 2007, Sun finished the process, making all of Java's core code free and open-source, aside from a small
portion of code to which Sun did not hold the copyright
...

You also will need the following softwares:


Linux 7
...




Java JDK 5



Microsoft Notepad or any other text editor

This tutorial will provide the necessary skills to create GUI, networking, and Web applications using Java
...
Finally, it instructs you on how to
install Java and prepare an environment to develop Java applications
...
This section

guides you on how to download and set up Java on your machine
...

Java SE is freely available from the link Download Java
...

Follow the instructions to download Java and run the
...
Once you installed Java
on your machine, you would need to set environment variables to point to correct installation directories:

Setting up the path for windows 2000/XP:
Assuming you have installed Java in c:\Program Files\java\jdk directory:


Right-click on 'My Computer' and select 'Properties'
...




Now, alter the 'Path' variable so that it also contains the path to the Java executable
...


Setting up the path for windows 95/98/ME:
Assuming you have installed Java in c:\Program Files\java\jdk directory:


Edit
the
'C:\autoexec
...
Refer to your
shell documentation if you have trouble doing this
...
bashrc: export
PATH=/path/to/java:$PATH'

TUTORIALS POINT
Simply Easy Learning

Popular Java Editors:
To write your Java programs, you will need a text editor
...
But for now, you can consider one of the following:




Notepad: On Windows machine, you can use any simple text editor like Notepad (Recommended for this
tutorial), TextPad
...
netbeans
...
html
...
eclipse
...


What is Next?
Next chapter will teach you how to write and run your first Java program and some of the important basic syntaxes
in Java needed for developing applications
...
Let us now briefly look into what do class, object, methods and instance variables
mean
...
Example: A dog has states-color, name, breed as well as
behaviors -wagging, barking, eating
...

Class - A class can be defined as a template/blue print that describes the behaviors/states that object of its
type support
...
A class can contain many methods
...

Instance Variables - Each object has its unique set of instance variables
...


First Java Program:
Let us look at a simple code that would print the words Hello World
...

* This will print 'Hello World' as the output
*/
public static void main(String[]args){
System
...
println("Hello World");// prints Hello World
}
}
Let's look at how to save the file, compile and run the program
...




Save the file as: MyFirstJavaProgram
...




Open a command prompt window and go o the directory where you saved the class
...




Type ' javac MyFirstJavaProgram
...
If there are no errors in your
code, the command prompt will take you to the next line(Assumption : The path variable is set)
...




You will be able to see ' Hello World ' printed on the window
...
java
C :> java MyFirstJavaProgram
HelloWorld

Basic Syntax:
About Java programs, it is very important to keep in mind the following points
...




Class Names - For all class names, the first letter should be in Upper Case
...

Example class MyFirstJavaClass



Method Names - All method names should start with a Lower Case letter
...

Example public void myMethodName()



Program File Name - Name of the program file should exactly match the class name
...
java' to the end of the name (if the file name and the class name do not match your program will not compile)
...
java'



public static void main(String args[]) - Java program processing starts from the main() method, which is a
mandatory part of every Java program
...
Names used for classes, variables and methods are called identifiers
...
They are as follows:


All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore (_)
...




A keyword cannot be used as an identifier
...




Examples of legal identifiers:age, $salary, _value, __1_value



Examples of illegal identifiers: 123abc, -salary

TUTORIALS POINT
Simply Easy Learning

Java Modifiers:
Like other languages, it is possible to modify classes, methods, etc
...
There are two categories
of modifiers:



Access Modifiers: default, public, protected, private
Non-access Modifiers: final, abstract, strictfp

We will be looking into more details about modifiers in the next section
...
However, an array itself is an object on the heap
...


Java Enums:
Enums were introduced in java 5
...
Enums restrict a variable to have one of only a few predefined values
...

With the use of enums, it is possible to reduce the number of bugs in your code
...
This would make sure that it would not allow anyone to order any size other than the
small, medium or large
...
size =FreshJuice
...
MEDUIM ;
}
}
Note: enums can be declared as their own or inside a class
...


TUTORIALS POINT
Simply Easy Learning

Java Keywords:
The following list shows the reserved words in Java
...

abstract

assert

boolean

break

byte

case

catch

char

class

const

continue

default

do

double

else

enum

extends

final

finally

float

for

goto

if

implements

import

instanceof

int

interface

long

native

new

package

private

protected

public

return

short

static

strictfp

super

switch

synchronized

this

throw

throws

transient

try

void

volatile

while

Comments in Java
Java supports single-line and multi-line comments very similar to c and c++
...

public class MyFirstJavaProgram{
/* This is my first java program
...

*/
public static void main(String[]args){
// This is an example of single line comment
/* This is also an example of single line comment
...
out
...


Inheritance:
Java classes can be derived from classes
...


TUTORIALS POINT
Simply Easy Learning

This concept allows you to reuse the fields and methods of the existing class without having to rewrite the code in a
new class
...


Interfaces:
In Java language, an interface can be defined as a contract between objects on how to communicate with each
other
...

An interface defines the methods, a deriving class(subclass) should use
...


What is Next?
The next section explains about Objects and classes in Java programming
...


TUTORIALS POINT
Simply Easy Learning

4

CHAPTER

Java Object & Classes

J

ava is an Object-Oriented Language
...




Object - Objects have states and behaviors
...
An object is an instance of a class
...


Objects in Java:
Let us now look deep into what are objects
...
All these objects have a state and behavior
...

Software objects also have a state and behavior
...

So in software development, methods operate on the internal state of an object and the object-to-object
communication is done via methods
...

A sample of a class is given below:
public class Dog{
String breed;
int age;
String color;
void barking(){
}
void hungry(){
}
void sleeping(){
}
}
A class can contain any of the following variable types
...
The
variable will be declared and initialized within the method and the variable will be destroyed when the method
has completed
...
These variables
are instantiated when the class is loaded
...

Class variables: Class variables are variables declared within a class, outside any method, with the static
keyword
...
In the above example,
barking(), hungry() and sleeping() are methods
...


Constructors:
When discussing about classes, one of the most important subtopic would be constructors
...
If we do not explicitly write a constructor for a class the Java compiler builds a default constructor for
that class
...
The main rule of constructors is that they
should have the same name as the class
...

Example of a constructor is given below:
public class Puppy{
public Puppy(){
}
public Puppy(String name){
// This constructor has one parameter, name
...


TUTORIALS POINT
Simply Easy Learning

Singleton Classes
The Singleton's purpose is to control object creation, limiting the number of objects to one only
...

Singletons often control access to resources such as database connections or sockets
...


Implementing Singletons:
Example 1:
The easiest implementation consists of a private constructor and a field to hold its result, and a static accessor
method with a name like getInstance()
...
The
getInstance( ) method (which must be public) then simply returns this instance:
// File Name: Singleton
...

*/
private Singleton(){}
/* Static 'instance' method */
public static Singleton getInstance(){
return singleton;
}
/* Other methods protected by singleton-ness */
protected static void demoMethod(){
System
...
println("demoMethod for singleton");
}
}
// File Name: SingletonDemo
...
getInstance();
tmp
...

}
public static ClassicSingleton getInstance(){
if(instance ==null){
instance =new ClassicSingleton();
}
return instance;
}
}
The ClassicSingleton class maintains a static reference to the lone singleton instance and returns that reference
from the static getInstance() method
...
This technique ensures
that singleton instances are created only when needed
...
So basically an object is created from a class
...

There are three steps when creating an object from a class:




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

Initialization: The 'new' keyword is followed by a call to a constructor
...


Example of creating an object is given below:
public class Puppy{
public Puppy(String name){
// This constructor has one parameter, name
...
out
...
To access an instance variable the fully qualified
path should be as follows:
/* First create an object */
ObjectReference = new Constructor();
/* Now call a variable as follows */

TUTORIALS POINT
Simply Easy Learning

ObjectReference
...
MethodName();

Example:
This example explains how to access instance variables and methods of a class:
public class Puppy{
int puppyAge;
public Puppy(String name){
// This constructor has one parameter, name
...
out
...
out
...
setAge(2);
/* Call another class method to get puppy's age */
myPuppy
...
out
...
puppyAge );
}
}
If we compile and run the above program, then it would produce the following result:
PassedName is:tommy
Puppy's age is :2
Variable Value :2

Source file declaration rules:
As the last part of this section, let’s now look into the source file declaration rules
...



There can be only one public class per source file
...




The public class name should be the name of the source file as well which should be appended by
...
For example : The class name is
...
java
...




If import statements are present then they must be written between the package statement and the class
declaration
...




Import and package statements will imply to all the classes present in the source file
...


Classes have several access levels and there are different types of classes; abstract classes, final classes, etc
...

Apart from the above mentioned types of classes, Java also has some special classes called Inner classes and
Anonymous classes
...
When developing applications in Java, hundreds of
classes and interfaces will be written, therefore categorizing these classes is a must as well as makes life much
easier
...
Import statement is a way of giving the proper location for the compiler to
find that particular class
...
io
...
They are Employee and EmployeeTest
...
Remember this is the Employee class and the class is a public
class
...
java
...
The class has one explicitly
defined constructor, which takes a parameter
...
io
...
name = name;
}
// Assign the age of the Employee to the variable age
...
*/
public void empDesignation(String empDesig){
designation = empDesig;
}
/* Assign the salary to the variable salary
...
out
...
out
...
out
...
out
...
Therefore in-order for us to run this
Employee class there should be main method and objects should be created
...

Given below is the EmployeeTest class, which creates two instances of the class Employee and invokes the
methods for each object to assign values for each variable
...
java file
import java
...
*;
publicclassEmployeeTest{
publicstaticvoid main(String args[]){
/* Create two objects using constructor */
Employee empOne =newEmployee("James Smith");
Employee empTwo =newEmployee("Mary Anne");
// Invoking methods for each object created
empOne
...
empDesignation("Senior Software Engineer");
empOne
...
printEmployee();
empTwo
...
empDesignation("Software Engineer");
empTwo
...
printEmployee();
}
}
Now, compile both the classes and then run EmployeeTest to see the result as follows:
C :> javac Employee
...
java
C :> javac EmployeeTest
...
0
Name:MaryAnne
Age:21
Designation:SoftwareEngineer

TUTORIALS POINT
Simply Easy Learning

Salary:500
...


TUTORIALS POINT
Simply Easy Learning

5

CHAPTER

Java Basic Data Types

V

ariables are nothing but reserved memory locations to store values
...

Based on the data type of a variable, the operating system allocates memory and decides what can be stored in
the reserved memory
...

There are two data types available in Java:


Primitive Data Types



Reference/Object Data Types

Primitive Data Types:
There are eight primitive data types supported by Java
...
Let us now look into detail about the eight primitive data types
...




Minimum value is -128 (-2^7)



Maximum value is 127 (inclusive)(2^7 -1)



Default value is 0



Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is four times
smaller than an int
...


TUTORIALS POINT
Simply Easy Learning



Minimum value is -32,768 (-2^15)



Maximum value is 32,767(inclusive) (2^15 -1)



Short data type can also be used to save memory as byte data type
...




Example: short s= 10000, short r = -20000

int:


int data type is a 32-bit signed two's complement integer
...
(-2^31)



Maximum value is 2,147,483,647(inclusive)
...




The default value is 0
...




Minimum value is -9,223,372,036,854,775,808
...
(2^63 -1)



This type is used when a wider range than int is needed
...




Example: int a = 100000L, int b = -200000L

float:


Float data type is a single-precision 32-bit IEEE 754 floating point
...




Default value is 0
...




Float data type is never used for precise values such as currency
...
5f

TUTORIALS POINT
Simply Easy Learning

double:


double data type is a double-precision 64-bit IEEE 754 floating point
...




Double data type should never be used for precise values such as currency
...
0d
...
4

boolean:


boolean data type represents one bit of information
...




This data type is used for simple flags that track true/false conditions
...




Example: boolean one = true

char:


char data type is a single 16-bit Unicode character
...




Maximum value is '\uffff' (or 65,535 inclusive)
...




Example: char letterA ='A'

Reference Data Types:


Reference variables are created using defined constructors of the classes
...

These variables are declared to be of a specific type that cannot be changed
...




Class objects and various types of array variables come under reference data type
...




A reference variable can be used to refer to any object of the declared type or any compatible type
...
They are represented directly in the code without any
computation
...
For example:
byte a =68;
char a ='A'
byte, int, long, and short can be expressed in decimal(base 10),hexadecimal(base 16) or octal(base 8) number
systems as well
...

For example:
int decimal=100;
int octal =0144;
int hexa =0x64;
String literals in Java are specified like they are in most other languages by enclosing a sequence of characters
between a pair of double quotes
...
For example:
char a ='\u0001';
String a ="\u0001";
Java language supports few special escape sequences for String and char literals as well
...
This will
give you a good understanding about how they can be used in the Java classes, interfaces, etc
...
Each variable in Java has a

specific type, which determines the size and layout of the variable's memory; the range of values that can be
stored within that memory; and the set of operations that can be applied to the variable
...
The basic form of a variable declaration is shown here:
data type variable [ = value][, variable [= value]
...
To declare more than one
variable of the specified type, you can use a comma-separated list
...
14159;
char a = 'a';

//
//
//
//
//

Declares three ints, a, b, and c
...

declares and assigns a value of PI
...
There are three kinds of variables in
Java:



Local variables



Instance variables



Class/static variables

Local variables:


Local variables are declared in methods, constructors, or blocks
...




Access modifiers cannot be used for local variables
...




Local variables are implemented at stack level internally
...


Example:
Here, age is a local variable
...

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

public class Test{
public void pupAge(){
int age;
age = age + 7;
System
...
println("Puppy age is : " + age);
}
public static void main(String args[]){
Test test = new Test();
test
...
java:4:variable number might not have been initialized
age = age + 7;
^
1 error

Instance variables:


Instance variables are declared in a class, but outside a method, constructor or any block
...


TUTORIALS POINT
Simply Easy Learning



Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when
the object is destroyed
...




Instance variables can be declared in class level before or after use
...




The instance variables are visible for all methods, constructors and block in the class
...
However visibility for subclasses can be given for
these variables with the use of access modifiers
...
For numbers the default value is 0, for Booleans it is false and for object
references it is null
...




Instance variables can be accessed directly by calling the variable name inside the class
...
ObjectReference
...


Example:
import java
...
*;
public class Employee{
// this instance variable is visible for any child class
...

private double salary;
// The name variable is assigned in the constructor
...

public void setSalary(double empSal){
salary = empSal;
}
// This method prints the employee details
...
out
...
out
...
setSalary(1000);
empOne
...
0

Class/static variables:


Class variables also known as static variables are declared with the static keyword in a class, but outside a
method, constructor or a block
...




Static variables are rarely used other than being declared as constants
...
Constant variables never change from their initial value
...
It is rare to use static variables other than declared final and used
as either public or private constants
...




Visibility is similar to instance variables
...




Default values are same as instance variables
...
Values can be assigned during the declaration or within the constructor
...




Static variables can be accessed by calling with the class name
...
VariableName
...
If
the static variables are not public and final the naming syntax is the same as instance and local variables
...
io
...
out
...
DEPARTMENT

TUTORIALS POINT
Simply Easy Learning

access

from

an

outside

class

the

constant

should

be

accessed

as

What is Next?
You already have used access modifiers ( public & private ) in this chapter
...


TUTORIALS POINT
Simply Easy Learning

7

CHAPTER

Java Modifier Types

M

odifiers arekeywords that you add to those definitions to change their meanings
...
Java Access Modifiers
Java provides a number of access modifiers to set access levels for classes, variables, methods and constructors
...
No modifiers are needed
...




Visible to the world (public)
...


Default Access Modifier - No keyword:
Default access modifier means we do not explicitly declare an access modifier for a class, field, method, etc
...
The fields in an interface are implicitly public static final and the methods in an interface are by default
public

Example:
Variables and methods can be declared without any modifiers, as in the following examples:
String version ="1
...
1";
boolean processOrder(){
return true;
}

TUTORIALS POINT
Simply Easy Learning

Private Access Modifier - private:
Methods, Variables and Constructors that are declared private can only be accessed within the declared class itself
...
Class and interfaces cannot be private
...

Using the private modifier is the main way that an object encapsulates itself and hide data from the outside world
...
format;
}
public void setFormat(String format){
this
...

So to make this variable available to the outside world, we defined two public methods: getFormat(), which returns
the value of format, and setFormat(String), which sets its value
...
Therefore fields,
methods, blocks declared inside a public class can be accessed from any class belonging to the Java Universe
...

Because of class inheritance, all public methods and variables of a class are inherited by its subclasses
...

}
The main() method of an application has to be public
...


Protected Access Modifier - protected:
Variables, methods and constructors which are declared protected in a superclass can be accessed only by the
subclasses in other package or any class within the package of the protected members' class
...
Methods, fields can be declared protected,
however methods and fields in a interface cannot be declared protected
...


Example:
The following parent class uses protected access control, to allow its child class overrideopenSpeaker() method:
class AudioPlayer{
protected boolean openSpeaker(Speaker sp){
// implementation details
}
}
class StreamingAudioPlayer{
boolean openSpeaker(Speaker sp){
// implementation details
}
}
Here, if we define openSpeaker() method as private, then it would not be accessible from any other class other
than AudioPlayer
...
But our
intension is to expose this method to its subclass only, thats why we usedprotected modifier
...




Methods declared protected in a superclass must either be protected or public in subclasses; they cannot be
private
...




Methods declared private are not inherited at all, so there is no rule for them
...
Non Access Modifiers
To use a modifier, you include its keyword in the definition of a class, method, or variable
...

}
private boolean myFlag;
static final double weeks =9
...

The four access levels are:


Visible to the package
...
No modifiers are needed
...




Visible to the world (public)
...


Non Access Modifiers:
Java provides a number of non-access modifiers to achieve many other functionality
...

The abstract modifier for creating abstract classes and methods
...


To use a modifier, you include its keyword in the definition of a class, method, or variable
...

}
private boolean myFlag;
static final double weeks =9
...

The four access levels are:


Visible to the package
...
No modifiers are needed
...




Visible to the world (public)
...


Non Access Modifiers:
Java provides a number of non-access modifiers to achieve many other functionality
...

The abstract modifier for creating abstract classes and methods
...


What is Next?
In the next section, I will be discussing about Basic Operators used in the Java Language
...


TUTORIALS POINT
Simply Easy Learning

8

CHAPTER

Java Basic Operators

J

ava provides a rich set of operators to manipulate variables
...
The
following table lists the arithmetic operators:
Assume integer variable A holds 10 and variable B holds 20, then:
Operator Description

Example

+

Addition - Adds values on either side of the operator

A + B will give 30

-

Subtraction - Subtracts right hand operand from left hand operand

A - B will give -10

*

Multiplication - Multiplies values on either side of the operator

A * B will give 200

/

Division - Divides left hand operand by right hand operand

B / A will give 2

%

Modulus - Divides left hand operand by right hand operand and returns
remainder

B % A will give 0

++

Increment - Increases the value of operand by 1

B++ gives 21

--

Decrement - Decreases the value of operand by 1

B-- gives 19

TUTORIALS POINT
Simply Easy Learning

Example
The following simple example program demonstrates the arithmetic operators
...
java file and compile and run this program:
public class Test{
public static void main(String args[]){
int a =10;
int b =20;
int c =25;
int d =25;
System
...
println("a + b = "+(a + b));
System
...
println("a - b = "+(a - b));
System
...
println("a * b = "+(a * b));
System
...
println("b / a = "+(b / a));
System
...
println("b % a = "+(b % a));
System
...
println("c % a = "+(c % a));
System
...
println("a++
= "+(a++));
System
...
println("b-= "+(a--));
// Check the difference in d++ and ++d
System
...
println("d++
= "+(d++));
System
...
println("++d
= "+(++d));
}
}
This would produce the following result:
a + b =30
a - b =-10
a * b =200
b / a =2
b % a =0
c % a =5
a++=10
b--=11
d++=25
++d
=27

The Relational Operators:
There are following relational operators supported by Java language:
Assume variable A holds 10 and variable B holds 20, then:
Operator Description

Example

==

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

equal then condition becomes true
...


(A > B) is not true
...


(A < B) is true
...


(A >= B) is not true
...


<=

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


Example
The following simple example program demonstrates the relational operators
...
java file and compile and run this program
...
out
...
out
...
out
...
out
...
out
...
out
...

Bitwise operator works on bits and performsbit-by-bit operation
...


|

Binary OR Operator copies a bit if it exists in either
(A | B) will give 61 which is 0011 1101
operand
...


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

~

Binary Ones Complement Operator is unary and
has the effect of 'flipping' bits
...
The left operands value
is moved left by the number of bits specified by
A << 2 will give 240 which is 1111 0000
the right operand
...
The left operands
value is moved right by the number of bits
specified by the right operand
...
The left operands
value is moved right by the number of bits
specified by the right operand and shifted values
are filled up with zeros
...
Copy and paste the following Java
program in Test
...
out
...
out
...
out
...
out
...
out
...
out
...
out
...
If both the operands are non-zero, then the
(A && B) is false
...


||

Called Logical OR Operator
...


(A || B) is true
...
Use to reverses the logical state of its
operand
...


!(A && B) is true
...
Copy and paste the following Java
program in Test
...
out
...
out
...
out
...
Copy and paste the following Java
program in Test
...
out
...
out
...
out
...
out
...
out
...
out
...
out
...
out
...
out
...
out
...
out
...
out
...


Conditional Operator (?:):
Conditional operator is also known as the ternary operator
...
The goal of the operator is to decide which value should be assigned to the variable
...
out
...
out
...
The operator checks whether the object is of a particular
type(class type or interface type)
...
Following is the example:
String name = “James”;
boolean result = name instanceof String;
// This will return true since name is type of String
This operator will still return true if the object being compared is the assignment compatible with the type on the
right
...
out
...
This affects how an expression is
evaluated
...

Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the
bottom
...


TUTORIALS POINT
Simply Easy Learning

Category

Operator

Associativity

Postfix

() []
...
The chapter will describe various types of
loops and how these loops can be used in Java program development and for what purposes they are being used
...

Java has very flexible three looping mechanisms
...
while Loop



for Loop

As of Java 5, the enhanced for loop was introduced
...


The while Loop:
A while loop is a control structure that allows you to repeat a task a certain number of times
...
This will
continue as long as the expression result is true
...
When the expression is tested and the result is
false, the loop body will be skipped and the first statement after the while loop will be executed
...
out
...
out
...
while Loop:
A do
...
while loop is guaranteed to execute at least one time
...
while loop is:
do
{
//Statements
}while(Boolean_expression);
Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute once
before the Boolean is tested
...
This process repeats until the Boolean expression is false
...
out
...
out
...

A for loop is useful when you know how many times a task is to be repeated
...
This step allows you to declare and initialize any loop
control variables
...




Next, the Boolean expression is evaluated
...
If it is false, the body
of the loop does not execute and flow of control jumps to the next statement past the for loop
...
This
statement allows you to update any loop control variables
...




The Boolean expression is now evaluated again
...
After the Boolean expression is false, the for loop
terminates
...
out
...
out
...
This is mainly used for Arrays
...
The variable will be available within the for block and its value would be the same as the
current array element
...
The expression can be an array variable or
method call that returns an array
...
out
...
out
...
out
...
out
...
out
...
The break keyword must be used inside any loop or a switch
statement
...


Syntax:
The syntax of a break is a single statement inside any loop:
break;

Example:
public class Test{
public static void main(String args[]){
int[] numbers ={10,20,30,40,50};
for(int x : numbers){
if(x ==30){
break;
}
System
...
print( x );
System
...
print("\n");
}
}
}
This would produce the following result:
10
20

The continue Keyword:
The continue keyword can be used in any of the loop control structures
...




In a for loop, the continue keyword causes flow of control to immediately jump to the update statement
...


Syntax:
The syntax of a continue is a single statement inside any loop:
continue;

Example:
public class Test{
public static void main(String args[]){
int[] numbers ={10,20,30,40,50};
for(int x : numbers){
if( x ==30){
continue;
}
System
...
print( x );
System
...
print("\n");

TUTORIALS POINT
Simply Easy Learning

}
}
}
This would produce the following result:
10
20
40
50

What is Next?
In the following chapter, we will be learning about decision making statements in Java programming
...
They are:



if statements



switch statements

The if Statement:
An if statement consists of a Boolean expression followed by one or more statements
...
If not,
the first set of code after the end of the if statement(after the closing curly brace) will be executed
...
out
...
else Statement:
An if statement can be followed by an optional else statement, which executes when the Boolean expression is
false
...
else is:
if(Boolean_expression){
//Executes when the Boolean expression is true
}else{
//Executes when the Boolean expression is false
}

Example:
public class Test{
public static void main(String args[]){
int x =30;
if(x <20){
System
...
print("This is if statement");
}else{
System
...
print("This is else statement");
}
}
}
This would produce the following result:
Thisiselse statement

The if
...
else Statement:
An if statement can be followed by an optional else if
...
else if statement
...



An if can have zero or one else's and it must come after any else if's
...




Once an else if succeeds, none of the remaining else if's or else's will be tested
...
else is:
if(Boolean_expression1){
//Executes when the Boolean expression 1 is true
}elseif(Boolean_expression2){
//Executes when the Boolean expression 2 is true
}elseif(Boolean_expression3){
//Executes when the Boolean expression 3 is true
}else{

TUTORIALS POINT
Simply Easy Learning

//Executes when the none of the above condition is true
...
out
...
out
...
out
...
out
...
else Statement:
It is always legal to nest if-else statements which means you can use one if or else if statement inside another if or
else if statement
...
else is as follows:
if(Boolean_expression1){
//Executes when the Boolean expression 1 is true
if(Boolean_expression2){
//Executes when the Boolean expression 2 is true
}
}
You can nest else if
...


Example:
public class Test{
public static void main(String args[]){
int x =30;
int y =10;
if( x ==30){
if( y ==10){
System
...
print("X = 30 and Y = 10");
}
}
}

TUTORIALS POINT
Simply Easy Learning

This would produce the following result:
X =30and Y =10

The switch Statement:
A switch statement allows a variable to be tested for equality against a list of values
...


Syntax:
The syntax of enhanced for loop is:
switch(expression){
case value :
//Statements
break;//optional
case value :
//Statements
break;//optional
//You can have any number of case statements
...




You can have any number of case statements within a switch
...




The value for a case must be the same data type as the variable in the switch and it must be a constant or a
literal
...




When a break statement is reached, the switch terminates, and the flow of control jumps to the next line
following the switch statement
...
If no break appears, the flow of control will fall throughto subsequent
cases until a break is reached
...
The default
case can be used for performing a task when none of the cases is true
...


Example:
public class Test{
public static void main(String args[]){
char grade = args[0]
...
out
...
out
...
out
...
out
...
out
...
out
...
This would produce the following result:
$ java Test a
Invalid grade
Your grade is a a
$ java Test A
Excellent!
Your grade is a A
$ java Test C
Welldone
Your grade is a C
$

What is Next?
Next chapter discuses about the Number class (in the java
...

We will be looking into some of the situations where you would use instantiations of these classes rather than the
primitive data types, as well as classes such as formatting, mathematical functions that you need to know about
when working with Numbers
...


Example:
int i =5000;
float gpa =13
...

In-order to achieve this, Java provides wrapper classes for each primitive data type
...


This wrapping is taken care of by the compiler,the process is called boxing
...
Similarly, the compiler unboxes the
object to a primitive as well
...
lang package
...
out
...
Later, x is unboxed
so that they can be added as integers
...


2

compareTo()
Compares this Number object to the argument
...


4

valueOf()
Returns an Integer object holding the value of the specified primitive
...


6

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


8

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


9

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


10

rint()
Returns the integer that is closest in value to the argument
...


11

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


13

max()
Returns the larger of the two arguments
...


15

log()
Returns the natural logarithm of the argument
...


17

sqrt()
Returns the square root of the argument
...


19

cos()
Returns the cosine of the specified double value
...


21

asin()
Returns the arcsine of the specified double value
...


23

atan()
Returns the arctangent of the specified double value
...


25

toDegrees()
Converts the argument to degrees

26

toRadians()
Converts the argument to radians
...


xxxValue()
Description:
The method converts the value of the Number Object that invokes the method to the primitive data type that is
returned from the method
...


TUTORIALS POINT
Simply Easy Learning

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

compareTo()
Description:
The method compares the Number object that invoked the method to the argument
...

However, two different types cannot be compared, both the argument and the Number object invoking the method
should be of same type
...


Return Value:


If the Integer is equal to the argument then 0 is returned
...




If the Integer is greater than the argument then 1 is returned
...
out
...
compareTo(3));
System
...
println(x
...
out
...
compareTo(8));
}
}
This produces the following result:

1
0
-1

equals()
Description:
The method determines whether the Number Object that invokes the method is equal to the argument
...


Return Value:
 The methods returns True if the argument is not null and is an object of the same type and with the same
numeric value
...


Example:
public class Test{
public static void main(String args[]){
Integer x =5;
Integer y =10;
Integer z =5;
Short a =5;
System
...
println(x
...
out
...
equals(z));
System
...
println(x
...
The
argument can be a primitive data type, String, etc
...
The method can take two arguments, where one is a String and the other is a
radix
...

s -- A String for which Integer representation would be returned
...


Return Value:


valueOf(int i): This returns an Integer object holding the value of the specified primitive
...




valueOf(String s, int radix): This returns an Integer object holding the integer value of the specified
string representation, parsed with the value of radix
...
valueOf(9);
Double c =Double
...
valueOf("80");
Integer b =Integer
...
out
...
out
...
out
...
out
...
0
80
...

If the method takes a primitive data type as an argument, then the String object representing the primitive
data type value is return
...


Syntax:
All the variant of this method are given below:
String toString()
staticString toString(int i)

Parameters:
Here is the detail of parameters:



i -- An int for which string representation would be returned
...

toString(int i): This returns a String object representing the specified integer
...
out
...
toString());
System
...
println(Integer
...
parseXxx() is a static method and can
have one argument or two
...

radix -- This would be used to convert String s into integer
...

parseInt(int i): This returns an integer, given a string representation of decimal, binary, octal, or
hexadecimal (radix equals 10, 2, 8, or 16 respectively) numbers as input
...
parseInt("9");
double c =Double
...
parseInt("444",16);
System
...
println(x);
System
...
println(c);
System
...
println(b);
}
}
This produces the following result:
9

TUTORIALS POINT
Simply Easy Learning

5
...
The argument can be int, float, long, double, short,
byte
...


Example:
public class Test{
public static void main(String args[]){
Integer a =-8;
double d =-100;
float f =-90;
System
...
println(Math
...
out
...
abs(d));
System
...
println(Math
...
0
90
...


Syntax:
This method has following variants:
double ceil(double d)
double ceil(float f)

Parameters:
Here is the detail of parameters:



A double or float primitive data type

Return Value:


This method Returns the smallest integer that is greater than or equal to the argument
...


Example:
public class Test{
public static void main(String args[]){
double d =-100
...
out
...
ceil(d));
System
...
println(Math
...
out
...
floor(d));
System
...
println(Math
...
0
-90
...
0
-90
...


Syntax:
This method has following variants:
double floor(double d)
double floor(float f)

Parameters:
Here is the detail of parameters:



A double or float primitive data type

Return Value:


This method Returns the largest integer that is less than or equal to the argument
...


Example:
public class Test{
public static void main(String args[]){
double d =-100
...
out
...
floor(d));
System
...
println(Math
...
out
...
ceil(d));
System
...
println(Math
...
0
-90
...
0
-90
...


Syntax:
double rint(double d)

Parameters:
Here is the detail of parameters:



d -- A double primitive data type

Return Value:


This method Returns the integer that is closest in value to the argument
...


Example:
public class Test{
public
double
double
double

static void main(String args[]){
d =100
...
500;
f =100
...
out
...
rint(d));
System
...
println(Math
...
out
...
rint(f));
}
}
This produces the following result:
101
...
0
100
...


TUTORIALS POINT
Simply Easy Learning

Syntax:
This method has following variants:
long round(double d)
int round(float f)

Parameters:
Here is the detail of parameters:




d -- A double or float primitive data type
f -- A float primitive data type

Return Value:


This method Returns the closest long or int, as indicated by the method's return type, to the argument
...
675;
double e =100
...
out
...
round(d));
System
...
println(Math
...
out
...
round(f));
System
...
println(Math
...
The argument can be int, float, long, double
...


Example:
public class Test{
public static void main(String args[]){
System
...
println(Math
...
123,12
...
out
...
min(23
...
0));
}
}
This produces the following result:
12
...
0

max()
Description:
The method gives the maximum of the two arguments
...


Syntax:
This method has following variants:
double max(double arg1,double arg2)
float max(float arg1,float arg2)
int max(int arg1,int arg2)
long max(long arg1,long arg2)

Parameters:
Here is the detail of parameters:

TUTORIALS POINT
Simply Easy Learning



A primitive data types

Return Value:


This method returns the maximum of the two arguments
...
out
...
max(12
...
456));
System
...
println(Math
...
12,23
...
456
23
...


Syntax:
double exp(double d)

Parameters:
Here is the detail of parameters:



d -- A primitive data types

Return Value:


This method Returns the base of the natural logarithms, e, to the power of the argument
...
635;
double y =2
...
out
...
4f%n",Math
...
out
...
3f) is %
...
exp(x));
}
}
This produces the following result:
The value of e is 2
...
635) is 112983
...


Syntax:
double log(double d)

Parameters:
Here is the detail of parameters:



d -- A primitive data types

Return Value:


This method Returns the natural logarithm of the argument
...
635;
double y =2
...
out
...
4f%n",Math
...
out
...
3f) is %
...
log(x));
}
}
This produces the following result:
The value of e is 2
...
635) is 2
...


Syntax:
double pow(doublebase,double exponent)

Parameters:
Here is the detail of parameters:




base -- A primitive data type
exponenet -- A primitive data type

Return Value:


This method Returns the value of the first argument raised to the power of the second argument
...
635;
double y =2
...
out
...
4f%n",Math
...
out
...
3f, %
...
3f%n",x, y,Math
...
7183
pow(11
...
760) is 874
...


Syntax:
double sqrt(double d)

Parameters:
Here is the detail of parameters:

TUTORIALS POINT
Simply Easy Learning



d -- A primitive data type

Return Value:


This method Returns the square root of the argument
...
635;
double y =2
...
out
...
4f%n",Math
...
out
...
3f) is %
...
sqrt(x));
}
}
This produces the following result:
The value of e is 2
...
635) is 3
...


Syntax:
double sin(double d)

Parameters:
Here is the detail of parameters:



d -- A double data types

Return Value:


This method Returns the sine of the specified double value
...
0;

TUTORIALS POINT
Simply Easy Learning

double radians =Math
...
out
...
4f%n",Math
...
out
...
1f degrees is
%
...
sin(radians));
}
}
This produces the following result:
The value of pi is 3
...
0 degrees is 0
...


Syntax:
double cos(double d)

Parameters:
Here is the detail of parameters:



d -- A double data types

Return Value:


This method Returns the cosine of the specified double value
...
0;
double radians =Math
...
out
...
4f%n",Math
...
out
...
1f degrees is %
...
cos(radians));
}
}
This produces the following result:
The value of pi is 3
...
0 degrees is 0
...


Syntax:
double tan(double d)

Parameters:
Here is the detail of parameters:



d -- A double data type

Return Value:


This method returns the tangent of the specified double value
...
0;
double radians =Math
...
out
...
4f%n",Math
...
out
...
1f degrees is %
...
tan(radians));
}
}
This produces the following result:
The value of pi is 3
...
0 degrees is 1
...


TUTORIALS POINT
Simply Easy Learning

Syntax:
double asin(double d)

Parameters:
Here is the detail of parameters:



d -- A double data types

Return Value:


This method Returns the arcsine of the specified double value
...
0;
double radians =Math
...
out
...
4f%n",Math
...
out
...
4f is %
...
sin(radians),
Math
...
asin(Math
...
1416
The arcsine of 0
...
0000 degrees

acos()
Description:
The method returns the arccosine of the specified double value
...


Example:
public class Test{
public static void main(String args[]){
double degrees =45
...
toRadians(degrees);
System
...
format("The value of pi is %
...
PI);
System
...
format("The arccosine of %
...
4f degrees %n",
Math
...
toDegrees(Math
...
sin(radians))));
}
}
This produces the following result:
The value of pi is 3
...
7071 is 45
...


Syntax:
double atan(double d)

Parameters:
Here is the detail of parameters:



d -- A double data types

Return Value :


This method Returns the arctangent of the specified double value
...
0;
double radians =Math
...
out
...
4f%n",Math
...
out
...
4f is %
...
cos(radians),
Math
...
atan(Math
...
1416
The arctangent of 1
...
0000 degrees

atan2()
Description:
The method Converts rectangular coordinates (x, y) to polar coordinate (r, theta) and returns theta
...
0;
double y =30
...
out
...
atan2(x, y));
}

TUTORIALS POINT
Simply Easy Learning

}
This produces the following result:
0
...


Syntax:
double toDegrees(double d)

Parameters:
Here is the detail of parameters:



d -- A double data type
...


Example:
public class Test{
public static void main(String args[]){
double x =45
...
0;
System
...
println(Math
...
out
...
toDegrees(y));
}
}
This produces the following result:
2578
...
8733853924698

toRadians()
Description:
The method converts the argument value to radians
...


Return Value:


This method returns a double value
...
0;
double y =30
...
out
...
toRadians(x));
System
...
println(Math
...
7853981633974483
0
...
0 and 1
...
The range is: 0
...
random <
1
...
Different ranges can be achieved by using arithmetic
...
out
...
random());
System
...
println(Math
...
16763945061451657
0
...


What is Next?
In the next section, we will be going through the Character class in Java
...


TUTORIALS POINT
Simply Easy Learning

CHAPTER

12
Java Characters

N

ormally, when we work with characters, we use primitive data types char
...

Inorder to achieve this, Java provides wrapper class Character for primitive data type char
...
e
...
You can
create a Character object with the Character constructor:
Character ch =newCharacter('a');
The Java compiler will also create a Character object for you under some circumstances
...
This feature is called autoboxing or unboxing, if the conversion goes the other way
...


TUTORIALS POINT
Simply Easy Learning

The newline character (\n) has been used frequently in this tutorial in System
...
println() statements to advance to
the next line after the string is printed
...


\b

Inserts a backspace in the text at this point
...


\r

Inserts a carriage return in the text at this point
...


\'

Inserts a single quote character in the text at this point
...


\\

Inserts a backslash character in the text at this point
...


Example:
If you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes:
public class Test{
public static void main(String args[]){
System
...
println("She said \"Hello!\" to me
...


Character Methods:
Here is the list of the important instance methods that all the subclasses of the Character class implement:
SN Methods with Description
1

isLetter()
Determines whether the specified char value is a letter
...


3

isWhitespace()
Determines whether the specified char value is white space
...


5

isLowerCase()

TUTORIALS POINT
Simply Easy Learning

Determines whether the specified char value is lowercase
...


7

toLowerCase()
Returns the lowercase form of the specified char value
...


For a complete list of methods, please refer to the java
...
Character API specification
...


Syntax:
boolean isLetter(char ch)

Parameters:
Here is the detail of parameters:



ch -- Primitive character type

Return Value:


This method Returns true if passed character is really a character
...
out
...
isLetter('c'));
System
...
println(Character
...


Syntax:
boolean isDigit(char ch)

Parameters:
Here is the detail of parameters:



ch -- Primitive character type

Return Value:


This method Returns true if passed character is really a digit
...
out
...
isDigit('c'));
System
...
println(Character
...


Syntax:
boolean isWhitespace(char ch)

TUTORIALS POINT
Simply Easy Learning

Parameters:
Here is the detail of parameters:



ch -- Primitive character type

Return Value:


This method Returns true if passed character is really a white space
...
out
...
isWhitespace('c'));
System
...
println(Character
...
out
...
isWhitespace('\n'));
System
...
println(Character
...


Syntax:
boolean isUpperCase(char ch)

Parameters:
Here is the detail of parameters:



ch -- Primitive character type

Return Value:


This method Returns true if passed character is really an uppercase
...
out
...
isUpperCase('c'));
System
...
println(Character
...
out
...
isUpperCase('\n'));
System
...
println(Character
...


Syntax:
boolean isLowerCase(char ch)

Parameters:
Here is the detail of parameters:



ch -- Primitive character type

Return Value:


This method Returns true if passed character is really an lowercase
...
out
...
isLowerCase('c'));
System
...
println(Character
...
out
...
isLowerCase('\n'));
System
...
println(Character
...


Syntax:
char toUpperCase(char ch)

Parameters:
Here is the detail of parameters:



ch -- Primitive character type

Return Value :


This method Returns the uppercase form of the specified char value
...
out
...
toUpperCase('c'));
System
...
println(Character
...


Syntax:
TUTORIALS POINT
Simply Easy Learning

char toLowerCase(char ch)

Parameters:
Here is the detail of parameters:



ch -- Primitive character type

Return Value:


This method Returns the lowercase form of the specified char value
...
out
...
toLowerCase('c'));
System
...
println(Character
...


Syntax:
String toString(char ch)

Parameters:
Here is the detail of parameters:



ch -- Primitive character type

Return Value:


This method Returns String object

Example:
TUTORIALS POINT
Simply Easy Learning

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

What is Next?
In the next section, we will be going through the String class in Java
...


TUTORIALS POINT
Simply Easy Learning

CHAPTER

13
Java Strings

S

trings which are widely used in Java programming are a sequence of characters
...

The Java platform provides the String class to create and manipulate strings
...

As with any other object, you can create String objects by using the new keyword and a constructor
...
'};
String helloString =new String(helloArray);
System
...
println(helloString);
}
}
This would produce the following result:
hello
...
If there is a
necessity to make alot of modifications to Strings of characters, then you should use String Buffer & String
Builder Classes
...
One accessor method that
you can use with strings is the length() method, which returns the number of characters contained in the string
object
...
length();
System
...
println("String Length is : "+ len );
}
}
This would produce the following result:
StringLengthis:17

Concatenating Strings:
The String class includes a method for concatenating two strings:
string1
...
You can also use the concat() method
with string literals, as in:
"My name is "
...
out
...
The String class has an equivalent
class method, format(), that returns a String object rather than a PrintStream object
...
For example, instead of:
System
...
printf("The value of the float variable is "+
"%f, while the value of the integer "+

TUTORIALS POINT
Simply Easy Learning

"variable is %d, and the string "+
"is %s", floatVar, intVar, stringVar);
you can write:
String fs;
fs =String
...
out
...


2

int compareTo(Object o)
Compares this String to another Object
...


4

int compareToIgnoreCase(String str)
Compares two strings lexicographically, ignoring case differences
...


6

boolean contentEquals(StringBuffer sb)
Returns true if and only if this String represents the same sequence of characters as the specified
StringBuffer
...


8

static String copyValueOf(char[] data, int offset, int count)
Returns a String that represents the character sequence in the array specified
...


10

boolean equals(Object anObject)
Compares this string to the specified object
...


12

byte getBytes()
Encodes this String into a sequence of bytes using the platform's default charset, storing the result
into a new byte array
...


14

void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Copies characters from this string into the destination character array
...


16

int indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character
...


18

int indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring
...


20

String intern()
Returns a canonical representation for the string object
...


22

int lastIndexOf(int ch, int fromIndex)
Returns the index within this string of the last occurrence of the specified character, searching
backward starting at the specified index
...


24

int lastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified substring, searching
backward starting at the specified index
...


26

boolean matches(String regex)
Tells whether or not this string matches the given regular expression
...


28

boolean regionMatches(int toffset, String other, int ooffset, int len)
Tests if two string regions are equal
...


30

String replaceAll(String regex, String replacement
Replaces each substring of this string that matches the given regular expression with the given
replacement
...


32

String[] split(String regex)
Splits this string around matches of the given regular expression
...


TUTORIALS POINT
Simply Easy Learning

34

boolean startsWith(String prefix)
Tests if this string starts with the specified prefix
...


36

CharSequence subSequence(int beginIndex, int endIndex)
Returns a new character sequence that is a subsequence of this sequence
...


38

String substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string
...


40

String toLowerCase()
Converts all of the characters in this String to lower case using the rules of the default locale
...


42

String toString()
This object (which is already a string!) is itself returned
...


44

String toUpperCase(Locale locale)
Converts all of the characters in this String to upper case using the rules of the given Locale
...


46

static String valueOf(primitive data type x)
Returns the string representation of the passed data type argument
...
The string indexes start from zero
...


TUTORIALS POINT
Simply Easy Learning

Return Value:


This method Returns a char at the specified index
...
charAt(8);
System
...
println(result);
}
}
This produces the following result:
a

int compareTo(Object o)
Description:
There are two variants of this method
...


Syntax:
Here is the syntax of this method:
int compareTo(Object o)
or
int compareTo(String anotherString)

Parameters:
Here is the detail of parameters:




o -- the Object to be compared
...


Return Value :


The value 0 if the argument is a string lexicographically equal to this string; a value less than 0 if the
argument is a string lexicographically greater than this string; and a value greater than 0 if the argument
is a string lexicographically less than this string
...
compareTo( str2 );
System
...
println(result);
result = str2
...
out
...
compareTo( str1 );
System
...
println(result);
}
}
This produces the following result:
0
10
-10

int compareTo(String anotherString)
Description:
There are two variants of this method
...


Syntax:
Here is the syntax of this method:
int compareTo(Object o)
or
int compareTo(String anotherString)

Parameters:
Here is the detail of parameters:




o -- the Object to be compared
...


Return Value :
 The value 0 if the argument is a string lexicographically equal to this string; a value less than 0 if the
argument is a string lexicographically greater than this string; and a value greater than 0 if the argument is
a string lexicographically less than this string
...
compareTo( str2 );
System
...
println(result);
result = str2
...
out
...
compareTo( str1 );
System
...
println(result);
}
}
This produces the following result:
0
10
-10

int compareToIgnoreCase(String str)
Description:
This method compares two strings lexicographically, ignoring case differences
...


Return Value:


This method returns a negative integer, zero, or a positive integer as the specified String is greater than,
equal to, or less than this String, ignoring case considerations
...
compareToIgnoreCase( str2 );
System
...
println(result);
result = str2
...
out
...
compareToIgnoreCase( str1 );
System
...
println(result);
}
}
This produces the following result:
0
10
-10

String concat(String str)
Description:
This method appends one String to the end of another
...


Syntax:
Here is the syntax of this method:
public String concat(String s)

Parameters:
Here is the detail of parameters:



s -- the String that is concatenated to the end of this String
...


Example:
public class Test{

TUTORIALS POINT
Simply Easy Learning

public static void main(String args[]){
String s ="Strings are immutable";
s = s
...
out
...


Syntax:
Here is the syntax of this method:
public boolean contentEquals(StringBuffer sb)

Parameters:
Here is the detail of parameters:



sb -- the StringBuffer to compare
...


Example:
public class Test{
public static void main(String args[]){
String str1 ="Not immutable";
String str2 ="Strings are immutable";
StringBuffer str3 =new StringBuffer("Not immutable");
boolean result = str1
...
out
...
contentEquals( str3 );
System
...
println(result);
}
}

TUTORIALS POINT
Simply Easy Learning

This produces the following result:
true
false

static String copyValueOf(char[] data)
Description:
This method has two different forms:




public static String copyValueOf(char[] data): Returns a String that represents the character
sequence in the array specified
...


Syntax:
Here is the syntax of this method:
public staticString copyValueOf(char[] data)
or
public staticString copyValueOf(char[] data,int offset,int count)

Parameters:
Here is the detail of parameters:





data -- the character array
...

count -- length of the subarray
...


Example:
public class Test{
public static void main(String args[]){
char[]Str1={'h','e','l','l','o',' ','w','o','r','l','d'};
String Str2="";
Str2=Str2
...
out
...
copyValueOf(Str1,2,6);
System
...
println("Returned String: "+Str2);
}
}

TUTORIALS POINT
Simply Easy Learning

This produces the following result:
Returned String: hello world
Returned String: llo wo

boolean endsWith(String suffix)
Description:
This method tests if this string ends with the specified suffix
...


Return Value:


This method returns true if the character sequence represented by the argument is a suffix of the
character sequence represented by this object; false otherwise
...


Example:
public class Test{
public static void main(String args[]){
String Str=new String("This is really not immutable!!");
boolean retVal;
retVal =Str
...
out
...
endsWith("immu");
System
...
println("Returned Value = "+ retVal );
}
}
This produces the following result:
Returned Value = true
Returned Value = false

TUTORIALS POINT
Simply Easy Learning

boolean equals(Object anObject)
Description:
This method compares this string to the specified object
...


Syntax:
Here is the syntax of this method:
public boolean equals(Object anObject)

Parameters:
Here is the detail of parameters:



anObject -- the object to compare this String against
...


Example:
public class Test{
public static void main(String args[]){
String Str1=new String("This is really not immutable!!");
String Str2=Str1;
String Str3=new String("This is really not immutable!!");
boolean retVal;
retVal =Str1
...
out
...
equals(Str3);
System
...
println("Returned Value = "+ retVal );
}
}
This produces the following result:
Returned Value = true
Returned Value = true

boolean equalsIgnoreCase(String anotherString)
Description:
TUTORIALS POINT
Simply Easy Learning

This method compares this String to another String, ignoring case considerations
...


Syntax:
Here is the syntax of this method:
public boolean equalsIgnoreCase(String anotherString)

Parameters:
Here is the detail of parameters:



anotherString -- the String to compare this String against

Return Value:


This method returns true if the argument is not null and the Strings are equal, ignoring case; false
otherwise
...
equals(Str2);
System
...
println("Returned Value = "+ retVal );
retVal =Str1
...
out
...
equalsIgnoreCase(Str4);
System
...
println("Returned Value = "+ retVal );
}
}
This produces the following result:
Returned Value = true
Returned Value = true
Returned Value = true

byte getBytes()
Description:
TUTORIALS POINT
Simply Easy Learning

This method has following two forms:




getBytes(String charsetName): Encodes this String into a sequence of bytes using the named charset,
storing the result into a new byte array
...


Syntax:
Here is the syntax of this method:
public byte[] getBytes(String charsetName)
throwsUnsupportedEncodingException
or
public byte[] getBytes()

Parameters:
Here is the detail of parameters:



charsetName -- the name of a supported charset
...
io
...
com");
try{
byte[]Str2=Str1
...
out
...
getBytes("UTF-8");
System
...
println("Returned

Value "+Str2);

Str2=Str1
...
out
...
out
...

getBytes(): Encodes this String into a sequence of bytes using the platform's default charset, storing the
result into a new byte array
...


Return Value:


This method returns the resultant byte array

Example:
import java
...
*;
public class Test{
public static void main(String args[]){
String Str1=new String("Welcome to Tutorialspoint
...
getBytes();
System
...
println("Returned

Value "+Str2);

Str2=Str1
...
out
...
getBytes("ISO-8859-1");

TUTORIALS POINT
Simply Easy Learning

System
...
println("Returned Value "+Str2);
}catch(UnsupportedEncodingException e){
System
...
println("Unsupported character set");
}
}
}
This produces the following result:
Returned
Returned
Returned

Value [B@192d342
Value [B@15ff48b
Value [B@1b90b39

void getChars(int srcBegin, int srcEnd, char[] dst, int
dstBegin)
Description:
This method copies characters from this string into the destination character array
...

srcEnd -- index after the last character in the string to copy
...

dstBegin -- the start offset in the destination array
...


Example:
import java
...
*;
public class Test{
public static void main(String args[]){
String Str1=new String("Welcome to Tutorialspoint
...
getChars(2,9,Str2,0);
System
...
print("Copied Value = ");
System
...
println(Str2);
}catch(Exception ex){
System
...
println("Raised exception
...
The hash code for a String object is computed as:
s[0]*31^(n-1)+ s[1]*31^(n-2)+
...
(The hash value of the empty string is zero
...


Example:
import java
...
*;
public class Test{
public static void main(String args[]){
String Str=new String("Welcome to Tutorialspoint
...
out
...
hashCode());

TUTORIALS POINT
Simply Easy Learning

}
}
This produces the following result:
Hashcode for Str :1186874997

int indexOf(int ch)
Description:
This method has following different variants:






public int indexOf(int ch): Returns the index within this string of the first occurrence of the specified
character or -1 if the character does not occur
...

int indexOf(String str): Returns the index within this string of the first occurrence of the specified
substring
...

int indexOf(String str, int fromIndex): Returns the index within this string of the first occurrence of the
specified substring, starting at the specified index
...


Syntax:
Here is the syntax of this method:
public int indexOf(int ch )
or
public int indexOf(int ch,int fromIndex)
or
int indexOf(String str)
or
int indexOf(String str,int fromIndex)

Parameters:
Here is the detail of parameters:





ch -- a character
...

str -- a string
...


TUTORIALS POINT
Simply Easy Learning

Example:
import java
...
*;
public class Test{
public static void main(String args[]){
String Str=new String("Welcome to Tutorialspoint
...
out
...
out
...
indexOf('o'));
System
...
print("Found Index :");
System
...
println(Str
...
out
...
out
...
indexOf(SubStr1));
System
...
print("Found Index :");
System
...
println(Str
...
out
...
out
...
indexOf(SubStr2));
}
}
This produces the following result:
Found
Found
Found
Found
Found

Index
Index
Index
Index
Index

:4
:9
:11
:-1
:-1

int indexOf(int ch, int fromIndex)
Description:
This method has following different variants:






public int indexOf(int ch): Returns the index within this string of the first occurrence of the specified
character or -1 if the character does not occur
...

int indexOf(String str): Returns the index within this string of the first occurrence of the specified
substring
...

int indexOf(String str, int fromIndex): Returns the index within this string of the first occurrence of the
specified substring, starting at the specified index
...


Syntax:
Here is the syntax of this method:
public int indexOf(int ch )
or

TUTORIALS POINT
Simply Easy Learning

public int indexOf(int ch,int fromIndex)
or
int indexOf(String str)
or
int indexOf(String str,int fromIndex)

Parameters:
Here is the detail of parameters:





ch -- a character
...

str -- a string
...


Example:
import java
...
*;
public class Test{
public
String
String
String

static void main(String args[]){
Str=new String("Welcome to Tutorialspoint
...
out
...
out
...
indexOf('o'));
System
...
print("Found Index :");
System
...
println(Str
...
out
...
out
...
indexOf(SubStr1));
System
...
print("Found Index :");
System
...
println(Str
...
out
...
out
...
indexOf(SubStr2));
}
}
This produces the following result:
Found
Found
Found
Found
Found

Index
Index
Index
Index
Index

:4
:9
:11
:-1
:-1

TUTORIALS POINT
Simply Easy Learning

int indexOf(String str)
Description:
This method has following different variants:






public int indexOf(int ch): Returns the index within this string of the first occurrence of the specified
character or -1 if the character does not occur
...

int indexOf(String str): Returns the index within this string of the first occurrence of the specified
substring
...

int indexOf(String str, int fromIndex): Returns the index within this string of the first occurrence of the
specified substring, starting at the specified index
...


Syntax:
Here is the syntax of this method:
public int indexOf(int ch )
or
public int indexOf(int ch,int fromIndex)
or
int indexOf(String str)
or
int indexOf(String str,int fromIndex)

Parameters:
Here is the detail of parameters:





ch -- a character
...

str -- a string
...


Example:
import java
...
*;
public class Test{
public static void main(String args[]){

TUTORIALS POINT
Simply Easy Learning

String Str=new String("Welcome to Tutorialspoint
...
out
...
out
...
indexOf('o'));
System
...
print("Found Index :");
System
...
println(Str
...
out
...
out
...
indexOf(SubStr1));
System
...
print("Found Index :");
System
...
println(Str
...
out
...
out
...
indexOf(SubStr2));
}
}
This produces the following result:
Found
Found
Found
Found
Found

Index
Index
Index
Index
Index

:4
:9
:11
:-1
:-1

int indexOf(String str, int fromIndex)
Description:
This method has following different variants:






public int indexOf(int ch): Returns the index within this string of the first occurrence of the specified
character or -1 if the character does not occur
...

int indexOf(String str): Returns the index within this string of the first occurrence of the specified
substring
...

int indexOf(String str, int fromIndex): Returns the index within this string of the first occurrence of the
specified substring, starting at the specified index
...


Syntax:
Here is the syntax of this method:
public int indexOf(int ch )
or
public int indexOf(int ch,int fromIndex)
or
int indexOf(String str)
or

TUTORIALS POINT
Simply Easy Learning

int indexOf(String str,int fromIndex)

Parameters:
Here is the detail of parameters:





ch -- a character
...

str -- a string
...


Example:
import java
...
*;
public class Test{
public
String
String
String

static void main(String args[]){
Str=new String("Welcome to Tutorialspoint
...
out
...
out
...
indexOf('o'));
System
...
print("Found Index :");
System
...
println(Str
...
out
...
out
...
indexOf(SubStr1));
System
...
print("Found Index :");
System
...
println(Str
...
out
...
out
...
indexOf(SubStr2));
}
}
This produces the following result:
Found
Found
Found
Found
Found

Index
Index
Index
Index
Index

:4
:9
:11
:-1
:-1

String intern()
Description:
This method returns a canonical representation for the string object
...
intern() == t
...
equals(t) is true
...


Example:
import java
...
*;
public
public
String
String

class Test{
static void main(String args[]){
Str1=new String("Welcome to Tutorialspoint
...
COM");

System
...
print("Canonical representation:");
System
...
println(Str1
...
out
...
out
...
intern());
}
}
This produces the following result:
Canonical representation: Welcome to Tutorialspoint
...
COM

int lastIndexOf(int ch)
Description:
This method has the following variants:





int lastIndexOf(int ch): Returns the index within this string of the last occurrence of the specified
character or -1 if the character does not occur
...

public int lastIndexOf(String str): If the string argument occurs one or more times as a substring within
this object, then it returns the index of the first character of the last such substring is returned
...


TUTORIALS POINT
Simply Easy Learning



public int lastIndexOf(String str, int fromIndex): Returns the index within this string of the last
occurrence of the specified substring, searching backward starting at the specified index
...

fromIndex -- the index to start the search from
...


Return Value:


This method returns the index
...
io
...
com");
SubStr1=new String("Tutorials");
SubStr2=new String("Sutorials");

System
...
print("Found Last Index :");
System
...
println(Str
...
out
...
out
...
lastIndexOf('o',5));
System
...
print("Found Last Index :");
System
...
println(Str
...
out
...
out
...
lastIndexOf(SubStr1,15));
System
...
print("Found Last Index :");
System
...
println(Str
...

public int lastIndexOf(int ch, int fromIndex): Returns the index of the last occurrence of the character
in the character sequence represented by this object that is less than or equal to fromIndex, or -1 if the
character does not occur before that point
...
If it does
not occur as a substring, -1 is returned
...


Syntax:
Here is the syntax of this method:
int lastIndexOf(int ch)
or
public int lastIndexOf(int ch,int fromIndex)
or
public int lastIndexOf(String str)
or
public int lastIndexOf(String str,int fromIndex)

Parameters:
Here is the detail of parameters:





ch -- a character
...

str -- A string
...


Example:
import java
...
*;
public class Test{
public
String
String
String

static void main(String args[]){
Str=new String("Welcome to Tutorialspoint
...
out
...
out
...
lastIndexOf('o'));
System
...
print("Found Last Index :");
System
...
println(Str
...
out
...
out
...
lastIndexOf(SubStr1));
System
...
print("Found Last Index :");
System
...
println(Str
...
out
...
out
...
lastIndexOf(SubStr2));
}
}
This produces the following result:
Found
Found
Found
Found
Found

Last
Last
Last
Last
Last

Index
Index
Index
Index
Index

:27
:4
:11
:11
:-1

int lastIndexOf(String str)
Description:
This method has the following variants:






int lastIndexOf(int ch): Returns the index within this string of the last occurrence of the specified
character or -1 if the character does not occur
...

public int lastIndexOf(String str): If the string argument occurs one or more times as a substring
within this object, then it returns the index of the first character of the last such substring is returned
...

public int lastIndexOf(String str, int fromIndex): Returns the index within this string of the last
occurrence of the specified substring, searching backward starting at the specified index
...

fromIndex -- the index to start the search from
...


Return Value:


This method returns the index
...
io
...
com");
SubStr1=new String("Tutorials");
SubStr2=new String("Sutorials");

System
...
print("Found Last Index :");
System
...
println(Str
...
out
...
out
...
lastIndexOf('o',5));
System
...
print("Found Last Index :");
System
...
println(Str
...
out
...
out
...
lastIndexOf(SubStr1,15));
System
...
print("Found Last Index :");
System
...
println(Str
...

public int lastIndexOf(int ch, int fromIndex): Returns the index of the last occurrence of the character
in the character sequence represented by this object that is less than or equal to fromIndex, or -1 if the
character does not occur before that point
...
If it does
not occur as a substring, -1 is returned
...


Syntax:
Here is the syntax of this method:
int lastIndexOf(int ch)
or
public int lastIndexOf(int ch,int fromIndex)
or
public int lastIndexOf(String str)
or
public int lastIndexOf(String str,int fromIndex)

Parameters:
Here is the detail of parameters:





ch -- a character
...

str -- A string
...


Example:
import java
...
*;
public class Test{
public
String
String
String

static void main(String args[]){
Str=new String("Welcome to Tutorialspoint
...
out
...
out
...
lastIndexOf('o'));
System
...
print("Found Last Index :");
System
...
println(Str
...
out
...
out
...
lastIndexOf(SubStr1));
System
...
print("Found Last Index :");
System
...
println(Str
...
out
...
out
...
lastIndexOf(SubStr2));
}
}
This produces the following result:
Found
Found
Found
Found
Found

Last
Last
Last
Last
Last

Index
Index
Index
Index
Index

:27
:4
:11
:11
:-1

int length()
Description:
This method returns the length of this string
...


Syntax:
Here is the syntax of this method:
public int length()

Parameters:
Here is the detail of parameters:



NA

TUTORIALS POINT
Simply Easy Learning

Return Value:


This method returns the the length of the sequence of characters represented by this object
...
io
...
com");
Str2=new String("Tutorials");

System
...
print("String Length :");
System
...
println(Str1
...
out
...
out
...
length());
}
}
This produces the following result:
String Length :29
String Length :9

boolean matches(String regex)
Description:
This method tells whether or not this string matches the given regular expression
...
matches(regex) yields exactly the same result as the expression
Pattern
...


Syntax:
Here is the syntax of this method:
public boolean matches(String regex)

Parameters:
Here is the detail of parameters:



regex -- the regular expression to which this string is to be matched
...


TUTORIALS POINT
Simply Easy Learning

Example:
import java
...
*;
public class Test{
public static void main(String args[]){
String Str=new String("Welcome to Tutorialspoint
...
out
...
out
...
matches("(
...
*)"));
System
...
print("Return Value :");
System
...
println(Str
...
out
...
out
...
matches("Welcome(
...


Syntax:
Here is the syntax of this method:
public boolean regionMatches(int toffset,
String other,
int ooffset,
int len)
or
public boolean regionMatches(boolean ignoreCase,
int toffset,
String other,
int ooffset,
int len)

Parameters:
Here is the detail of parameters:

TUTORIALS POINT
Simply Easy Learning







toffset -- the starting offset of the subregion in this string
...

ooffset -- the starting offset of the subregion in the string argument
...

ignoreCase -- if true, ignore case when comparing characters
...
Whether the matching is exact or case insensitive depends on the
ignoreCase argument
...
io
...
com");
Str2=new String("Tutorials");
Str3=new String("TUTORIALS");

System
...
print("Return Value :");
System
...
println(Str1
...
out
...
out
...
regionMatches(11,Str3,0,9));
System
...
print("Return Value :");
System
...
println(Str1
...


Syntax:
Here is the syntax of this method:
public boolean regionMatches(int toffset,
String other,

TUTORIALS POINT
Simply Easy Learning

int ooffset,
int len)
or
public boolean regionMatches(boolean ignoreCase,
int toffset,
String other,
int ooffset,
int len)

Parameters:
Here is the detail of parameters:







toffset -- the starting offset of the subregion in this string
...

ooffset -- the starting offset of the subregion in the string argument
...

ignoreCase -- if true, ignore case when comparing characters
...
Whether the matching is exact or case insensitive depends on the ignoreCase
argument
...
io
...
com");
Str2=new String("Tutorials");
Str3=new String("TUTORIALS");

System
...
print("Return Value :");
System
...
println(Str1
...
out
...
out
...
regionMatches(11,Str3,0,9));
System
...
print("Return Value :");
System
...
println(Str1
...


Syntax:
Here is the syntax of this method:
public String replace(char oldChar,char newChar)

Parameters:
Here is the detail of parameters:




oldChar -- the old character
...


Return Value:


It returns a string derived from this string by replacing every occurrence of oldChar with newChar
...
io
...
com");
System
...
print("Return Value :");
System
...
println(Str
...
out
...
out
...
replace('l','D'));
}
}
This produces the following result:
Return Value :WelcTme tT TutTrialspTint
...
com

String replaceAll(String regex, String replacement)
Description:
TUTORIALS POINT
Simply Easy Learning

This method replaces each substring of this string that matches the given regular expression with the given
replacement
...

replacement -- the string which would replace found expression
...


Example:
import java
...
*;
public class Test{
public static void main(String args[]){
String Str=new String("Welcome to Tutorialspoint
...
out
...
out
...
replaceAll("(
...
*)",
"AMROOD"));
}
}
This produces the following result:
Return Value :AMROOD

String replaceFirst(String regex, String replacement)
Description:
This method replaces the first substring of this string that matches the given regular expression with the given
replacement
...

replacement -- the string which would replace found expression
...


Example:
import java
...
*;
public class Test{
public static void main(String args[]){
String Str=new String("Welcome to Tutorialspoint
...
out
...
out
...
replaceFirst("(
...
*)",
"AMROOD"));
System
...
print("Return Value :");
System
...
println(Str
...
com

String[] split(String regex)
Description:
This method has two variants and splits this string around matches of the given regular expression
...

limit -- the result threshold which means how many strings to be returned
...


Example:
import java
...
*;
public class Test{
public static void main(String args[]){
String Str=new String("Welcome-to-Tutorialspoint
...
out
...
split("-",2)){
System
...
println(retval);
}
System
...
println("");
System
...
println("Return Value :");
for(String retval:Str
...
out
...
out
...
out
...
split("-",0)){
System
...
println(retval);
}
System
...
println("");
System
...
println("Return Value :");
for(String retval:Str
...
out
...
com
Return Value :
Welcome
to
Tutorialspoint
...
com
Return Value :
Welcome

TUTORIALS POINT
Simply Easy Learning

to
Tutorialspoint
...


Syntax:
Here is the syntax of this method:
public String[] split(String regex,int limit)
or
public String[] split(String regex)

Parameters:
Here is the detail of parameters:




regex -- the delimiting regular expression
...


Return Value:


It returns the array of strings computed by splitting this string around matches of the given regular
expression
...
io
...
com");
System
...
println("Return Value :");
for(String retval:Str
...
out
...
out
...
out
...
split("-",3)){
System
...
println(retval);
}
System
...
println("");
System
...
println("Return Value :");
for(String retval:Str
...
out
...
out
...
out
...
split("-")){
System
...
println(retval);
}
}
}
This produces the following result:
Return Value :
Welcome
to-Tutorialspoint
...
com
Return Value:
Welcome
to
Tutorialspoint
...
com

boolean startsWith(String prefix)
Description:
This method has two variants and tests if a string starts with the specified prefix beginning a specified index or
by default at the beginning
...

toffset -- where to begin looking in the string
...


Example:
import java
...
*;
public class Test{
public static void main(String args[]){
String Str=new String("Welcome to Tutorialspoint
...
out
...
out
...
startsWith("Welcome"));
System
...
print("Return Value :");
System
...
println(Str
...
out
...
out
...
startsWith("Tutorials",11));
}
}
This produces the following result:
Return Value :true
Return Value :false
Return Value :true

boolean startsWith(String prefix, int toffset)
Description:
This method has two variants and tests if a string starts with the specified prefix beginning a specified index or
by default at the beginning
...


TUTORIALS POINT
Simply Easy Learning



toffset -- where to begin looking in the string
...


Example:
import java
...
*;
public class Test{
public static void main(String args[]){
String Str=new String("Welcome to Tutorialspoint
...
out
...
out
...
startsWith("Welcome"));
System
...
print("Return Value :");
System
...
println(Str
...
out
...
out
...
startsWith("Tutorials",11));
}
}
This produces the following result:
Return Value :true
Return Value :false
Return Value :true

CharSequence subSequence(int beginIndex, int endIndex)
Description:
This method returns a new character sequence that is a subsequence of this sequence
...

endIndex -- the end index, exclusive
...


Example:
import java
...
*;
public class Test{
public static void main(String args[]){
String Str=new String("Welcome to Tutorialspoint
...
out
...
out
...
subSequence(0,10));
System
...
print("Return Value :");
System
...
println(Str
...
The substring begins
with the character at the specified index and extends to the end of this string or up to endIndex - 1 if second
argument is given
...

endIndex -- the end index, exclusive
...


TUTORIALS POINT
Simply Easy Learning

Example:
import java
...
*;
public class Test{
public static void main(String args[]){
String Str=new String("Welcome to Tutorialspoint
...
out
...
out
...
substring(10));
System
...
print("Return Value :");
System
...
println(Str
...
com
Return Value : Tuto

String substring(int beginIndex, int endIndex)
Description:
This method has two variants and returns a new string that is a substring of this string
...


Syntax:
Here is the syntax of this method:
public String substring(int beginIndex)
or
public String substring(int beginIndex,int endIndex)

Parameters:
Here is the detail of parameters:




beginIndex -- the begin index, inclusive
...


Return Value:


The specified substring
...
io
...
com");
System
...
print("Return Value :");
System
...
println(Str
...
out
...
out
...
substring(10,15));
}
}
This produces the following result:
Return Value : Tutorialspoint
...


Syntax:
Here is the syntax of this method:
public char[] toCharArray()

Parameters:
Here is the detail of parameters:



NA

Return Value:


It returns a newly allocated character array, whose length is the length of this string and whose contents
are initialized to contain the character sequence represented by this string
...
io
...
com");
System
...
print("Return Value :");

TUTORIALS POINT
Simply Easy Learning

System
...
println(Str
...
com

String toLowerCase()
Description:
This method has two variants
...
This is equivalent to calling toLowerCase(Locale
...

Second variant takes locale as an argument to be used while converting into lower case
...


Example:
import java
...
*;
public class Test{
public static void main(String args[]){
String Str=new String("Welcome to Tutorialspoint
...
out
...
out
...
toLowerCase());
}
}
This produces the following result:

TUTORIALS POINT
Simply Easy Learning

Return Value :welcome to tutorialspoint
...
First variant converts all of the characters in this String to lower case using the
rules of the given Locale
...
getDefault())
...


Syntax:
Here is the syntax of this method:
public String toLowerCase()
or
public String toLowerCase(Locale locale)

Parameters:
Here is the detail of parameters:



NA

Return Value:


It returns the String, converted to lowercase
...
io
...
com");
System
...
print("Return Value :");
System
...
println(Str
...
com

TUTORIALS POINT
Simply Easy Learning

String toString()
Description:
This method returns itself a string

Syntax:
Here is the syntax of this method:
public String toString()

Parameters:
Here is the detail of parameters:



NA

Return Value:
 This method returns the string itself
...
io
...
com");
System
...
print("Return Value :");
System
...
println(Str
...
com

String toUpperCase()
Description:
This method has two variants
...
This is equivalent to calling toUpperCase(Locale
...

Second variant takes locale as an argument to be used while converting into upper case
...


Example:
import java
...
*;
public class Test{
public static void main(String args[]){
String Str=new String("Welcome to Tutorialspoint
...
out
...
out
...
toUpperCase());
}
}
This produces the following result:
Return Value :WELCOME TO TUTORIALSPOINT
...
First variant converts all of the characters in this String to upper case using the
rules of the given Locale
...
getDefault())
...


Syntax:
Here is the syntax of this method:
public String toUpperCase()
or

TUTORIALS POINT
Simply Easy Learning

public String toUpperCase(Locale locale)

Parameters:
Here is the detail of parameters:



NA

Return Value:


It returns the String, converted to uppercase
...
io
...
com");
System
...
print("Return Value :");
System
...
println(Str
...
COM

String trim()
Description:
This method returns a copy of the string, with leading and trailing whitespace omitted
...


Example:
import java
...
*;
public class Test{
public static void main(String args[]){
String Str=new String("
Welcome to Tutorialspoint
...
out
...
out
...
trim());
}
}
This produces the following result:
Return Value :Welcome to Tutorialspoint
...
This method returns the string
representation of the passed argument
...

valueOf(char c): Returns the string representation of the char argument
...

valueOf(char[] data, int offset, int count): Returns the string representation of a specific subarray of the
char array argument
...

valueOf(float f): Returns the string representation of the float argument
...

valueOf(long l): Returns the string representation of the long argument
...


Syntax:
Here is the syntax of this method:
static String valueOf(boolean b)
or
static String valueOf(char c)
or
static String valueOf(char[] data)
or

TUTORIALS POINT
Simply Easy Learning

static String valueOf(char[] data,int offset,int count)
or
static String valueOf(double d)
or
static String valueOf(float f)
or
static String valueOf(int i)
or
static String valueOf(long l)
or
static String valueOf(Object obj)

Parameters:
Here is the detail of parameters:



See the description
...


Example:
import java
...
*;
public class Test{
public static void main(String args[]){
double d =102939939
...
out
...
out
...
out
...
out
...
02939939939E8
Return Value : true
Return Value : 1232874

TUTORIALS POINT
Simply Easy Learning

:
:
:
:

"+String
...
valueOf(b));
"+String
...
valueOf(arr));

Return Value : abcdefg

TUTORIALS POINT
Simply Easy Learning

CHAPTER

14
Java Arrays

J

ava provides a data structure, the array, which stores a fixed-size sequential collection of elements of the

same type
...

Instead of declaring individual variables, such as number0, number1,
...
, numbers[99] to represent individual variables
...


Declaring Array Variables:
To use an array in a program, you must declare a variable to reference the array, and you must specify the type of
array the variable can reference
...

or
dataType arrayRefVar[];//

works but not preferred way
...
The style dataType arrayRefVar[] comes from the C/C++
language and was adopted in Java to accommodate C/C++ programmers
...

or
double myList[];//

works but not preferred way
...


Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be
combined in one statement, as shown below:
dataType[] arrayRefVar =new dataType[arraySize];
Alternatively you can create arrays as follows:
dataType[] arrayRefVar ={value0, value1,
...
Array indices are 0-based; that is, they start from 0
to arrayRefVar
...


Example:
Following statement declares an array variable, myList, creates an array of 10 elements of double type and assigns
its reference to myList:
double[] myList =new double[10];
Following picture represents array myList
...


Processing Arrays:
When processing array elements, we often use either for loop or foreach loop because all of the elements in an
array are of the same type and the size of the array is known
...
9,2
...
4,3
...
length; i++){
System
...
println(myList[i]+" ");

TUTORIALS POINT
Simply Easy Learning

}
// Summing all elements
double total =0;
for(int i =0; i < myList
...
out
...
length; i++){
if(myList[i]> max) max = myList[i];
}
System
...
println("Max is "+ max);
}
}
This would produce the following result:
1
...
9
3
...
5
Totalis11
...
5

The foreach Loops:
JDK 1
...


Example:
The following code displays all the elements in the array myList:
public class TestArray{
public static void main(String[] args){
double[] myList ={1
...
9,3
...
5};
// Print all the array elements
for(double element: myList){
System
...
println(element);
}
}
}
This would produce the following result:
1
...
9
3
...
5

Passing Arrays to Methods:
Just as you can pass primitive type values to methods, you can also pass arrays to methods
...
length; i++){
System
...
print(array[i]+" ");
}
}
You can invoke it by passing an array
...
For example, the method shown below returns an array that is the reversal of
another array:
publicstaticint[] reverse(int[] list){
int[] result =newint[list
...
length -1; i < list
...
util
...
These methods are overloaded for all primitive types
...
) for the specified value using the binary search
algorithm
...
This returns index of the search key, if it is
contained in the list; otherwise, (-(insertion point + 1)
...
Two arrays are considered equal if
both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays
are equal
...
Same method could be used by all other primitive data
types ( Byte, short, Int, etc
...
Same method could be used by
all other primitive data types ( Byte, short, Int, etc
...

Same method could be used by all other primitive data types ( Byte, short, Int, etc
...
util package, this class encapsulates the current date and time
...
The first constructor initializes the object with the current date and time
...


2

boolean before(Date date)
Returns true if the invoking Date object contains a date that is earlier than the one specified by date,
otherwise, it returns false
...


4

int compareTo(Date date)
Compares the value of the invoking object with that of date
...
Returns a
negative value if the invoking object is earlier than date
...


5

int compareTo(Object obj)
Operates identically to compareTo(Date) if obj is of class Date
...


6

boolean equals(Object date)
Returns true if the invoking Date object contains the same time and date as the one specified by date,
otherwise, it returns false
...


8

int hashCode( )

TUTORIALS POINT
Simply Easy Learning

Returns a hash code for the invoking object
...


Getting Current Date & Time
This is very easy to get current date and time in Java
...
util
...
out
...
toString());
}
}
This would produce the following result:
MonMay0409:51:52 CDT 2009

Date Comparison:
There are following three ways to compare two dates:



You can use getTime( ) to obtain the number of milliseconds that have elapsed since midnight, January 1,
1970, for both objects and then compare these two values
...
Because the 12th of the month comes before the
18th, for example, new Date(99, 2, 12)
...




You can use the compareTo( ) method, which is defined by the Comparable interface and implemented by
Date
...

SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting
...
util
...
text
...
MM
...
out
...
format(dNow));
}
}
This would produce the following result:
CurrentDate:Sun2004
...
18 at 04:14:09 PM PDT

Simple DateFormat format codes:
To specify the time format, use a time pattern string
...
M
...
M
...
in July)

W

Week in year

40

W

Week in month

1

A

A
...
/P
...
marker

PM

K

Hour in day (1~24)

24

K

Hour in A
...
/P
...
(0~11)

10

Z

Time zone

Eastern Standard Time

'

Escape for text

Delimiter

"

Single quote

`

Date Formatting using printf:
Date and time formatting can be done very easily using printf method
...
For example:
import java
...
Date;

TUTORIALS POINT
Simply Easy Learning

public class DateDemo{
public static void main(String args[]){
// Instantiate a Date object
Date date =new Date();
// display time and date using toString()
String str =String
...
out
...
For that reason, a format string
can indicate the index of the argument to be formatted
...
For example:
import java
...
Date;
public class DateDemo{
public static void main(String args[]){
// Instantiate a Date object
Date date =new Date();
// display time and date using toString()
System
...
printf("%1$s %2$tB %2$td, %2$tY",
"Due date:", date);
}
}
This would produce the following result:
Due date:February09,2004
Alternatively, you can use the < flag
...
For example:
import java
...
Date;
public class DateDemo{
public static void main(String args[]){
// Instantiate a Date object
Date date =new Date();
// display formatted date
System
...
printf("%s %tB %"Due date:", date);
}
}
This would produce the following result:
Due date:February09,2004

TUTORIALS POINT
Simply Easy Learning

Date and Time Conversion Characters:
Character Description

Example

c

Complete date and time

Mon May 04 09:51:52 CDT 2009

F

ISO 8601 date

2004-02-09

D

U
...
formatted date (month/day/year)

02/09/2004

T

24-hour time

18:05:19

r

12-hour time

06:05:19 pm

R

24-hour time, no seconds

18:05

Y

Four-digit year (with leading zeroes)

2004

y

Last two digits of the year (with leading zeroes)

04

C

First two digits of the year (with leading zeroes)

20

B

Full month name

February

b

Abbreviated month name

Feb

m

Two-digit month (with leading zeroes)

02

d

Two-digit day (with leading zeroes)

03

e

Two-digit day (without leading zeroes)

9

A

Full weekday name

Monday

a

Abbreviated weekday name

Mon

j

Three-digit day of year (with leading zeroes)

069

H

Two-digit hour (with leading zeroes), between 00 and 23

18

k

Two-digit hour (without leading zeroes), between 0 and
23

18

I

Two-digit hour (with leading zeroes), between 01 and 12

06

l

Two-digit hour (without leading zeroes), between 1 and
12

6

M

Two-digit minutes (with leading zeroes)

05

S

Two-digit seconds (with leading zeroes)

19

L

Three-digit milliseconds (with leading zeroes)

047

N

Nine-digit nanoseconds (with leading zeroes)

047000000

P

Uppercase morning or afternoon marker

PM

p

Lowercase morning or afternoon marker

pm

z

RFC 822 numeric offset from GMT

-0800

Z

Time zone

PST

s

Seconds since 1970-01-01 00:00:00 GMT

1078884319

TUTORIALS POINT
Simply Easy Learning

Q

Milliseconds since 1970-01-01 00:00:00 GMT

1078884319047

There are other useful classes related to Date and time
...


Parsing Strings into Dates:
The SimpleDateFormat class has some additional methods, notably parse( ) , which tries to parse a string according
to the format stored in the given SimpleDateFormat object
...
util
...
text
...
length ==0?"1818-11-11": args[0];
System
...
print(input +" Parses as ");
Date t;
try{
t = ft
...
out
...
out
...
For example,
following program would sleep for 10 seconds:
import java
...
*;
public class SleepDemo{
public static void main(String args[]){
try{
System
...
println(new Date()+"\n");
Thread
...
out
...
out
...
So let's rewrite above example once again:
import java
...
*;
public class DiffDemo{
public static void main(String args[]){
try{
long start =System
...
out
...
sleep(5*60*10);
System
...
println(new Date()+"\n");
longend=System
...
out
...
out
...
I did not discuss Calendar class in this tutorial, you can look standard Java
documentation for this
...
GregorianCalendar defines two fields: AD and BC
...

There are also several constructors for GregorianCalendar objects:
SN Constructor with Description
1

GregorianCalendar()
Constructs a default GregorianCalendar using the current time in the default time zone with the default locale
...


3

GregorianCalendar(int year, int month, int date, int hour, int minute)
Constructs a GregorianCalendar with the given date and time set for the default time zone with the default
locale
...


5

GregorianCalendar(Locale aLocale)
Constructs a GregorianCalendar based on the current time in the default time zone with the given locale
...


7

GregorianCalendar(TimeZone zone, Locale aLocale)
Constructs a GregorianCalendar based on the current time in the given time zone with the given locale
...


2

protected void computeFields()
Converts UTC as milliseconds to time field values
...


4

boolean equals(Object obj)
Compares this GregorianCalendar to an object reference
...


6

int getActualMaximum(int field)
Return the maximum value that this field could have, given the current date
...


8

int getGreatestMinimum(int field)
Returns highest minimum value for the given field if varies
...


10

int getLeastMaximum(int field)
Returns lowest maximum value for the given field if varies
...


12

Date getTime()
Gets this Calendar's current time
...


14

TimeZone getTimeZone()
Gets the time zone
...


16

int hashCode()

TUTORIALS POINT
Simply Easy Learning

Override hashCode
...


18

void roll(int field, boolean up)
Adds or subtracts (up/down) a single unit of time on the given time field without changing larger fields
...


20

void set(int year, int month, int date)
Sets the values for the fields year, month, and date
...


22

void set(int year, int month, int date, int hour, int minute, int second)
Sets the values for the fields year, month, date, hour, minute, and second
...


24

void setTime(Date date)
Sets this Calendar's current time with the given Date
...


26

void setTimeZone(TimeZone value)
Sets the time zone with the given time zone value
...


Example:
import java
...
*;
public class GregorianCalendarDemo{
public static void main(String args[]){
String months[]={
"Jan","Feb","Mar","Apr",
"May","Jun","Jul","Aug",
"Sep","Oct","Nov","Dec"};
int year;
// Create a Gregorian calendar initialized
// with the current date and time in the
// default locale and timezone
...

System
...
print("Date: ");
System
...
print(months[gcalendar
...
MONTH)]);
System
...
print(" "+ gcalendar
...
DATE)+" ");
System
...
println(year = gcalendar
...
YEAR));
System
...
print("Time: ");
System
...
print(gcalendar
...
HOUR)+":");
System
...
print(gcalendar
...
MINUTE)+":");
System
...
println(gcalendar
...
SECOND));

TUTORIALS POINT
Simply Easy Learning

// Test if the current year is a leap year
if(gcalendar
...
out
...
out
...


TUTORIALS POINT
Simply Easy Learning

CHAPTER

16
Java Regular Expressions

J

ava provides the java
...
regex package for pattern matching with regular expressions
...

A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings,
using a specialized syntax held in a pattern
...

The java
...
regex package primarily consists of the following three classes:


Pattern Class: A Pattern object is a compiled representation of a regular expression
...
To create a pattern, you must first invoke one of its public static compile
methods, which will then return a Pattern object
...




Matcher Class: A Matcher object is the engine that interprets the pattern and performs match operations
against an input string
...
You obtain a Matcher
object by invoking the matcher method on a Pattern object
...


Capturing Groups:
Capturing groups are a way to treat multiple characters as a single unit
...
For example, the regular expression (dog) creates a single group
containing the letters "d", "o", and "g"
...
In the expression
((A)(B(C))), for example, there are four such groups:



((A)(B(C)))



(A)



(B(C))



(C)

To find out how many groups are present in the expression, call the groupCount method on a matcher object
...


TUTORIALS POINT
Simply Easy Learning

There is also a special group, group 0, which always represents the entire expression
...


Example:
Following example illustrates how to find a digit string from the given alphanumeric string:
import java
...
regex
...
util
...
Pattern;
public class RegexMatches
{
public static void main(String args[]){
// String to be scanned to find the pattern
...
*)(\\d+)(
...
compile(pattern);
// Now create matcher object
...
matcher(line);
if(m
...
out
...
group(0));
System
...
println("Found value: "+ m
...
out
...
group(2));
}else{
System
...
println("NO MATCH");
}
}
}
This would produce the following result:
Found value:This order was places for QT3000! OK?
Found value:This order was places for QT300
Found value:0

Regular Expression Syntax:
Here is the table listing down all the regular expression metacharacter syntax available in Java:
Subexpression Matches
^

Matches beginning of line
...



...
Using m option allows it to match newline as well
...
]

Matches any single character in brackets
...
]

Matches any single character not in brackets

\A

Beginning of entire string

\z

End of entire string

\Z

End of entire string except allowable final line terminator
...


re+

Matches 1 or more of the previous thing

re?

Matches 0 or 1 occurrence of preceding expression
...


re{ n,}

Matches n or more occurrences of preceding expression
...


a| b

Matches either a or b
...


(?: re)

Groups regular expressions without remembering matched text
...


\w

Matches word characters
...


\s

Matches whitespace
...


\S

Matches nonwhitespace
...
Equivalent to [0-9]
...


\A

Matches beginning of string
...
If a newline exists, it matches just before newline
...


\G

Matches point where last match finished
...
Matches backspace (0x08) when inside
brackets
...


\n, \t, etc
...


\Q

Escape (quote) all characters up to \E

\E

Ends quoting begun with \Q

Methods of the Matcher Class:
Here is a list of useful instance methods:

Index Methods:
Index methods provide useful index values that show precisely where the match was found in the input string:
SN Methods with Description

TUTORIALS POINT
Simply Easy Learning

1

public int start()
Returns the start index of the previous match
...


3

public int end()
Returns the offset after the last character matched
...


Study Methods:
Study methods review the input string and return a Boolean indicating whether or not the pattern is found:
SN Methods with Description
1

public boolean lookingAt()
Attempts to match the input sequence, starting at the beginning of the region, against the pattern
...


3

public boolean find(int start
Resets this matcher and then attempts to find the next subsequence of the input sequence that matches the
pattern, starting at the specified index
...


Replacement Methods:
Replacement methods are useful methods for replacing text in an input string:
SN Methods with Description
1

public Matcher appendReplacement(StringBuffer sb, String replacement)
Implements a non-terminal append-and-replace step
...


3

public String replaceAll(String replacement)
Replaces every subsequence of the input sequence that matches the pattern with the given replacement
string
...


5

public static String quoteReplacement(String s)
Returns a literal replacement String for the specified String
...


The start and end Methods:
Following is the example that counts the number of times the word "cats" appears in the input string:

TUTORIALS POINT
Simply Easy Learning

import java
...
regex
...
util
...
Pattern;
public class RegexMatches
{
private static final String REGEX ="\\bcat\\b";
private static final String INPUT ="cat cat cat cattie cat";
public static void main(String args[]){
Pattern p =Pattern
...
matcher(INPUT);// get a matcher object
int count =0;
while(m
...
out
...
out
...
start());
System
...
println("end(): "+m
...
It also gives some useful information about where in the input string the match has occurred
...


The matches and lookingAt Methods:
The matches and lookingAt methods both attempt to match an input sequence against a pattern
...

Both methods always start at the beginning of the input string
...
util
...
Matcher;
import java
...
regex
...
compile(REGEX);
matcher = pattern
...
out
...
out
...
out
...
lookingAt());
System
...
println("matches(): "+matcher
...
As their names
indicate, replaceFirst replaces the first occurrence, and replaceAll replaces all occurrences
...
util
...
Matcher;
import java
...
regex
...
"+"All dogs say meow
...
compile(REGEX);
// get a matcher object
Matcher m = p
...
replaceAll(REPLACE);
System
...
println(INPUT);
}
}
This would produce the following result:
The cat says meow
...


The appendReplacement and appendTail Methods:
The Matcher class also provides appendReplacement and appendTail methods for text replacement
...
util
...
Matcher;
import java
...
regex
...
compile(REGEX);
// get a matcher object
Matcher m = p
...
find()){
m
...
appendTail(sb);
System
...
println(sb
...

The PatternSyntaxException class provides the following methods to help you determine what went wrong:
SN Methods with Description
1

public String getDescription()
Retrieves the description of the error
...


3

public String getPattern()
Retrieves the erroneous regular expression pattern
...


TUTORIALS POINT
Simply Easy Learning

CHAPTER

17
Java Methods

A

Javamethod is a collection of statements that are grouped together to perform an operation
...
out
...

Now you will learn how to create your own methods with or without return values, invoke a method with or without
parameters, overload methods using the same names, and apply method abstraction in the program design
...

int: return type
funcName: function name
a, b: formal parameters
int a, int b: list of parameters

Methods are also known as Procedures or Functions:




Procedures: They don't return any value
...


Method definition consists of a method header and a method body
...

returnType: Method may return a value
...
The method signature consists of the method name and the
parameter list
...
These are
optional, method may contain zero parameters
...


Example:
Here is the source code of the above defined method called max()
...
There are two ways in which a method is called i
...
method returns a value
or returning nothing (no return value)
...
When a program invokes a method, the program control gets transferred to
the called method
...




reaches the method ending closing brace
...
Lets consider an example:
System
...
println("This is tutorialspoint
...
out
...
Here, in the following example we're
considering a void method methodRankPoints
...
Call
to a void method must be a statement i
...
methodRankPoints(255
...
It is a Java statement which ends with a
semicolon as shown below
...
7);
}
public static void methodRankPoints(double points) {
if (points >= 202
...
out
...
4) {
System
...
println("Rank:A2");
}
else {
System
...
println("Rank:A3");
}
}
}
This would produce the following result:
Rank:A1

Passing Parameters by Value:
While working under calling process, arguments is to be passed
...
Parameters can be passed by value or by reference
...
Through this the argument value is passed
to the parameter
...
The values of the arguments remains the
same even after the method invocation
...
out
...
out
...
out
...
out
...
out
...

It is different from overriding
...

Lets consider the example shown before for finding minimum numbers of integer type
...
Then the concept of Overloading will be introduced to create two or more methods
with the same name but different parameters
...
3;
double d = 9
...
out
...
out
...
3
Overloading methods makes program readable
...
The minimum number from integer and double types is the result
...
This is accomplished by passing
command-line arguments to main( )
...
To access the command-line arguments inside a Java program is quite easy
...


Example:
The following program displays all of the command-line arguments that it is called with:
public class CommandLine{
public static void main(String args[]){
for(int i=0; i ...
out
...
It has the same name as its class and is syntactically similar to
a method
...

Typically, you will use a constructor to give initial values to the instance variables defined by the class, or to perform
any other startup procedures required to create a fully formed object
...
However, once you define your own constructor, the default
constructor is no longer used
...

class MyClass{
int x;
// Following is the constructor
MyClass(){
x =10;
}
}
You would call constructor to initialize objects as follows:
public class ConsDemo{
public static void main(String args[]){
MyClass t1 =new MyClass();
MyClass t2 =new MyClass();
System
...
println(t1
...
x);
}
}
Most often, you will need a constructor that accepts one or more parameters
...


Example:
Here is a simple example that uses a constructor:

TUTORIALS POINT
Simply Easy Learning

// A simple constructor
...
out
...
x +" "+ t2
...
5 enables you to pass a variable number of arguments of the same type to a method
...
parameterName
In the method declaration, you specify the type followed by an ellipsis (
...
Any regular parameters must precede it
...
5);
printMax(new double[]{1,2,3});
}
public static void printMax(double
...
length ==0){
System
...
println("No argument passed");
return;
}
double result = numbers[0];
for(int i =1; i < numbers
...
out
...
5
The max value is 3
...

This method is called finalize( ), and it can be used to ensure that an object terminates cleanly
...

To add a finalizer to a class, you simply define the finalize( ) method
...

Inside the finalize( ) method, you will specify those actions that must be performed before an object is destroyed
...

This means that you cannot know whenor even iffinalize( ) will be executed
...


TUTORIALS POINT
Simply Easy Learning

CHAPTER

18
Java Streams, Files and I/O

T

he java
...
All these streams represent an input source and an output destination
...
io package
supports many data such as primitives, Object, localized characters, etc
...
The InputStream is used to read data from a source and the
OutputStream is used for writing data to a destination
...
We would see most commonly used example one by one:

Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes
...
Following is an
example which makes use of these two classes to copy an input file into an output file:
import java
...
*;
public class CopyFile {
public static void main(String args[]) throws IOException
{
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("input
...
txt");
int c;
while ((c = in
...
write(c);
}
}finally {
if (in != null) {
in
...
close();
}
}

TUTORIALS POINT
Simply Easy Learning

}
}
Now let's have a file input
...

As a next step, compile above program and execute it, which will result in creating output
...
txt
...
java file and do the following:
$javac CopyFile
...
Though there are many classes related to character streams but the
most frequently used classes are , FileReader and FileWriter
...

We can re-write above example which makes use of these two classes to copy an input file (having unicode
characters) into an output file:
import java
...
*;
public class CopyFile {
public static void main(String args[]) throws IOException
{
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("input
...
txt");
int c;
while ((c = in
...
write(c);
}
}finally {
if (in != null) {
in
...
close();
}
}
}
}
Now let's have a file input
...

As a next step, compile above program and execute it, which will result in creating output
...
txt
...
java file and do the following:
$javac CopyFile
...
If you are aware if C or C++ programming languages,
then you must be aware of three standard devices STDIN, STDOUT and STDERR
...
in
...
out
...
err
...
io
...
in);
System
...
println("Enter characters, 'q' to quit
...
read();
System
...
print(c);
} while(c != 'q');
}finally {
if (cin != null) {
cin
...
java file and try to compile and execute it as below
...
java
$java ReadConsole
Enter characters, 'q' to quit
...
The InputStream is used to read data from a
source and the OutputStream is used for writing data to a destination
...


The two important streams are FileInputStream and FileOutputStream, which would be discussed in this tutorial:

FileInputStream:
This stream is used for reading data from the files
...

Following constructor takes a file name as a string to create an input stream object to read the file
...
First we create a file object
using File() method as follows:
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);
Once you have InputStream object in hand, then there is a list of helper methods which can be used to read to
stream or to do other operations on the stream
...
Releases any system resources associated with the file
...


2

protected void finalize()throws IOException {}
This method cleans up the connection to the file
...
Throws an IOException
...
Returns an int
...

4

public int read(byte[] r) throws IOException{}
This method reads r
...
Returns the total number of bytes read
...


5

public int available() throws IOException{}
Gives the number of bytes that can be read from this file input stream
...


There are other important input streams available, for more detail you can refer to the following links:




ByteArrayInputStream
DataInputStream

ByteArrayInputStream
The ByteArrayInputStream class allows a buffer in the memory to be used as an InputStream
...
There are following forms of constructors to create ByteArrayInputStream objects
Takes a byte array as the parameter:
ByteArrayInputStream bArray = new ByteArrayInputStream(byte [] a);
Another form takes an array of bytes, and two ints, where off is the first byte to be read and len is the number of
bytes to be read
...

SN Methods with Description
1

public int read()
This method reads the next byte of data from the InputStream
...
If it is end of file then it returns -1
...

Returns the total number of bytes read
...


3

public int available()
Gives the number of bytes that can be read from this file input stream
...


4

public void mark(int read)
This sets the current marked position in the stream
...


5

public long skip(long n)
Skips n number of bytes from the stream
...


Example:
Following is the example to demonstrate ByteArrayInputStream and ByteArrayOutputStream
import java
...
*;

TUTORIALS POINT
Simply Easy Learning

public class ByteStreamTest {
public static void main(String args[])throws IOException {
ByteArrayOutputStream bOutput = new ByteArrayOutputStream(12);
while( bOutput
...
write(System
...
read());
}
byte b [] = bOutput
...
out
...
length; x++) {
// printing the characters
System
...
print((char)b[x] + "
");
}
System
...
println("
");
int c;
ByteArrayInputStream bInput = new ByteArrayInputStream(b);
System
...
println("Converting characters to Upper case " );
for(int y = 0 ; y < 1; y++ ) {
while(( c= bInput
...
out
...
toUpperCase((char)c));
}
bInput
...

Following is the constructor to create an InputStream:
InputStream in = DataInputStream(InputStream in);

TUTORIALS POINT
Simply Easy Learning

Once you have DataInputStream object in hand, then there is a list of helper methods, which can be used to read
the stream or to do other operations on the stream
...
Returns the total number of bytes
read into the buffer otherwise -1 if it is end of file
...
Returns the total number of bytes
read into the buffer otherwise -1 if it is end of file
...
Returns the next two bytes of the
InputStream as the specific primitive type
...
It reads successive bytes, converting each byte separately
into a character, until it encounters a line terminator or end of file; the characters read are then returned as a
String
...
This example reads 5 lines given
in a file test
...
txt
...
io
...
txt"));
DataOutputStream out = new DataOutputStream(new
FileOutputStream("test1
...
readLine()) != null){
String u = count
...
out
...
writeBytes(u + " ,");
}
d
...
close();
}
}
Here is the sample run of the above program:
THIS
THIS
THIS
THIS
THIS

IS
IS
IS
IS
IS

TEST
TEST
TEST
TEST
TEST

1
2
3
4
5

,
,
,
,
,

TUTORIALS POINT
Simply Easy Learning

FileOutputStream:
FileOutputStream is used to create a file and write data into it
...

Here are two constructors which can be used to create a FileOutputStream object
...
First, we create a file
object using File() method as follows:
File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);
Once you have OutputStream object in hand, then there is a list of helper methods, which can be used to write to
stream or to do other operations on the stream
...
Releases any system resources associated with the file
...


2

protected void finalize()throws IOException {}
This method cleans up the connection to the file
...
Throws an IOException
...


4

public void write(byte[] w)
Writes w
...


There are other important output streams available, for more detail you can refer to the following links:




ByteArrayOutputStream
DataOutputStream

ByteArrayOutputStream
The ByteArrayOutputStream class stream creates a buffer in memory and all the data sent to the stream is stored in
the buffer
...


TUTORIALS POINT
Simply Easy Learning

SN Methods with Description
1

public void reset()
This method resets the number of valid bytes of the byte array output stream to zero, so all the accumulated
output in the stream will be discarded
...
Its size would be the current size of the output stream and
the contents of the buffer will be copied into it
...


3

public String toString()
Converts the buffer content into a string
...
Returns the String translated from the buffer's content
...


5

public void write(byte []b, int of, int len)
Writes len number of bytes starting from offset off to the stream
...


Example:
Following is the example to demonstrate ByteArrayOutputStream and ByteArrayOutputStream
import java
...
*;
public class ByteStreamTest {
public static void main(String args[])throws IOException {
ByteArrayOutputStream bOutput = new ByteArrayOutputStream(12);
while( bOutput
...
write(System
...
read());
}
byte b [] = bOutput
...
out
...
length; x++) {
//printing the characters
System
...
print((char)b[x] + "
");
}
System
...
println("
");
int c;
ByteArrayOutputStream bInput = new ByteArrayOutputStream(b);
System
...
println("Converting characters to Upper case " );
for(int y = 0 ; y < 1; y++ ) {
while(( c= bInput
...
out
...
toUpperCase((char)c));
}
bInput
...

Following is the constructor to create a DataOutputStream
...

SN Methods with Description
1

public final void write(byte[] w, int off, int len)throws IOException
Writes len bytes from the specified byte array starting at point off , to the underlying stream
...
Returns the total number of
bytes write into the buffer
...


4

Public void flush()throws IOException
Flushes the data output stream
...
Each character in the
string is written out, in sequence, by discarding its high eight bits
...
This example reads 5 lines
given in a file test
...
txt
...
io
...
txt"));
DataOutputStream out = new DataOutputStream(new
FileOutputStream("test1
...
readLine()) != null){
String u = count
...
out
...
writeBytes(u + " ,");
}
d
...
close();
}
}
Here is the sample run of the above program:
THIS
THIS
THIS
THIS
THIS

IS
IS
IS
IS
IS

TEST
TEST
TEST
TEST
TEST

1
2
3
4
5

,
,
,
,
,

Example:
Following is the example to demonstrate InputStream and OutputStream:
import java
...
*;
public class fileStreamTest{
public static void main(String args[]){
try{
byte bWrite [] = {11,21,3,40,5};
OutputStream os = new FileOutputStream("test
...
length ; x++){
os
...
close();
InputStream is = new FileInputStream("test
...
available();
for(int i=0; i< size; i++){
System
...
print((char)is
...
close();
}catch(IOException e){
System
...
print("Exception");
}
}
}

TUTORIALS POINT
Simply Easy Learning

");

The above code would create file test
...
Same would be output on
the stdout screen
...






File Class
FileReader Class
FileWriter Class

File Class
Java File class represents the files and directory pathnames in an abstract manner
...

The File object represents the actual file/directory on the disk
...

File(File parent, String child);
Following syntax creates a new File instance by converting the given pathname string into an abstract pathname
...

File(String parent, String child)
Following syntax creates a new File instance by converting the given file: URI into an abstract pathname
...

SN Methods with Description
1

public String getName()
Returns the name of the file or directory denoted by this abstract pathname
...


3

public File getParentFile()
Returns the abstract pathname of this abstract pathname's parent, or null if this pathname does not name a
parent directory
...


5

public boolean isAbsolute()
Tests whether this abstract pathname is absolute
...


7

public boolean canRead()
Tests whether the application can read the file denoted by this abstract pathname
...


8

public boolean canWrite()
Tests whether the application can modify to the file denoted by this abstract pathname
...


9

public boolean exists()
Tests whether the file or directory denoted by this abstract pathname exists
...
Returns true if and only if the file
denoted by this abstract pathname exists and is a directory; false otherwise
...
A file is normal if it is not a directory
and, in addition, satisfies other system-dependent criteria
...
Returns true if and only if the file denoted by this abstract
pathname exists and is a normal file; false otherwise
...
Returns a long value
representing the time the file was last modified, measured in milliseconds since the epoch (00:00:00 GMT,
January 1, 1970), or 0L if the file does not exist or if an I/O error occurs
...
The return value is unspecified if this
pathname denotes a directory
...
Returns true if the named file does not exist and was successfully created; false if the named
file already exists
...
If this pathname denotes a directory, then the
directory must be empty in order to be deleted
...


16

public void deleteOnExit()
Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine
terminates
...


18

public String[] list(FilenameFilter filter)
Returns an array of strings naming the files and directories in the directory denoted by this abstract
pathname that satisfy the specified filter
...


21

public File[] listFiles(FileFilter filter)

TUTORIALS POINT
Simply Easy Learning

Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this
abstract pathname that satisfy the specified filter
...
Returns true if and only if the directory was created;
false otherwise
...
Returns true if and only if the directory was created, along with all necessary parent directories;
false otherwise
...
Returns true if and only if the renaming succeeded;
false otherwise
...
Returns true if and only if
the operation succeeded; false otherwise
...

Returns true if and only if the operation succeeded; false otherwise
...
Returns an abstract pathname denoting a newly-created empty file
...
Invoking this method is equivalent to invoking createTempFile(prefix, suffix, null)
...


29

public int compareTo(File pathname)
Compares two abstract pathnames lexicographically
...


30

public int compareTo(Object o)
Compares this abstract pathname to another object
...


31

public boolean equals(Object obj)
Tests this abstract pathname for equality with the given object
...


32

public String toString()
Returns the pathname string of this abstract pathname
...


Example:
Following is the example to demonstrate File object:
package com
...
io
...
txt", "test2
...
canExecute();
// find the absolute path
String a = f
...
out
...
out
...
printStackTrace();
}
}
}
Consider there is an executable file test1
...
txt is non executable in current directory, Let us
compile and run the above program, this will produce the following result:
test1
...
txt is executable: false

FileReader Class
This class inherits from the InputStreamReader class
...

This class has several constructors to create required objects
...

FileReader(File file)
Following syntax creates a new FileReader, given the FileDescriptor to read from
...

FileReader(String fileName)
Once you have FileReader object in hand then there is a list of helper methods which can be used manipulate the
files
...
Returns an int, which represents the character read
...
Returns the number of characters read
...
io
...
txt");
// creates the file
file
...
write("This\n is\n an\n example\n");
writer
...
close();
//Creates a FileReader Object
FileReader fr = new FileReader(file);
char [] a = new char[50];
fr
...
out
...
close();
}
}
This would produce the following result:
This
is
an
example

FileWriter Class
This class inherits from the OutputStreamWriter class
...

This class has several constructors to create required objects
...

FileWriter(File file)
Following syntax creates a FileWriter object given a File object
...

FileWriter(FileDescriptor fd)
Following syntax creates a FileWriter object given a file name
...

FileWriter(String fileName, boolean append)
Once you have FileWriter object in hand, then there is a list of helper methods, which can be used manipulate the
files
...


2

public void write(char [] c, int offset, int len)
Writes a portion of an array of characters starting from offset and with a length of len
...


Example:
Following is the example to demonstrate class:
import java
...
*;
public class FileRead{
public static void main(String args[])throws IOException{
File file = new File("Hello1
...
createNewFile();
// creates a FileWriter Object
FileWriter writer = new FileWriter(file);
// Writes the content to the file
writer
...
flush();
writer
...
read(a); // reads the content to the array
for(char c : a)
System
...
print(c); //prints the characters one by one
fr
...
You use File object to create directories,
to list down files available in a directory
...


Creating Directories:
There are two useful File utility methods, which can be used to create directories:
 The mkdir( ) method creates a directory, returning true on success and false on failure
...

 The mkdirs() method creates both a directory and all the parents of the directory
...
io
...

d
...

Note: Java automatically takes care of path separators on UNIX and Windows as per conventions
...


Listing Directories:
You can use list( ) method provided by File object to list down all the files and directories available in a directory as
follows:
import java
...
File;
public class ReadDir {
public static void main(String[] args) {
File file = null;
String[] paths;
try{
// create new file object
file = new File("/tmp");
// array of files and directory
paths = file
...
out
...
printStackTrace();
}
}
}
This would produce following result based on the directories and files available in your /tmp directory:
test1
...
txt
ReadDir
...
class

TUTORIALS POINT
Simply Easy Learning

CHAPTER

19
Java Exceptions

A

nexception is a problem that arises during the execution of a program
...




A file that needs to be opened cannot be found
...


Some of these exceptions are caused by user error, others by programmer error, and others by physical resources
that have failed in some manner
...
For example, if a file is to be opened, but the file cannot be found, an
exception occurs
...

Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided
by the programmer
...

Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the
programmer
...
For
example, if a stack overflow occurs, an error will arise
...


Exception Hierarchy:
All exception classes are subtypes of the java
...
Exception class
...
Other than the exception class there is another subclass called Error which is derived from the
Throwable class
...
These conditions normally happen in case of severe
failures, which are not handled by the java programs
...
Example : JVM is out of Memory
...

The Exception class has two main subclasses: IOException class and RuntimeException Class
...


Java’s Built-in Exceptions
Java defines several exception classes inside the standard package java
...

The most general of these exceptions are subclasses of the standard type RuntimeException
...
lang is
implicitly imported into all Java programs, most exceptions derived from RuntimeException are automatically
available
...
Following is the list of Java
Unchecked RuntimeException
...


ArrayIndexOutOfBoundsException

Array index is out-of-bounds
...


ClassCastException

Invalid cast
...


IllegalMonitorStateException

Illegal monitor operation, such as waiting on an unlocked thread
...


IllegalThreadStateException

Requested operation not compatible with current thread state
...


NegativeArraySizeException

Array created with a negative size
...


NumberFormatException

Invalid conversion of a string to a numeric format
...


StringIndexOutOfBounds

Attempt to index outside the bounds of a string
...


Following is the list of Java Checked Exceptions Defined in java
...

Exception

Description

ClassNotFoundException

Class not found
...


IllegalAccessException

Access to a class is denied
...


InterruptedException

One thread has been interrupted by another thread
...


NoSuchMethodException

A requested method does not exist
...

SN Methods with Description
1

public String getMessage()
Returns a detailed message about the exception that has occurred
...


2

public Throwable getCause()
Returns the cause of the exception as represented by a Throwable object
...
err, the error output stream
...
The element at index 0 represents
the top of the call stack, and the last element in the array represents the method at the bottom of
the call stack
...


Catching Exceptions:
A method catches an exception using a combination of the try and catch keywords
...
Code within a try/catch block is referred to as protected code,
and the syntax for using try/catch looks like the following:
try
{
//Protected code
}catch(ExceptionName e1)
{
//Catch block

TUTORIALS POINT
Simply Easy Learning

}
A catch statement involves declaring the type of exception you are trying to catch
...
If the type of exception that occurred is
listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method
parameter
...
Then, the code tries to access the 3rd element of the array
which throws an exception
...
java
import java
...
*;
public class ExcepTest{
public static void main(String args[]){
try{
int a[]=new int[2];
System
...
println("Access element three :"+ a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System
...
println("Exception thrown :"+ e);
}
System
...
println("Out of the block");
}
}
This would produce the following result:
Exception thrown
Out of the block

:java
...
ArrayIndexOutOfBoundsException:3

Multiple catch Blocks:
A try block can be followed by multiple catch blocks
...
If
an exception occurs in the protected code, the exception is thrown to the first catch block in the list
...
If not, the exception passes down to the
second catch statement
...


Example:
Here is code segment showing how to use multiple try/catch statements
...
read();
}catch(IOException i)
{
i
...
printStackTrace();
return-1;
}

The throws/throw Keywords:
If a method does not handle a checked exception, the method must declare it using the throwskeyword
...

You can throw an exception, either a newly instantiated one or an exception that you just caught, by using
the throw keyword
...

The following method declares that it throws a RemoteException:
import java
...
*;
public class className
{
public void deposit(double amount)throws RemoteException
{
// Method implementation
throw new RemoteException();
}
//Remainder of class definition
}
A method can declare that it throws more than one exception, in which case the exceptions are declared in a list
separated by commas
...
io
...
A finally block of code always
executes, whether or not an exception has occurred
...

A finally block appears at the end of the catch blocks and has the following syntax:

TUTORIALS POINT
Simply Easy Learning

try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}finally
{
//The finally block always executes
...
out
...
out
...
out
...
out
...
lang
...




It is not compulsory to have finally clauses whenever a try/catch block is present
...




Any code cannot be present in between the try, catch, finally blocks
...
Keep the following points in mind when writing your own exception
classes:

TUTORIALS POINT
Simply Easy Learning



All exceptions must be a child of Throwable
...




If you want to write a runtime exception, you need to extend the RuntimeException class
...
These are considered to be
checked exceptions
...
An exception class is like any other class, containing useful fields
and methods
...
java
import java
...
*;
public class InsufficientFundsException extends Exception
{
private double amount;
public InsufficientFundsException(double amount)
{
this
...

// File Name CheckingAccount
...
io
...
number = number;
}
public void deposit(double amount)
{
balance += amount;
}
public void withdraw(double amount)throws InsufficientFundsException
{
if(amount <= balance)
{
balance -= amount;
}
else

TUTORIALS POINT
Simply Easy Learning

{
double needs = amount - balance;
throw new InsufficientFundsException(needs);
}
}
public double getBalance()
{
return balance;
}
public int getNumber()
{
return number;
}
}
The following BankDemo
CheckingAccount
...
java
public class BankDemo
{
public static void main(String[] args)
{
CheckingAccount c =new CheckingAccount(101);
System
...
println("Depositing $500
...
deposit(500
...
out
...
");
c
...
00);
System
...
println("\nWithdrawing $600
...
withdraw(600
...
out
...
getAmount());
e
...

Withdrawing $100
...

Sorry, but you are short $200
...
withdraw(CheckingAccount
...
main(BankDemo
...


TUTORIALS POINT
Simply Easy Learning

methods

of




JVM Exceptions: - These are exceptions/errors that are exclusively or logically thrown by the JVM
...
Examples: IllegalArgumentException, IllegalStateException
...
With the use of

inheritance, the information is made manageable in a hierarchical order
...
These
words would determine whether one object IS-A type of another
...


IS-A Relationship:
IS-A is a way of saying : This object is a type of that object
...

public class Animal{
}
public class Mammal extends Animal{
}
public class Reptile extends Animal{
}
public class Dog extends Mammal{
}
Now, based on the above example, In Object Oriented terms the following are true:


Animal is the superclass of Mammal class
...




Mammal and Reptile are subclasses of Animal class
...


Now, if we consider the IS-A relationship, we can say:


Mammal IS-A Animal



Reptile IS-A Animal

TUTORIALS POINT
Simply Easy Learning



Dog IS-A Mammal



Hence : Dog IS-A Animal as well

With use of the extends keyword the subclasses will be able to inherit all the properties of the superclass except for
the private properties of the superclass
...


Example:
public class Dog extends Mammal{
public static void main(String args[]){
Animal a =new Animal();
Mammal m =new Mammal();
Dog d =new Dog();
System
...
println(m instanceof Animal);
System
...
println(d instanceof Mammal);
System
...
println(d instanceof Animal);
}
}
This would produce the following result:
true
true
true
Since we have a good understanding of the extends keyword, let us look into how the implementskeyword is used
to get the IS-A relationship
...
Interfaces can never be extended by the
classes
...
out
...
out
...
out
...
This determines whether a certain class HAS-Acertain thing
...

Lets us look into an example:
public class Vehicle{}
public class Speed{}
public class Van extends Vehicle{
privateS peed sp;
}
This shows that class Van HAS-A Speed
...

In Object-Oriented feature, the users do not need to bother about which object is doing the real work
...
So basically what happens is
the users would ask the Van class to do a certain action and the Van class will either do the work by itself or ask
another class to perform the action
...
This means that a class cannot
extend more than one class
...
This has made Java get rid of the impossibility of multiple
inheritance
...
If a class inherits a method from its

superclass, then there is a chance to override the method provided that it is not marked final
...

In object-oriented terms, overriding means to override the functionality of an existing method
...

classAnimal{
public void move(){
System
...
println("Animals can move");
}
}
class Dog extends Animal{
public void move(){
System
...
println("Dogs can walk and run");
}
}
public class TestDog{
public static void main(String args[]){
Animal a =new Animal();// Animal reference and object
Animal b =new Dog();// Animal reference but Dog object
a
...
move();//Runs the method in Dog class
}
}
This would produce the following result:

TUTORIALS POINT
Simply Easy Learning

Animals can move
Dogs can walk and run
In the above example, you can see that the even though b is a type of Animal it runs the move method in the Dog
class
...
However, in the runtime,
JVM figures out the object type and would run the method that belongs to that particular object
...
Then,
at the runtime, it runs the method specific for that object
...
out
...
out
...
out
...
move();// runs the method in Animal class
b
...
bark();
}
}
This would produce the following result:
TestDog
...
bark();
^
This program will throw a compile time error since b's reference type Animal doesn't have a method by the name of
bark
...

 The return type should be the same or a subtype of the return type declared in the original overridden method
in the superclass
...
For example, if the
superclass method is declared public, then the overriding method in the subclass cannot be either private or
protected
...

 A method declared final cannot be overridden
...

 If a method cannot be inherited, then it cannot be overridden
...


 A subclass in a different package can only override the non-final methods declared public or protected
...
However the overriding method should not throw checked exceptions that are new or
broader than the ones declared by the overridden method
...


 Constructors cannot be overridden
...

class Animal{
public void move(){
System
...
println("Animals can move");
}
}
class Dog extends Animal{
public void move(){
super
...
out
...
move();//Runs the method in Dog class
}
}
This would produce the following result:
Animals can move
Dogs can walk and run

TUTORIALS POINT
Simply Easy Learning

CHAPTER

22
Java Polymorphism

P

olymorphism is the ability of an object to take on many forms
...

Any Java object that can pass more than one IS-A test is considered to be polymorphic
...

It is important to know that the only possible way to access an object is through a reference variable
...
Once declared, the type of a reference variable cannot be changed
...
The type of the
reference variable would determine the methods that it can invoke on the object
...
A reference
variable can be declared as a class or interface type
...

public interfaceVegetarian{}
public class Animal{}
public class Deer extends Animal implements Vegetarian{}
Now, the Deer class is considered to be polymorphic since this has multiple inheritance
...


Virtual Methods:
In this section, I will show you how the behavior of overridden methods in Java allows you to take advantage of
polymorphism when designing your classes
...
An
overridden method is essentially hidden in the parent class, and is not invoked unless the child class uses the super
keyword within the overriding method
...
java */
public class Employee
{
private String name;
private String address;
private int number;
public Employee(String name,String address,int number)
{
System
...
println("Constructing an Employee");
this
...
address = address;
this
...
out
...
name
+" "+this
...
java */
public class Salaryextends Employee
{
private double salary;//Annual salary
public Salary(String name,String address,int number,double

TUTORIALS POINT
Simply Easy Learning

salary)
{
super(name, address, number);
setSalary(salary);
}
public void mailCheck()
{
System
...
println("Within mailCheck of Salary class ");
System
...
println("Mailing check to "+ getName()
+" with salary "+ salary);
}
public double getSalary()
{
return salary;
}
public void setSalary(double newSalary)
{
if(newSalary >=0
...
out
...
java */
public class VirtualDemo
{
public static void main(String[] args)
{
Salary s =new Salary("Mohd Mohtashim","Ambehta, UP",
3,3600
...
00);
System
...
println("Call mailCheck using Salary reference --");
s
...
out
...
mailCheck();
}
}
This would produce the following result:
Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference -Within mailCheck of Salary class
Mailing check to MohdMohtashim with salary 3600
...
0

TUTORIALS POINT
Simply Easy Learning

Here, we instantiate two Salary objects, one using a Salary reference s, and the other using an Employee reference
e
...
mailCheck() the compiler sees mailCheck() in the Salary class at compile time, and the JVM
invokes mailCheck() in the Salary class at run time
...
When the compiler
seese
...

Here, at compile time, the compiler used mailCheck() in Employee to validate this statement
...

This behavior is referred to as virtual method invocation, and the methods are referred to as virtual methods
...


TUTORIALS POINT
Simply Easy Learning

CHAPTER

23
Java Abstraction

A

bstraction refers to the ability to make a class abstract in OOP
...
All other functionality of the class still exists, and its fields, methods, and constructors are all accessed
in the same manner
...

If a class is abstract and cannot be instantiated, the class does not have much use unless it is subclass
...
A parent class contains the common
functionality of a collection of child classes, but the parent class itself is too abstract to be used on its own
...
The keyword appears in the class declaration somewhere
before the class keyword
...
java */
public abstract classEmployee
{
private String name;
private String address;
private int number;
public Employee(String name,String address,int number)
{
System
...
println("Constructing an Employee");
this
...
address = address;
this
...
out
...
0;
}
public void mailCheck()
{
System
...
println("Mailing a check to "+this
...
address);
}
public String toString()
{
return name +" "+ address +" "+ number;
}

TUTORIALS POINT
Simply Easy Learning

public String getName()
{
return name;
}
public String getAddress()
{
return address;
}
public void setAddress(String newAddress)
{
address = newAddress;
}
public int getNumber()
{
return number;
}
}
Notice that nothing is different in this Employee class
...

Now if you would try as follows:
/* File name : AbstractDemo
...
","Houston, TX",43);
System
...
println("\n Call mailCheck usingEmployee reference--");
e
...
java:46:Employee is abstract; cannot be instantiated
Employee e =new Employee("George W
...
java */
public class Salary extends Employee
{
private double salary;//Annual salary
public Salary(String name,String address,int number,double salary)
{
super(name, address, number);
setSalary(salary);
}
public void mailCheck()
{
System
...
println("Within mailCheck of Salary class ");
System
...
println("Mailing check to "+ getName()

TUTORIALS POINT
Simply Easy Learning

+" with salary "+ salary);
}
public double getSalary()
{
return salary;
}
public void setSalary(double newSalary)
{
if(newSalary >=0
...
out
...

/* File name : AbstractDemo
...
00);
Employee e =new Salary("John Adams","Boston, MA",
2,2400
...
out
...
mailCheck();
System
...
println("\n Call mailCheck usingEmployee reference--");
e
...
0
Call mailCheck using Employee reference-Within mailCheck of Salary class
Mailing check to JohnAdams with salary 2400
...

The abstract keyword is also used to declare a method as abstract
...


TUTORIALS POINT
Simply Easy Learning

Abstract method would have no definition, and its signature is followed by a semicolon, not curly braces as follows:
public abstract class Employee
{
private String name;
private String address;
private int number;
public abstract tdouble computePay();
//Remainder of class definition
}
Declaring a method as abstract has two results:


The class must also be declared abstract
...




Any child class must either override the abstract method or declare itself abstract
...
If they do not, they must be abstractand any of their
children must override it
...

If Salary is extending Employee class, then it is required to implement computePay() method as follows:
/* File name : Salary
...
out
...
The other three are inheritance, polymorphism,

and abstraction
...
If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields
within the class
...

Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed
by other code defined outside the class
...

The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others
who use our code
...


Example:
Let us look at an example that depicts encapsulation:
/* File name : EncapTest
...
Normally, these methods
are referred as getters and setters
...

The variables of the EncapTest class can be access as below:
/* File name : RunEncap
...
setName("James");
encap
...
setIdNum("12343ms");
System
...
print("Name : "+ encap
...
getAge());
}
}
This would produce the following result:
Name:JamesAge:20

Benefits of Encapsulation:
The fields of a class can be made read-only or write-only
...

The users of a class do not know how the class stores its data
...


TUTORIALS POINT
Simply Easy Learning

CHAPTER

25
Java Interfaces

A

n interface is a collection of abstract methods
...

An interface is not a class
...
A
class describes the attributes and behaviors of an object
...

Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the
class
...

 An interface is written in a file with a
...


 The bytecode of an interface appears in a
...

 Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that
matches the package name
...

 An interface does not contain any constructors
...

 An interface cannot contain instance fields
...


 An interface is not extended by a class; it is implemented by a class
...


TUTORIALS POINT
Simply Easy Learning

Declaring Interfaces:
The interface keyword is used to declare an interface
...
java */
import java
...
*;
//Any number of import statements
public interface NameOfInterface
{
//Any number of final, static fields
//Any number of abstract method declarations\
}
Interfaces have the following properties:

 An interface is implicitly abstract
...

 Each method in an interface is also implicitly abstract, so the abstract keyword is not needed
...


Example:
/* File name : Animal
...
If a class does not perform all the behaviors of the interface, the class must
declare itself as abstract
...
The implements keyword appears in the class
declaration following the extends portion of the declaration
...
java */
public class MammalInt implements Animal{
public void eat(){
System
...
println("Mammal eats");
}
public void travel(){
System
...
println("Mammal travels");
}
public int noOfLegs(){
return0;
}

TUTORIALS POINT
Simply Easy Learning

public static void main(String args[]){
MammalInt m =new MammalInt();
m
...
travel();
}
}
This would produce the following result:
Mammal eats
Mammal travels
When overriding methods defined in interfaces there are several rules to be followed:

 Checked exceptions should not be declared on implementation methods other than the ones declared by the
interface method or subclasses of those declared by the interface method
...


 An implementation class itself can be abstract and if so interface methods need not be implemented
...

 A class can extend only one class, but implement many interfaces
...


Extending Interfaces:
An interface can extend another interface, similarly to the way that a class can extend another class
...

The following Sports interface is extended by Hockey and Football interfaces
...
java
public interface Sports
{
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}
//Filename: Football
...
java
public interface Hockey extends Sports
{
public void homeGoalScored();
public void visitingGoalScored();

TUTORIALS POINT
Simply Easy Learning

public void endOfPeriod(int period);
public void overtimePeriod(int ot);
}
The Hockey interface has four methods, but it inherits two from Sports; thus, a class that implements Hockey needs
to implement all six methods
...


Extending Multiple Interfaces:
A Java class can only extend one parent class
...
Interfaces are not classes,
however, and an interface can extend more than one parent interface
...

For example, if the Hockey interface extended both Sports and Event, it would be declared as:
public interface Hockey extends Sports,Event

Tagging Interfaces:
The most common use of extending interfaces occurs when the parent interface does not contain any methods
...
awt
...
util
...
util;
public interface EventListener
{}
An interface with no methods in it is referred to as a tagging interface
...
For
example, when an interface extends EventListener, the JVM knows that this particular interface is going to be used
in an event delegation scenario
...
A class that implements a
tagging interface does not need to define any methods (since the interface does not have any), but the class
becomes an interface type through polymorphism
...

A Package can be defined as a grouping of related types(classes, interfaces, enumerations and annotations)
providing access protection and name space management
...
lang - bundles the fundamental classes
 java
...
It is a good practice to
group related classes implemented by you so that a programmer can easily determine that the classes, interfaces,
enumerations, annotations are related
...

Using packages, it is easier to provide access control and it is also easier to locate the related classed
...

The package statement should be the first line in the source file
...

If a package statement is not used then the class, interfaces, enumerations, and annotation types will be put into an
unnamed package
...
It is common practice to use lowercased names
of packages to avoid any conflicts with the names of classes, interfaces
...
java */
package animals;
interface Animal{
public void eat();
public void travel();

TUTORIALS POINT
Simply Easy Learning

}
Now, put an implementation in the same package animals:
package animals;
/* File name : MammalInt
...
out
...
out
...
eat();
m
...
classMammalInt
...
Classes in
the same package find each other without any special syntax
...
The Boss can then refer
to the Employee class without using the payroll prefix, as demonstrated by the following Boss class
...
mailCheck();
}
}
What happens if Boss is not in the payroll package? The Boss class must then use one of the following techniques
for referring to a class in a different package
...
For example:

payroll
...
For example:

import payroll
...
For example:

import payroll
...
The import statements must appear after the
package statement and before the class declaration
...




The name of the package must match the directory structure where the corresponding bytecode resides
...
java
...
java

package vehicle;
public class Car{
// Class implementation
...
\vehicle\Car
...
Car



Path name -> vehicle\Car
...
Example: A company's
Internet domain name is apple
...
apple
...

Example: The company had a com
...
computers package that contained a Dell
...
\com\apple\computers\Dell
...
The base name of the output file is the name of the type, and its extension is
...
java
package com
...
computers;
public class Dell{
}
classUps{
}
Now, compile this file as follows using -d option:
$javac -d
...
java
This would put compiled files as follows:

...
class

...
class
You can import all the classes or interfaces defined in \com\apple\computers\ as follows:
import com
...
computers
...
java source files, the compiled
...
However, the path to the
...
java source files
...
java
\classes\com\apple\computers\Dell
...
You
also need to manage source and class files in this manner so that the compiler and the Java Virtual Machine (JVM)
can find all the types your program uses
...
Both the compiler and the JVM construct the path to your
...

Say \classes is the class path, and the package name is com
...
computers, then the compiler and
JVM will look for
...

A class path may include several paths
...
By default, the compiler and the JVM search the current directory and the JAR file containing the Java
platform classes so that these directories are automatically in the class path
...
These data structures consist of the following interface and classes:



Enumeration



BitSet



Vector



Stack



Dictionary



Hashtable



Properties

All these classes are now legacy and Java-2 has introduced a new framework called Collections Framework, which
is discussed in next tutorial:

The Enumeration:
The Enumeration interface isn't itself a data structure, but it is very important within the context of other data
structures
...

For example, Enumeration defines a method called nextElement that is used to get the next element in a data
structure that contains multiple elements
...

This legacy interface has been superceded by Iterator
...
However, it is used by several methods defined by the legacy classes such as Vector and
Properties, is used by several other API classes, and is currently in widespread use in application code
...


2

Object nextElement( )
This returns the next object in the enumeration as a generic Object reference
...

import java
...
Vector;
import java
...
Enumeration;
public class EnumerationTester{
public static void main(String args[]){
Enumeration days;
Vector dayNames =newVector();
dayNames
...
add("Monday");
dayNames
...
add("Wednesday");
dayNames
...
add("Friday");
dayNames
...
elements();
while(days
...
out
...
nextElement());
}
}
}
This would produce the following result:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

The BitSet
The BitSet class implements a group of bits or flags that can be set and cleared individually
...

A BitSet class creates a special type of array that holds bit values
...

This makes it similar to a vector of bits
...
4
...
The first version creates a default object:

TUTORIALS POINT
Simply Easy Learning

BitSet()
The second version allows you to specify its initial size, i
...
, the number of bits that it can hold
...

BitSet(int size)
BitSet implements the Cloneable interface and defines the methods listed in table below:
SN Methods with Description
1

void and(BitSet bitSet)
ANDs the contents of the invoking BitSet object with those specified by bitSet
...


2

void andNot(BitSet bitSet)
For each 1 bit in bitSet, the corresponding bit in the invoking BitSet is cleared
...


4

void clear( )
Zeros all bits
...


6

void clear(int startIndex, int endIndex)
Zeros the bits from startIndex to endIndex
...


7

Object clone( )
Duplicates the invoking BitSet object
...
Otherwise, the method
returns false
...
(

10

void flip(int startIndex, int endIndex)
Reverses the bits from startIndex to endIndex
...


11

boolean get(int index)
Returns the current state of the bit at the specified index
...
1
...


13

int hashCode( )
Returns the hash code for the invoking object
...


15

boolean isEmpty( )
Returns true if all bits in the invoking object are zero
...
This value is
determined by the location of the last 1 bit
...
If no bit is set,
...


19

void or(BitSet bitSet)
ORs the contents of the invoking BitSet object with that specified by bitSet
...


20

void set(int index)
Sets the bit specified by index
...
true sets the bit, false clears the bit
...
1
...
1, to the value passed in v
...


24

int size( )
Returns the number of bits in the invoking BitSet object
...


26

void xor(BitSet bitSet)
XORs the contents of the invoking BitSet object with that specified by bitSet
...
util
...
set(i);
if((i%5)!=0) bits2
...
out
...
out
...
out
...
out
...
and(bits1);
System
...
println("\nbits2 AND bits1: ");
System
...
println(bits2);

TUTORIALS POINT
Simply Easy Learning

// OR bits
bits2
...
out
...
out
...
xor(bits1);
System
...
println("\nbits2 XOR bits1: ");
System
...
println(bits2);
}
}
This would produce the following result:
Initial pattern in bits1:
{0,2,4,6,8,10,12,14}
Initial pattern in bits2:
{1,2,3,4,6,7,8,9,11,12,13,14}
bits2 AND bits1:
{2,4,6,8,12,14}
bits2 OR bits1:
{0,2,4,6,8,10,12,14}
bits2 XOR bits1:
{}

The Vector
The Vector class is similar to a traditional Java array, except that it can grow as necessary to accommodate new
elements
...

The nice thing about using the Vector class is that you don't have to worry about setting it to a specific size upon
creation; it shrinks and grows automatically when necessary
...
It is similar to ArrayList, but with two differences:



Vector is synchronized
...


Vector proves to be very useful if you don't know the size of the array in advance or you just need one that can
change sizes over the lifetime of a program
...
The first form creates a default vector, which has an initial size of 10:
Vector()
The second form creates a vector whose initial capacity is specified by size:
Vector(int size)
The third form creates a vector whose initial capacity is specified by size and whose increment is specified by incr
...


2

boolean add(Object o)
Appends the specified element to the end of this Vector
...


4

boolean addAll(int index, Collection c)
Inserts all of the elements in in the specified Collection into this Vector at the specified position
...


6

int capacity()
Returns the current capacity of this vector
...


8

Object clone()
Returns a clone of this vector
...


10

boolean containsAll(Collection c)
Returns true if this Vector contains all of the elements in the specified Collection
...


12

Object elementAt(int index)
Returns the component at the specified index
...


14

void ensureCapacity(int minCapacity)
Increases the capacity of this vector, if necessary, to ensure that it can hold at least the number of
components specified by the minimum capacity argument
...


16

Object firstElement()
Returns the first component (the item at index 0) of this vector
...


TUTORIALS POINT
Simply Easy Learning

18

int hashCode()
Returns the hash code value for this Vector
...


20

int indexOf(Object elem, int index)
Searches for the first occurence of the given argument, beginning the search at index, and testing
for equality using the equals method
...


22

boolean isEmpty()
Tests if this vector has no components
...


24

int lastIndexOf(Object elem)
Returns the index of the last occurrence of the specified object in this vector
...


26

Object remove(int index)
Removes the element at the specified position in this Vector
...


28

boolean removeAll(Collection c)
Removes from this Vector all of its elements that are contained in the specified Collection
...


30

boolean removeElement(Object obj)
Removes the first (lowest-indexed) occurrence of the argument from this vector
...


33

boolean retainAll(Collection c)
Retains only the elements in this Vector that are contained in the specified Collection
...


35

void setElementAt(Object obj, int index)
Sets the component at the specified index of this vector to be the specified object
...


37

int size()

TUTORIALS POINT
Simply Easy Learning

Returns the number of components in this vector
...


39

Object[] toArray()
Returns an array containing all of the elements in this Vector in the correct order
...


41

String toString()
Returns a string representation of this Vector, containing the String representation of each
element
...


Example:
The following program illustrates several of the methods supported by this collection:
import java
...
*;
public class VectorDemo{
public static void main(String args[]){
// initial size is 3, increment is 2
Vector v =new Vector(3,2);
System
...
println("Initial size: "+ v
...
out
...
capacity());
v
...
addElement(new Integer(2));
v
...
addElement(new Integer(4));
System
...
println("Capacity after four additions: "+v
...
addElement(new Double(5
...
out
...
capacity());
v
...
08));
v
...
out
...
capacity());
v
...
4));
v
...
out
...
capacity());
v
...
addElement(new Integer(12));
System
...
println("First element: "+(Integer)v
...
out
...
lastElement());
if(v
...
out
...
");
// enumerate the elements in the vector
...
elements();
System
...
println("\nElements in vector:");
while(vEnum
...
out
...
nextElement()+" ");
System
...
println();
}
}

TUTORIALS POINT
Simply Easy Learning

This would produce the following result:
Initial size:0
Initial capacity:3
Capacity after four additions:5
Current capacity:5
Current capacity:7
Current capacity:9
First element:1
Last element:12
Vector contains 3
...
456
...
4101112

The Stack
The Stack class implements a last-in-first-out (LIFO) stack of elements
...

When you pull an element off the stack, it comes off the top
...

Stack is a subclass of Vector that implements a standard last-in, first-out stack
...
Stack includes all the methods defined by
Vector and adds several of its own
...
Returns true if the stack is empty, and returns false if the stack
contains elements
...


3

Object pop( )
Returns the element on the top of the stack, removing it in the process
...
element is also returned
...
If found, its offset from the top of the stack is returned
...
1 is returned
...
util
...
push(new Integer(a));
System
...
println("push("+ a +")");
System
...
println("stack: "+ st);
}
static void showpop(Stack st){
System
...
print("pop -> ");
Integer a =(Integer) st
...
out
...
out
...
out
...
out
...

This is useful in cases where you want to be able to access data via a particular key rather than an integer index
...

Dictionary is an abstract class that represents a key/value storage repository and operates much like Map
...
Once the value is stored, you can retrieve it
by using its key
...

The abstract methods defined by Dictionary are listed below:
SN Methods with Description
1

Enumeration elements( )
Returns an enumeration of the values contained in the dictionary
...
If key is not in the dictionary, a null
object is returned
...


4

Enumeration keys( )
Returns an enumeration of the keys contained in the dictionary
...
Returns null if key is not already in the dictionary;
returns the previous value associated with key if key is already in the dictionary
...
Returns the value associated with key
...


7

int size( )
Returns the number of entries in the dictionary
...
You should implement the Map interface to obtain key/value storage functionality
...
A key is an object that you use to retrieve a value at a later date
...
After the value is stored, you can retrieve it
by using its key
...




A ClassCastException is thrown when an object is incompatible with the elements in a map
...




A NullPointerException is thrown if an attempt is made to use a null object and null is not allowed in the map
...


SN Methods with Description
1

void clear( )
Removes all key/value pairs from the invoking map
...
Otherwise, returns false
...
Otherwise, returns false
...
The set contains objects of type Map
...

This method provides a set-view of the invoking map
...
Otherwise, returns false
...


7

int hashCode( )
Returns the hash code for the invoking map
...
Otherwise, returns false
...
This method provides a set-view of the
keys in the invoking map
...
The key
and value are k and v, respectively
...
Otherwise, the
previous value linked to the key is returned
...


12

Object remove(Object k)
Removes the entry whose key equals k
...


14

Collection values( )
Returns a collection containing the values in the map
...


Example:
Map has its implementation in various classes like HashMap, Following is the example to explain map functionality:
import java
...
*;
public class CollectionsDemo{
public static void main(String[] args){
Map m1 =new HashMap();
m1
...
put("Mahnaz","31");
m1
...
put("Daisy","14");
System
...
println();
System
...
println(" Map Elements");
System
...
print("\t"+ m1);
}
}
This would produce the following result:

TUTORIALS POINT
Simply Easy Learning

MapElements
{Mahnaz=31,Ayan=12,Daisy=14,Zara=8}

The Hashtable
The Hashtable class provides a means of organizing data based on some user-defined key structure
...

The specific meaning of keys in regard to hashtables is totally dependent on the usage of the hashtable and the
data it contains
...
util and is a concrete implementation of a Dictionary
...
Thus, Hashtable is now
integrated into the collections framework
...

Like HashMap, Hashtable stores key/value pairs in a hashtable
...
The key is then hashed, and the resulting hash
code is used as the index at which the value is stored within the table
...
The first version is the default constructor:
Hashtable()
The second version creates a hashtable that has an initial size specified by size:
Hashtable(int size)
The third version creates a hashtable that has an initial size specified by size and a fill ratio specified by fillRatio
...
0 and 1
...

Hashtable(int size,float fillRatio)
The fourth version creates a hashtable that is initialized with the elements in m
...
The default load factor of 0
...

Hashtable(Map m)
Apart from the methods defined by Map interface, Hashtable defines the following methods:
SN Methods with Description
1

void clear( )
Resets and empties the hash table
...


3

boolean contains(Object value)
Returns true if some value equal to value exists within the hash table
...


4

boolean containsKey(Object key)
Returns true if some key equal to key exists within the hash table
...

5

boolean containsValue(Object value)
Returns true if some value equal to value exists within the hash table
...


6

Enumeration elements( )
Returns an enumeration of the values contained in the hash table
...
If key is not in the hash table, a null
object is returned
...


9

Enumeration keys( )
Returns an enumeration of the keys contained in the hash table
...
Returns null if key isn't already in the hash table;
returns the previous value associated with key if key is already in the hash table
...


12

Object remove(Object key)
Removes key and its value
...
If key is not in the hash table,
a null object is returned
...


14

String toString( )
Returns the string equivalent of a hash table
...
util
...
put("Zara",new Double(3434
...
put("Mahnaz",new Double(123
...
put("Ayan",new Double(1378
...
put("Daisy",new Double(99
...
put("Qadir",new Double(-19
...

names = balance
...
hasMoreElements()){
str =(String) names
...
out
...
get(str));

TUTORIALS POINT
Simply Easy Learning

}
System
...
println();
// Deposit 1,000 into Zara's account
bal =((Double)balance
...
doubleValue();
balance
...
out
...
get("Zara"));
}
}
This would produce the following result:
Qadir:-19
...
34
Mahnaz:123
...
22
Ayan:1378
...
34

The Properties
Properties is a subclass of Hashtable
...

The Properties class is used by many other Java classes
...
getProperties( ) when obtaining environmental values
...
It is used to maintain lists of values in which the key is a String and the value
is also a String
...
For example, it is the type of object returned by
System
...

Properties define the following instance variable
...

Properties defaults;
The Properties define two constructors
...
In both cases, the property list is empty:
Properties(Properties propDefault)
Apart from the methods defined by Hashtable, Properties define the following methods:
SN Methods with Description
1

String getProperty(String key)
Returns the value associated with key
...


2

String getProperty(String key, String defaultProperty)
Returns the value associated with key
...


TUTORIALS POINT
Simply Easy Learning

3

void list(PrintStream streamOut)
Sends the property list to the output stream linked to streamOut
...


5

void load(InputStream streamIn) throws IOException
Inputs a property list from the input stream linked to streamIn
...
This includes those keys found in the default property list,
too
...
Returns the previous value associated with key, or returns null if no
such association exists
...


Example:
The following program illustrates several of the methods supported by this data structure:
import java
...
*;
public class PropDemo{
public static void main(String args[]){
Properties capitals =new Properties();
Set states;
String str;
capitals
...
put("Missouri","Jefferson City");
capitals
...
put("California","Sacramento");
capitals
...

states = capitals
...
iterator();
while(itr
...
next();
System
...
println("The capital of "+str +" is "+capitals
...
");
}
System
...
println();
// look for state not in list -- specify default
str = capitals
...
out
...
");
}
}
This would produce the following result:
The
The
The
The

capital
capital
capital
capital

of
of
of
of

Missouri is JeffersonCity
...

Indiana is Indianapolis
...


TUTORIALS POINT
Simply Easy Learning

The capital of Washington is Olympia
...


TUTORIALS POINT
Simply Easy Learning

CHAPTER

28
Java Collections

P

riorto Java 2, Java provided ad hoc classes such as Dictionary, Vector, Stack, and Properties to store

and manipulate groups of objects
...

Thus, the way that you used Vector was different from the way that you used Properties
...




The framework had to be high-performance
...




The framework had to allow different types of collections to work in a similar manner and with a high degree of
interoperability
...


Towards this end, the entire collections framework is designed around a set of standard interfaces
...

A collections framework is a unified architecture for representing and manipulating collections
...
Interfaces allow collections to be
manipulated independently of the details of their representation
...




Implementations, i
...
, Classes: These are the concrete implementations of the collection interfaces
...




Algorithms: These are the methods that perform useful computations, such as searching and sorting, on
objects that implement collection interfaces
...


In addition to collections, the framework defines several map interfaces and classes
...

Although maps are not collections in the proper use of the term, but they are fully integrated with collections
...
This section provides an overview of each interface:
SN Interfaces with Description
1

The Collection Interface

TUTORIALS POINT
Simply Easy Learning

This enables you to work with groups of objects; it is at the top of the collections hierarchy
...


3

The Set
This extends Collection to handle sets, which must contain unique elements

4

The SortedSet
This extends Set to handle sorted sets

5

The Map
This maps unique keys to values
...
Entry
This describes an element (a key/value pair) in a map
...


7

The SortedMap
This extends Map so that the keys are maintained in ascending order
...
This legacy interface has been superceded by
Iterator
...
Some of the classes provide
full implementations that can be used as-is and others are abstract class, providing skeletal implementations that
are used as starting points for creating concrete collections
...


2

AbstractList
Extends AbstractCollection and implements most of the List interface
...


4

LinkedList
Implements a linked list by extending AbstractSequentialList
...


6

AbstractSet
Extends AbstractCollection and implements most of the Set interface
...


8

LinkedHashSet
Extends HashSet to allow insertion-order iterations
...
Extends AbstractSet
...


11

HashMap
Extends AbstractMap to use a hash table
...


13

WeakHashMap
Extends AbstractMap to use a hash table with weak keys
...


15

IdentityHashMap
Extends AbstractMap and uses reference equality when comparing documents
...

The following legacy classes defined by java
...
It is similar to ArrayList, but with some differences
...


3

Dictionary
Dictionary is an abstract class that represents a key/value storage repository and operates much
like Map
...
util and is a concrete implementation of a Dictionary
...
It is used to maintain lists of values in which the key is a
String and the value is also a String
...
This array can increase in size
as needed
...
These algorithms
are defined as static methods within the Collections class
...

Collections define three static variables: EMPTY_SET, EMPTY_LIST, and EMPTY_MAP
...

SN

Algorithms with Description

1

The Collection Algorithms
Here is a list of all the algorithm implementation
...
For example, you might want to display each
element
...

Iterator enables you to cycle through a collection, obtaining or removing elements
...

SN Iterator Methods with Description
1

Using Java Iterator
Here is a list of all the methods with examples provided by Iterator and ListIterator interfaces
...
For example, you might want to display each
element
...

Iterator enables you to cycle through a collection, obtaining or removing elements
...

Before you can access a collection through an iterator, you must obtain one
...
By using this iterator object, you can
access each element in the collection, one element at a time
...




Set up a loop that makes a call to hasNext( )
...




Within the loop, obtain each element by calling next( )
...


The Methods Declared by Iterator:
SN Methods with Description
1

boolean hasNext( )
Returns true if there are more elements
...


2

Object next( )
Returns the next element
...


3

void remove( )
Removes the current element
...


TUTORIALS POINT
Simply Easy Learning

The Methods Declared by ListIterator:
SN Methods with Description
1

void add(Object obj)
Inserts obj into the list in front of the element that will be returned by the next call to next( )
...
Otherwise, returns false
...
Otherwise, returns false
...
A NoSuchElementException is thrown if there is not a next element
...
If there is not a next element, returns the size of the list
...
A NoSuchElementException is thrown if there is not a previous element
...
If there is not a previous element, returns -1
...
An IllegalStateException is thrown if remove( ) is called before
next( ) or previous( ) is invoked
...
This is the element last returned by a call to either next( ) or previous( )
...
It uses an ArrayList object, but the general
principles apply to any type of collection
...

import java
...
*;
public class IteratorDemo {
public static void main(String args[]) {
// Create an array list
ArrayList al = new ArrayList();
// add elements to the array list
al
...
add("A");
al
...
add("B");
al
...
add("F");
// Use iterator to display contents of al
System
...
print("Original contents of al: ");
Iterator itr = al
...
hasNext()) {
Object element = itr
...
out
...
out
...
listIterator();
while(litr
...
next();
litr
...
out
...
iterator();
while(itr
...
next();
System
...
print(element + " ");
}
System
...
println();
// Now, display the list backwards
System
...
print("Modified list backwards: ");
while(litr
...
previous();
System
...
print(element + " ");
}
System
...
println();
}
}
This would produce the following result:
Original contents of al: C A E B D F
Modified contents of al: C+ A+ E+ B+ D+ F+
Modified list backwards: F+ D+ B+ E+ A+ C+

How to use a Comparator?
Both TreeSet and TreeMap store elements in sorted order
...

This interface lets us sort a given collection any number of different ways
...

SN

Iterator Methods with Description

1

Using Java Comparator
Here is a list of all the methods with examples provided by Comparator Interface
...
However, it is the comparator that defines precisely
what sorted order means
...
The compare( ) method, shown here,
compares two elements for order:

The compare Method:
int compare(Object obj1, Object obj2)

TUTORIALS POINT
Simply Easy Learning

obj1 and obj2 are the objects to be compared
...
It returns a positive
value if obj1 is greater than obj2
...

By overriding compare( ), you can alter the way that objects are ordered
...


The equals Method:
The equals( ) method, shown here, tests whether an object equals the invoking comparator:
boolean equals(Object obj)
obj is the object to be tested for equality
...
Otherwise, it returns false
...


Example:
class Dog implements Comparator, Comparable{
private String name;
private int age;
Dog(){
}
Dog(String n, int a){
name = n;
age = a;
}
public String getDogName(){
return name;
}
public int getDogAge(){
return age;
}
// Overriding the compareTo method
public int compareTo(Dog d){
return (this
...
compareTo(d
...
age - d1
...
add(new
list
...
add(new
list
...
add(new Dog("Tammy",1));
Collections
...
out
...
getDogName() + ", ");
// Sorts the array list using comparator
Collections
...
out
...
out
...
getDogName() +" : "+
a
...


Summary:
The Java collections framework gives the programmer access to prepackaged data structures as well as to
algorithms for manipulating them
...
The collection interfaces declare the operations
that can be performed on each type of collection
...
util
...

Java Generic methods and generic classes enable programmers to specify, with a single method declaration, a set
of related methods or, with a single class declaration, a set of related types, respectively
...

Using Java Generic concept, we might write a generic method for sorting an array of objects, then invoke the
generic method with Integer arrays, Double arrays, String arrays and so on, to sort the array elements
...
Based on
the types of the arguments passed to the generic method, the compiler handles each method call appropriately
...




Each type parameter section contains one or more type parameters separated by commas
...




The type parameters can be used to declare the return type and act as placeholders for the types of the
arguments passed to the generic method, which are known as actual type arguments
...
Note that type parameters can represent
only reference types, not primitive types (like int, double and char)
...
out
...
out
...
1,2
...
3,4
...
out
...
out
...
out
...
12
...
34
...
For example, a method that operates on numbers might only want to accept instances of Number or its
subclasses
...

To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by
its upper bound
...
This example is Generic method to return the largest of three Comparable objects:
public class MaximumTest
{
// determines the largest of three Comparable objects
publicstatic> T maximum(T x, T y, T z)
{
T max = x;// assume x is initially the largest
if( y
...
compareTo( max )>0){
max = z;// z is the largest now
}
return max;// returns the largest object
}
public static void main(String args[])
{
System
...
printf("Max of %d, %d and %d is %d\n\n",3,4,5, maximum(3,4,5));
System
...
printf("Maxm of %
...
1f and %
...
1f\n\n",6
...
8,7
...
6,8
...
7));
System
...
printf("Max of %s, %s and %s is %s\n","pear",
"apple","orange", maximum("pear","apple","orange"));
}
}
This would produce the following result:
Maximum of 3,4and5is5
Maximum of 6
...
8and7
...
8
Maximum of pear, apple and orange is pear

Generic Classes:
A generic class declaration looks like a non-generic class declaration, except that the class name is followed by a
type parameter section
...
These classes are known as parameterized classes or parameterized types because they
accept one or more parameters
...
t = t;
}
public T get(){
return t;
}
public static void main(String[] args){
Box integerBox =new Box();
Box stringBox =new Box();
integerBox
...
add(new String("Hello World"));
System
...
printf("Integer Value :%d\n\n", integerBox
...
out
...
get());

TUTORIALS POINT
Simply Easy Learning

}
}
This would produce the following result:
IntegerValue:10
StringValue:HelloWorld

TUTORIALS POINT
Simply Easy Learning

CHAPTER

30
Java Serialization

J

ava provides a mechanism, called object serialization where an object can be represented as a sequence of

bytes that includes the object's data as well as information about the object's type and the types of data stored in the
object
...

Most impressive is that the entire process is JVM independent, meaning an object can be serialized on one platform
and deserialized on an entirely different platform
...

The ObjectOutputStream class contains many write methods for writing various data types, but one method in
particular stands out:
public final void writeObject(Object x)throws IOException
The above method serializes an Object and sends it to the output stream
...
The return value is Object, so you will
need to cast it to its appropriate data type
...
Suppose that we have the following Employee class, which implements the Serializable interface:
public class Employeeimplements java
...
Serializable
{
public String name;
public String address;
public transient int SSN;
public int number;
public void mailCheck()
{
System
...
println("Mailing a check to "+ name+" "+ address);
}
}

TUTORIALS POINT
Simply Easy Learning

Notice that for a class to be serialized successfully, two conditions must be met:



The class must implement the java
...
Serializable interface
...
If a field is not serializable, it must be marked transient
...
The
test is simple: If the class implements java
...
Serializable, then it is serializable; otherwise, it's not
...
The following SerializeDemo program instantiates an
Employee object and serializes it to a file
...
ser is created
...

Note: When serializing an object to a file, the standard convention in Java is to give the file a
...

import java
...
*;
public class SerializeDemo
{
public static void main(String[] args)
{
Employee e =new Employee();
e
...
address ="Phokka Kuan, Ambehta Peer";
e
...
number =101;
try
{
FileOutputStream fileOut =new FileOutputStream("employee
...
writeObject(e);
out
...
close();
}catch(IOException i)
{
i
...

Study the program and try to determine its output:
import java
...
*;
public class DeserializeDemo
{
public static void main(String[] args)
{
Employee e =null;
try
{
FileInputStream fileIn =new FileInputStream("employee
...
readObject();
in
...
close();
}catch(IOException i)
{
i
...
out
...
printStackTrace();
return;
}
System
...
println("Deserialized Employee
...
out
...
name);
System
...
println("Address: "+ e
...
out
...
SSN);
System
...
println("Number: "+ e
...

Name:ReyanAli
Address:PhokkaKuan,AmbehtaPeer
SSN:0
Number:101
Here are following important points to be noted:



The try/catch block tries to catch a ClassNotFoundException, which is declared by the readObject() method
...
If the JVM
can't find a class during the deserialization of an object, it throws a ClassNotFoundException
...




The value of the SSN field was 11122333 when the object was serialized, but because the field is transient,
this value was not sent to the output stream
...


TUTORIALS POINT
Simply Easy Learning

CHAPTER

31
Java Networking

T

he term network programming refers to writing programs that execute across multiple devices (computers),

in which the devices are all connected to each other using a network
...
net package of the J2SE APIs contains a collection of classes and interfaces that provide the low-level
communication details, allowing you to write programs that focus on solving the problem at hand
...
net package provides support for the two common network protocols:




TCP: TCP stands for Transmission Control Protocol, which allows for reliable communication between two
applications
...

UDP: UDP stands for User Datagram Protocol, a connection-less protocol that allows for packets of data to be
transmitted between applications
...

URL Processing: This would be covered separately
...


Url Processing
URL stands for Uniform Resource Locator and represents a resource on the World Wide Web, such as a Web page
or FTP directory
...
A URL can be broken down into
parts, as follows:
protocol://host:port/path?query#ref
Examples of protocols include HTTP, HTTPS, FTP, and File
...

The following is a URL to a Web page whose protocol is HTTP:
http://www
...
com/index
...
With HTTP, the
default port is 80
...
net
...

The URL class has several constructors for creating URLs, including the following:
SN Methods with Description
1

public URL(String protocol, String host, int port, String file) throws
MalformedURLException
...


2

public URL(String protocol, String host, String file) throws MalformedURLException
Identical to the previous constructor, except that the default port for the given protocol is used
...

Some of the methods in the URL class include the following:
SN

Methods with Description

1

public String getPath()
Returns the path of the URL
...


3

public String getAuthority()
Returns the authority of the URL
...


5

public int getDefaultPort()
Returns the default port for the protocol of the URL
...


7

public String getHost()
Returns the host of the URL
...


9

public String getFile()
Returns the filename of the URL
...


11

public URLConnection openConnection() throws IOException
Opens a connection to the URL, allowing a client to communicate with the resource
...
A URL is entered on the command line,
and the URLDemo program outputs each part of the given URL
...
java
import java
...
*;
import java
...
*;
public class URLDemo
{
public static void main(String[] args)
{
try
{
URL url =new URL(args[0]);
System
...
println("URL is "+ url
...
out
...
getProtocol());
System
...
println("authority is "+ url
...
out
...
getFile());
System
...
println("host is "+ url
...
out
...
getPath());
System
...
println("port is "+ url
...
out
...
getDefaultPort());
System
...
println("query is "+ url
...
out
...
getRef());
}catch(IOException e)
{
e
...
amrood
...
htm?language=en#j2se
URL is http://www
...
com/index
...
amrood
...
htm?language=en
host is www
...
com
path is/index
...
net
...

For example:



If you connect to a URL whose protocol is HTTP, the openConnection() method returns an
HttpURLConnection object
...




etc
...


2

Object getContent(Class[] classes)
Retrieves the contents of this URL connection
...


4

int getContentLength()
Returns the value of the content-length header field
...


6

int getLastModified()
Returns the value of the last-modified header field
...


8

long getIfModifiedSince()
Returns the value of this object's ifModifiedSince field
...
The default value is true
because clients typically read from a URLConnection
...
The default value is false
because many types of URLs do not support being written to
...


12

public OutputStream getOutputStream() throws IOException
Returns the output stream of the URL connection for writing to the resource

13

public URL getURL()
Returns the URL that this URLConnection object is connected to

Example:
The following URLConnectionDemo program connects to a URL entered from the command line
...

// File Name : URLConnDemo
...
net
...
io
...
openConnection();

TUTORIALS POINT
Simply Easy Learning

HttpURLConnection connection =null;
if(urlConnection instanceof HttpURLConnection)
{
connection =(HttpURLConnection) urlConnection;
}
else
{
System
...
println("Please enter an HTTP URL
...
getInputStream()));
String urlString ="";
String current;
while((current =in
...
out
...
printStackTrace();
}
}
}
A sample run of the thid program would produce the following result:
$ java URLConnDemo http://www
...
com

...
com
...
A client program creates a
socket on its end of the communication and attempts to connect that socket to a server
...
The client and
server can now communicate by writing to and reading from the socket
...
net
...
net
...

The following steps occur when establishing a TCP connection between two computers using sockets:



The server instantiates a ServerSocket object, denoting which port number communication is to occur on
...
This method waits until a client connects to
the server on the given port
...




The constructor of the Socket class attempts to connect the client to the specified server and port number
...


TUTORIALS POINT
Simply Easy Learning



On the server side, the accept() method returns a reference to a new socket on the server that is connected to
the client's socket
...
Each socket has both an
OutputStream and an InputStream
...

TCP is a twoway communication protocol, so data can be sent across both streams at the same time
...


ServerSocket Class Methods:
The java
...
ServerSocket class is used by server applications to obtain a port and listen for client requests
The ServerSocket class has four constructors:
SN Methods with Description
1

public ServerSocket(int port) throws IOException
Attempts to create a server socket bound to the specified port
...


2

public ServerSocket(int port, int backlog) throws IOException
Similar to the previous constructor, the backlog parameter specifies how many incoming clients to
store in a wait queue
...
The InetAddress is used for servers that may have multiple IP addresses, allowing the
server to specify which of its IP addresses to accept client requests on

4

public ServerSocket() throws IOException
Creates an unbound server socket
...

Here are some of the common methods of the ServerSocket class:
SN Methods with Description
1

public int getLocalPort()
Returns the port that the server socket is listening on
...


2

public Socket accept() throws IOException
Waits for an incoming client
...
Otherwise, this method blocks indefinitely
...


4

public void bind(SocketAddress host, int backlog)
Binds the socket to the specified server and port in the SocketAddress object
...


When the ServerSocket invokes accept(), the method does not return until a client connects
...

A TCP connection now exists between the client and server, and communication can begin
...
net
...
The client obtains a Socket object by instantiating one, whereas the server obtains a Socket object from the
return value of the accept() method
...

This method attempts to connect to the specified server at the specified port
...


2

public Socket(InetAddress host, int port) throws IOException
This method is identical to the previous constructor, except that the host is denoted by an
InetAddress object
...

Connects to the specified host and port, creating a socket on the local host at the specified
address and port
...

This method is identical to the previous constructor, except that the host is denoted by an
InetAddress object instead of a String

5

public Socket()
Creates an unconnected socket
...


When the Socket constructor returns, it does not simply instantiate a Socket object but it actually attempts to
connect to the specified server and port
...
Notice that both the client and server have a Socket
object, so these methods can be invoked by both the client and server
...
This method is needed only when you
instantiated the Socket using the no-argument constructor
...


3

public int getPort()
Returns the port the socket is bound to on the remote machine
...


5

public SocketAddress getRemoteSocketAddress()
Returns the address of the remote socket
...
The input stream is connected to the output stream of the
remote socket
...
The output stream is connected to the input stream of the

TUTORIALS POINT
Simply Easy Learning

remote socket
8

public void close() throws IOException
Closes the socket, which makes this Socket object no longer capable of connecting again to any
server

InetAddress Class Methods:
This class represents an Internet Protocol (IP) address
...


2

static InetAddress getByAddress(String host, byte[] addr)
Create an InetAddress based on the provided host name and IP address
...


4

String getHostAddress()
Returns the IP address string in textual presentation
...


6

static InetAddress InetAddress getLocalHost()
Returns the local host
...


Socket Client Example:
The following GreetingClient is a client program that connects to a server by using a socket and sends a greeting,
and then waits for a response
...
java
import java
...
*;
import java
...
*;
public class GreetingClient
{
public static void main(String[] args)
{
String serverName = args[0];
int port =Integer
...
out
...
out
...
getRemoteSocketAddress());
OutputStream outToServer = client
...
writeUTF("Hello from "+ client
...
getInputStream();

TUTORIALS POINT
Simply Easy Learning

DataInputStreamin=newDataInputStream(inFromServer);
System
...
println("Server says "+in
...
close();
}catch(IOException e)
{
e
...
java
import java
...
*;
import java
...
*;
public class GreetingServer extends Thread
{
private ServerSocket serverSocket;
public GreetingServer(int port)throws IOException
{
serverSocket =new ServerSocket(port);
serverSocket
...
out
...
getLocalPort()+"
...
accept();
System
...
println("Just connected to "
+ server
...
getInputStream());
System
...
println(in
...
getOutputStream());
out
...
getLocalSocketAddress()+"\nGoodbye!");
server
...
out
...
printStackTrace();
break;
}
}
}
public static void main(String[] args)

TUTORIALS POINT
Simply Easy Learning

{
int port =Integer
...
start();
}catch(IOException e)
{
e
...

Check client program as follows:
$ java GreetingClient localhost 6066
Connecting to localhost on port 6066
Just connected to localhost/127
...
0
...
0
...
1:6066
Goodbye!

TUTORIALS POINT
Simply Easy Learning

CHAPTER

32
Java Sending E-mail

T

o send an e-mail using your Java Application is simple enough but to start with you should haveJavaMail

API and Java Activation Framework (JAF) installed on your machine
...
2) from Java's standard website
...
1
...


Download and unzip these files, in the newly created top level directories you will find a number of jar files for both
the applications
...
jar and activation
...


Send a Simple E-mail:
Here is an example to send a simple e-mail from your machine
...

// File Name SendEmail
...
util
...
mail
...
mail
...
*;
javax
...
*;

public class SendEmail
{
public static void main(String[] args)
{
// Recipient's email ID needs to be mentioned
...
com";
// Sender's email ID needs to be mentioned
Stringfrom="web@gmail
...
getProperties();
// Setup mail server
properties
...
smtp
...


TUTORIALS POINT
Simply Easy Learning

Session session =Session
...

MimeMessage message =new MimeMessage(session);
// Set From: header field of the header
...
setFrom(new InternetAddress(from));
// Set To: header field of the header
...
addRecipient(Message
...
TO,new InternetAddress(to));
// Set Subject: header field
message
...
setText("This is actual message");
// Send message
Transport
...
out
...
");
}catch(MessagingException mex){
mex
...

If you want to send an e-mail to multiple recipients, then following methods would be used to specify multiple e-mail
IDs:
void addRecipients(Message
...
Here CC represents Carbon Copy and BCC represents Black
Carbon Copy
...
RecipientType
...
You would need to use InternetAddress() method while specifying email IDs

Send an HTML E-mail:
Here is an example to send an HTML e-mail from your machine
...

This example is very similar to previous one, except here we are using setContent() method to set content, whose
second argument is "text/html" to specify that the HTML content is included in the message
...

// File Name SendHTMLEmail
...
util
...
mail
...
mail
...
*;
import javax
...
*;
public class SendHTMLEmail
{
public static void main(String[] args)
{
// Recipient's email ID needs to be mentioned
...
com";
// Sender's email ID needs to be mentioned
Stringfrom="web@gmail
...
getProperties();
// Setup mail server
properties
...
smtp
...

Session session =Session
...

MimeMessage message =new MimeMessage(session);
// Set From: header field of the header
...
setFrom(new InternetAddress(from));
// Set To: header field of the header
...
addRecipient(Message
...
TO,
newInternetAddress(to));
// Set Subject: header field
message
...
setContent("

This is actual message

",
"text/html");
// Send message
Transport
...
out
...
");
}catch(MessagingException mex){
mex
...


TUTORIALS POINT
Simply Easy Learning

Send Attachment in E-mail:
Here is an example to send an e-mail with attachment from your machine
...

// File Name SendFileEmail
...
util
...
mail
...
mail
...
*;
javax
...
*;

public class SendFileEmail
{
public static void main(String[] args)
{
// Recipient's email ID needs to be mentioned
...
com";
// Sender's email ID needs to be mentioned
Stringfrom="web@gmail
...
getProperties();
// Setup mail server
properties
...
smtp
...

Session session =Session
...

MimeMessage message =new MimeMessage(session);
// Set From: header field of the header
...
setFrom(new InternetAddress(from));
// Set To: header field of the header
...
addRecipient(Message
...
TO,
new InternetAddress(to));
// Set Subject: header field
message
...
setText("This is message body");
// Create a multipar message
Multipart multipart =new MimeMultipart();
// Set text message part
multipart
...
txt";
DataSource source =new FileDataSource(filename);
messageBodyPart
...
setFileName(filename);
multipart
...
setContent(multipart );
// Send message
Transport
...
out
...
");
}catch(MessagingException mex){
mex
...


User Authentication Part:
If it is required to provide user ID and Password to the e-mail server for authentication purpose, then you can set
these properties as follows:
props
...
user","myuser");
props
...
password","mypwd");
Rest of the e-mail sending mechanism would remain as explained above
...
A multithreaded program contains two or more parts that can run concurrently and each part can handle
different task at the same time making optimal use of the available resources specially when your computer has
multiple CPUs
...

Multithreading extends the idea of multitasking into applications where you can subdivide specific operations within
a single application into individual threads
...
The OS divides processing time
not only among different applications, but also among each thread within an application
...


Life Cycle of a Thread:
A thread goes through various stages in its life cycle
...

Following diagram shows complete life cycle of a thread
...
It remains in this state until the program starts the
thread
...

Runnable: After a newly born thread is started, the thread becomes runnable
...

Waiting: Sometimes, a thread transitions to the waiting state while the thread waits for another thread to
perform a task
...

Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of time
...

Terminated: A runnable thread enters the terminated state when it completes its task or otherwise terminates
...

Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant
of 10)
...

Threads with higher priority are more important to a program and should be allocated processor time before lowerpriority threads
...


Create Thread by Implementing Runnable Interface:
If your class is intended to be executed as a thread then you can achieve this by implementingRunnable interface
...
This method provides entry
point for the thread and you will put you complete business logic inside this method
...


STEP 3
Once Thread object is created, you can start it by calling start( ) method, which executes a call to run( ) method
...
out
...
out
...
out
...

Thread
...
out
...
");
}
System
...
println("Thread " + threadName + " exiting
...
out
...
start ();
}
}
}
public class TestThread {
public static void main(String args[]) {
RunnableDemo R1 = new RunnableDemo( "Thread-1");
R1
...
start();
}
}
This would produce the following result:
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3

TUTORIALS POINT
Simply Easy Learning

Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting
...


Create Thread by Extending Thread Class:
The second way to create a thread is to create a new class that extends Thread class using the following two
simple steps
...


STEP 1
You will need to override run( ) method available in Thread class
...
Following is simple syntax of run() method:
public void run( )

STEP 2
Once Thread object is created, you can start it by calling start( ) method, which executes a call to run( ) method
...
out
...
out
...
out
...

Thread
...
out
...
");
}
System
...
println("Thread " + threadName + " exiting
...
out
...
start ();
}
}
}
public class TestThread {
public static void main(String args[]) {
ThreadDemo T1 = new ThreadDemo( "Thread-1");
T1
...
start();
}
}
This would produce the following result:
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting
...


Thread Methods:
Following is the list of important methods available in the Thread class
...


2

public void run()
If this Thread object was instantiated using a separate Runnable target, the run() method is invoked on that
Runnable object
...
There is also a getName() method for retrieving the name
...
The possible values are between 1 and 10
...


6

public final void join(long millisec)

TUTORIALS POINT
Simply Easy Learning

The current thread invokes this method on a second thread, causing the current thread to block until the
second thread terminates or the specified number of milliseconds passes
...


8

public final boolean isAlive()
Returns true if the thread is alive, which is any time after the thread has been started but before it runs to
completion
...
The following methods in the Thread class are
static
...

SN Methods with Description
1

public static void yield()
Causes the currently running thread to yield to any other threads of the same priority that are waiting to be
scheduled
...


3

public static boolean holdsLock(Object x)
Returns true if the current thread holds the lock on the given Object
...


5

public static void dumpStack()
Prints the stack trace for the currently running thread, which is useful when debugging a multithreaded
application
...
Consider a
class DisplayMessage which implements Runnable:
// File Name : DisplayMessage
...
message = message;
}
public void run()
{
while(true)
{
System
...
println(message);
}
}
}
Following is another class which extends Thread class:
// File Name : GuessANumber
...
number = number;
}
public void run()
{
int counter = 0;
int guess = 0;
do
{
guess = (int) (Math
...
out
...
getName()
+ " guesses " + guess);
counter++;
}while(guess != number);
System
...
println("** Correct! " + this
...
**");
}
}
Following is the main program which makes use of above defined classes:
// File Name : ThreadClassDemo
...
setDaemon(true);
thread1
...
out
...
");
thread1
...
setPriority(Thread
...
setDaemon(true);
System
...
println("Starting goodbye thread
...
start();
System
...
println("Starting thread3
...
start();
try
{
thread3
...
out
...
");
}
System
...
println("Starting thread4
...
start();
System
...
println("main() is ending
...
You can try this example again and again and you would get different result
every time
...

Starting goodbye thread
...


Major Java Multithreading Concepts:
While doing Multithreading programming in Java, you would need to have the following concepts very handy:






What is thread synchronization?
Handling threads inter communication
Handling thread deadlock
Major thread operations

What is Thread synchronization?
When we start two or more threads within a program, there may be a situation when multiple threads try to access
the same resource and finally they can produce unforeseen result due to concurrency issue
...

So there is a need to synchronize the action of multiple threads and make sure that only one thread can access the
resource at a given point in time
...
Each object in Java is
associated with a monitor, which a thread can lock or unlock
...

Java programming language provides a very handy way of creating threads and synchronizing their task by
using synchronized blocks
...
Following is the general form of the
synchronized statement:
synchronized(objectidentifier) {
// Access shared variables and other shared resources
}
Here, the objectidentifier is a reference to an object whose lock associates with the monitor that the synchronized
statement represents
...
When threads are not synchronized, they print counter value which is not in sequence, but when we print
counter by putting inside synchronized() block, then it prints counter very much in sequence for both the threads
...


TUTORIALS POINT
Simply Easy Learning

class PrintDemo {
public void printCount(){
try {
for(int i = 5; i > 0; i--) {
System
...
println("Counter
--" + i );
}
} catch (Exception e) {
System
...
println("Thread interrupted
...
printCount();
System
...
println("Thread " + threadName + " exiting
...
out
...
start ();
}
}
}
public class TestThread {
public static void main(String args[]) {
PrintDemo PD = new PrintDemo();
ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD );
ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD );
T1
...
start();
// wait for threads to end
try {
T1
...
join();
} catch( Exception e) {
System
...
println("Interrupted");
}
}
}
This produces different result every time you run this program:

TUTORIALS POINT
Simply Easy Learning

Starting Thread
Starting Thread
Counter
--Counter
--Counter
--Counter
--Counter
--Counter
--Counter
--Thread Thread Counter
--Counter
--Counter
--Thread Thread -

- 1
- 2
5
4
3
5
2
1
4
1 exiting
...


Multithreading example with Synchronization:
Here is the same example which prints counter value in sequence and every time we run it, it produces same result
...
out
...
out
...
");
}
}
}
class ThreadDemo extends Thread {
private Thread t;
private String threadName;
PrintDemo PD;
ThreadDemo( String name, PrintDemo pd){
threadName = name;
PD = pd;
}
public void run() {
synchronized(PD) {
PD
...
out
...
");
}
public void start ()
{
System
...
println("Starting " + threadName );
if (t == null)
{
t = new Thread (this, threadName);
t
...
start();
T2
...
join();
T2
...
out
...

5
4
3
2
1
2 exiting
...
Inter thread communication is important when you develop an application where two or more
threads exchange some information
...
First let's see all the
three methods listed below:
SN

Methods with Description

1

public void wait()
Causes the current thread to wait until another thread invokes the notify()
...


3

public void notifyAll()
Wakes up all the threads that called wait( ) on the same object
...
All
three methods can be called only from within a synchronized context
...
You can create a
complex system using the same concept
...
printStackTrace();
}
}
System
...
println(msg);
flag = true;
notify();
}
public synchronized void Answer(String msg) {
if (!flag) {
try {
wait();
} catch (InterruptedException e) {
e
...
out
...
m = m1;
new Thread(this, "Question")
...
length; i++) {
m
...
m = m2;

TUTORIALS POINT
Simply Easy Learning

new Thread(this, "Answer")
...
length; i++) {
m
...
com/questions/2170520/inter-threadcommunication-in-java]

Handling threads deadlock
Deadlock describes a situation where two or more threads are blocked forever, waiting for each other
...
A Java multithreaded program
may suffer from the deadlock condition because the synchronized keyword causes the executing thread to block
while waiting for the lock, or monitor, associated with the specified object
...
start();
T2
...
out
...
");
try { Thread
...
out
...
");
synchronized (Lock2) {
System
...
println("Thread 1: Holding lock 1 & 2
...
out
...
");
try { Thread
...
out
...
");
synchronized (Lock1) {
System
...
println("Thread 2: Holding lock 1 & 2
...

lock 2
...

for lock 1
...


Deadlock Solution Example:
Let's change the order of the lock and run the same program to see if still both the threads waits for each other:
public class TestThread {
public static Object Lock1 = new Object();
public static Object Lock2 = new Object();
public static void main(String args[]) {
ThreadDemo1 T1 = new ThreadDemo1();
ThreadDemo2 T2 = new ThreadDemo2();
T1
...
start();
}
private static class ThreadDemo1 extends Thread {
public void run() {
synchronized (Lock1) {
System
...
println("Thread 1: Holding lock 1
...
sleep(10); }
catch (InterruptedException e) {}
System
...
println("Thread 1: Waiting for lock 2
...
out
...
");
}
}
}
}
private static class ThreadDemo2 extends Thread {

TUTORIALS POINT
Simply Easy Learning

public void run() {
synchronized (Lock1) {
System
...
println("Thread 2: Holding lock 1
...
sleep(10); }
catch (InterruptedException e) {}
System
...
println("Thread 2: Waiting for lock 2
...
out
...
");
}
}
}
}
}
So just changing the order of the locks prevent the program in going deadlock situation and completes with the
following result:
Thread
Thread
Thread
Thread
Thread
Thread

1:
1:
1:
2:
2:
2:

Holding
Waiting
Holding
Holding
Waiting
Holding

lock 1
...

lock 1 & 2
...

for lock 2
...


Above example has been shown just for making you the concept clear, but its a more complex concept and you
should deep dive into it before you develop your applications to deal with deadlock situations
...
You can develop a multithreaded program
which can be suspended, resumed or stopped completely based on your requirements
...
Following table lists down those methods:
SN

Methods with Description

1

public void suspend()
This method puts a thread in suspended state and can be resumed using resume() method
...


3

public void resume()
This method resumes a thread which was suspended using suspend() method
...


5

public void notify()
Wakes up a single thread that is waiting on this object's monitor
...


Example:
class RunnableDemo implements Runnable {
public Thread t;
private String threadName;
boolean suspended = false;

TUTORIALS POINT
Simply Easy Learning

RunnableDemo( String name){
threadName = name;
System
...
println("Creating " + threadName );
}
public void run() {
System
...
println("Running " + threadName );
try {
for(int i = 10; i > 0; i--) {
System
...
println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while
...
sleep(300);
synchronized(this) {
while(suspended) {
wait();
}
}
}
} catch (InterruptedException e) {
System
...
println("Thread " + threadName + " interrupted
...
out
...
");
}
public void start ()
{
System
...
println("Starting " + threadName );
if (t == null)
{
t = new Thread (this, threadName);
t
...
start();
RunnableDemo R2 = new RunnableDemo( "Thread-2");
R2
...
sleep(1000);
R1
...
out
...
sleep(1000);
R1
...
out
...
suspend();
System
...
println("Suspending thread Two");
Thread
...
resume();

TUTORIALS POINT
Simply Easy Learning

System
...
println("Resuming thread Two");
} catch (InterruptedException e) {
System
...
println("Main thread Interrupted");
}
try {
System
...
println("Waiting for threads to finish
...
t
...
t
...
out
...
out
...
");
}
}
Here is the output produced by the above program:
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 10
Running Thread-2
Thread: Thread-2, 10
Thread: Thread-1, 9
Thread: Thread-2, 9
Thread: Thread-1, 8
Thread: Thread-2, 8
Thread: Thread-1, 7
Thread: Thread-2, 7
Suspending First Thread
Thread: Thread-2, 6
Thread: Thread-2, 5
Thread: Thread-2, 4
Resuming First Thread
Suspending thread Two
Thread: Thread-1, 6
Thread: Thread-1, 5
Thread: Thread-1, 4
Thread: Thread-1, 3
Resuming thread Two
Thread: Thread-2, 3
Waiting for threads to finish
...

Thread Thread-2 exiting
...


TUTORIALS POINT
Simply Easy Learning

CHAPTER

34
Java Applet Basics

A

n applet is a Java program that runs in a Web browser
...

There are some important differences between an applet and a standalone Java application, including the following:



An applet is a Java class that extends the java
...
Applet class
...




Applets are designed to be embedded within an HTML page
...




A JVM is required to view an applet
...




The JVM on the user's machine creates an instance of the applet class and invokes various methods during
the applet's lifetime
...
The security of an applet is often
referred to as sandbox security, comparing the applet to a child playing in a sandbox with various rules that
must be followed
...


Life Cycle of an Applet:
Four methods in the Applet class give you the framework on which you build any serious applet:





init: This method is intended for whatever initialization is needed for your applet
...

start: This method is automatically called after the browser calls the init method
...

stop: This method is automatically called when the user moves off the page on which the applet sits
...


TUTORIALS POINT
Simply Easy Learning





destroy: This method is only called when the browser shuts down normally
...

paint: Invoked immediately after the start() method, and also any time the applet needs to repaint itself in
the browser
...
awt
...
java:
import java
...
*;
import java
...
*;
public class HelloWorldApplet extends Applet
{
public void paint (Graphics g)
{
g
...
applet
...




java
...
Graphics
...


The Applet CLASS:
Every applet is an extension of the java
...
Applet class
...

These include methods that do the following:


Get applet parameters



Get the network location of the HTML file that contains the applet



Get the network location of the applet class directory



Print a status message in the browser



Fetch an image



Fetch an audio clip



Play an audio clip



Resize the applet

Additionally, the Applet class provides an interface by which the viewer or browser obtains information about the
applet and controls the applet's execution
...
Those implementations may be
overridden as necessary
...
The only method overridden is the paint method
...

The tag is the basis for embedding an applet in an HTML file
...
class" width="320" height="120">
If your browser was Java-enabled, a "Hello, World"
message would appear here
...

Applet Tag to understand more about calling applet from HTML
...
It specifies the Applet class to run
...
The applet directive must be closed with a
tag
...
The browser ignores text and other tags between the applet tags
...
Therefore, anything that appears between the
tags, not related to the applet, is visible in non-Java-enabled browsers
...
To specify otherwise, use
the codebase attribute of the tag as shown:

If an applet resides in a package other than the default, the holding package must be specified in the code attribute
using the period character (
...
For example:
parseSquareSize (squareSizeParam);
String colorParam = getParameter ("color");
Color fg = parseColor (colorParam);
setBackground (Color
...
parseInt (param);
}
catch(Exception e){
// Let default value remain
}
}
The applet calls parseSquareSize() to parse the squareSize parameter
...
parseInt(), which parses a string and returns an integer
...
parseInt() throws an exception whenever its
argument is invalid
...

The applet calls parseColor() to parse the color parameter into a Color value
...
You need to implement these
methods to make this applet works
...
The HTML file specifies both
parameters to the applet by means of the tag
...
class" width="480" height="320">






Note: Parameter names are not case sensitive
...

Here are the specific steps for converting an application to an applet
...




Supply a subclass of the JApplet class
...
Otherwise, the applet cannot be loaded
...
Do not construct a frame window for the application
...




Move any initialization code from the frame window constructor to the init method of the applet
...
the browser instantiates it for you and calls the init method
...




Remove the call to setDefaultCloseOperation
...




If the application calls setTitle, eliminate the call to the method
...
(You can, of
course, title the web page itself, using the HTML title tag
...
The applet is displayed automatically
...
The Container class defines several
methods, such as processKeyEvent and processMouseEvent, for handling particular types of events, and then one
catch-all method called processEvent
...

import
import
import
import

java
...
event
...
awt
...
MouseEvent;
java
...
Applet;
java
...
Graphics;

public class ExampleEventHandling extends Applet implements MouseListener{
StringBuffer strBuffer;
public void init(){
addMouseListener(this);
strBuffer =new StringBuffer();
addItem("initializing the apple ");
}
public void start(){
addItem("starting the applet ");
}
public void stop(){
addItem("stopping the applet ");
}
public void destroy(){
addItem("unloading the applet");
}
void addItem(String word){
System
...
println(word);
strBuffer
...

g
...

g
...
toString(),10,20);
}
public
}
public
}
public
}
public
}

void mouseEntered(MouseEvent event){
void mouseExited(MouseEvent event){
void mousePressed(MouseEvent event){
void mouseReleased(MouseEvent event){

TUTORIALS POINT
Simply Easy Learning

publicvoid mouseClicked(MouseEventevent){
addItem("mouse clicked! ");
}
}
Now, let us call this applet as follows:

Event Handling


...
Starting the applet
...

Based on the above examples, here is the live applet example: Applet

Example
...
To display an image within the applet, you
use the drawImage() method found in the java
...
Graphics class
...
applet
...
awt
...
net
...
getAppletContext();
String imageURL =this
...
jpg";
}
try
{
URL url =new URL(this
...
getImage(url);
}catch(MalformedURLException e)
{
e
...
showStatus("Could not load image!");
}
}
public void paint(Graphics g)
{
context
...
drawImage(image,0,0,200,84,null);
g
...
javalicense
...
class"width="300"height="200">
...


Playing Audio:
An applet can play an audio file represented by the AudioClip interface in the java
...
The AudioClip
interface has three methods, including:




public void play(): Plays the audio clip one time, from the beginning
...

public void stop(): Stops playing the audio clip
...
The getAudioClip()
method returns immediately, whether or not the URL resolves to an actual audio file
...

Following is the example showing all the steps to play an audio:
import java
...
*;
import java
...
*;
import java
...
*;
public class AudioDemo extends Applet
{
private AudioClip clip;
private AppletContext context;
public void init()
{
context =this
...
getParameter("audio");
if(audioURL ==null)
{
audioURL ="default
...
getDocumentBase(), audioURL);
clip = context
...
printStackTrace();
context
...
loop();

TUTORIALS POINT
Simply Easy Learning

}
}
publicvoid stop()
{
if(clip !=null)
{
clip
...
class"width="0"height="0">
...
wav at your PC to test the above example
...


// text

The compiler ignores everything from // to the end of the line
...
The JDK
javadoc tool uses doc comments when preparing automatically generated documentation
...
We will see how we can make use of Javadoc for generating useful
documentation for our Java code
...

Following is a simple example where red part of the code represents Java comments:
/**
* The HelloWorld program implements an application that
* simply displays "Hello World!" to the standard output
...
0
* @since
2014-03-31
*/
public class HelloWorld {
public static void main(String[] args) {
/* Prints Hello, World! on standard output
...
out
...
for heading and

has been used for creating paragraph break:

TUTORIALS POINT
Simply Easy Learning

/**
*

Hello, World!


* The HelloWorld program implements an application that
* simply displays "Hello World!" to the standard output
...

*
*
* @author Zara Ali
* @version 1
...

System
...
println("Hello World!");
}
}

The javadoc Tags:
The javadoc tool recognizes the following tags:
Tag

Description

Syntax

@author

Adds the author of a class
...


{@code text}

{@docRoot}

Represents the relative path to the generated document's root
directory from any generated page

{@docRoot}

@deprecated

Adds a comment indicating that this API should no longer be
used
...


@exception class-name
description

{@inheritDoc}

Inherits a comment from the nearest inheritable class or
implementable interface

Inherits a comment from the
immediate surperclass
...
T

{@link package
...


{@linkplain
package
...


@param parameter-name
description

@return

Adds a "Returns" section with the description text
...


@see reference

@serial

Used in the doc comment for a default serializable field
...


@serialField field-name fieldtype field-description

@since

Adds a "Since" heading with the specified since-text to the
generated documentation
...


@throws class-name description

{@value}

When {@value} is used in the doc comment of a static field, it
displays the value of that constant:

{@value package
...


@version version-text

Example:
Following program uses few of the important tags available for documentation comments
...

The documentation about the AddNum class will be produced in HTML file AddNum
...
html will also be created
...
io
...

*


* Note: Giving proper comments in your program makes it more
* user friendly and it is assumed as a high quality code
...
0
* @since
2014-03-31
*/
public class AddNum {
/**
* This method is used to add two integers
...

* @param numA This is the first paramter to addNum method
* @param numB This is the second parameter to addNum method
* @return int This returns sum of numA and numB
...

* @param args Unused
...

* @exception IOException On input error
...
addNum(10, 20);
System
...
println("Sum of 10 and 20 is :" + sum);
}
}
Now, process above AddNum
...
java
Loading source file AddNum
...

Constructing Javadoc information
...
7
...

Generating /AddNum
...

AddNum
...

Generating /package-frame
...

Generating /package-summary
...

Generating /package-tree
...

Generating /constant-values
...

Building index for all the packages and classes
...
html
...
html
...
html
...

Generating /allclasses-frame
...

Generating /allclasses-noframe
...

Generating /index
...

Generating /help-doc
...

1 warning
$
You can check all the generated documentation here: AddNum
...
7 then javadoc does not
generate a great stylesheet
...
oracle
...
css

TUTORIALS POINT
Simply Easy Learning

CHAPTER

36
Java Library Classes

T

his tutorial would cover package java
...
The most important classes are Object, which is the root of the class hierarchy,
and Class, instances of which represent classes at run time
...
lang
...

Click a class link to know more detail about that class
...

SN

Methods with Description

1

Boolean
Boolean

2

Byte
The Byte class wraps a value of primitive type byte in an object
...


4

Class
Instances of the class Class represent classes and interfaces in a running Java application
...


6

Compiler
The Compiler class is provided to support Java-to-native-code compilers and related services
...


8

Float
The Float class wraps a value of primitive type float in an object
...


10

Long
The Long class wraps a value of the primitive type long in an object
...


12

Number

TUTORIALS POINT
Simply Easy Learning

The abstract class Number is the superclass of classes BigDecimal, BigInteger, Byte, Double, Float, Integer,
Long, and Short
...


14

Package
Package objects contain version information about the implementation and specification of a Java package
...
exec methods create a native process and return an instance of a subclass of Process that can
be used to control the process and obtain information about it
...


17

RuntimePermission
This class is for runtime permissions
...


19

Short
The Short class wraps a value of primitive type short in an object
...
getStackTrace()
...


22

String
The String class represents character strings
...


24

System
The System class contains several useful class fields and methods
...


26

ThreadGroup
A thread group represents a set of threads
...


28

Throwable
The Throwable class is the superclass of all errors and exceptions in the Java language
...


TUTORIALS POINT
Simply Easy Learning


Title: learn java
Description: Beginning work online requires these rules